@linjz/opencode-qqbot 0.3.14 → 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.
- package/README.md +73 -5
- package/bin/openqq.js +34 -0
- package/dist/notify-cli.js +593 -0
- package/dist/opencode-qqbot-plugin.js +938 -65
- package/dist/openqq-bot.js +3585 -717
- package/dist/openqq-cli.js +791 -0
- package/dist/openqq-watchdog.js +1063 -0
- package/package.json +9 -5
- package/src/bridge.ts +1338 -157
- package/src/cli/notify-main.ts +6 -0
- package/src/cli/notify.ts +167 -0
- package/src/cli/openqq-main.ts +95 -0
- package/src/cli/service-main.ts +302 -0
- package/src/cli/watchdog-main.ts +77 -0
- package/src/commands.ts +644 -554
- package/src/config.ts +87 -2
- package/src/core/bot-control.ts +148 -0
- package/src/core/bot-launcher.ts +106 -13
- package/src/core/card-approval.ts +20 -9
- package/src/core/delivery.ts +145 -54
- package/src/core/discovery.ts +22 -4
- package/src/core/file-log.ts +35 -3
- package/src/core/form-bridge.ts +16 -7
- package/src/core/form-journal.ts +4 -4
- package/src/core/gateway-state.ts +3 -3
- package/src/core/inflight-journal.ts +214 -36
- package/src/core/instance-lock.ts +21 -6
- package/src/core/linkwatch.ts +3 -4
- package/src/core/markdown.ts +117 -0
- package/src/core/message-queue.ts +242 -91
- package/src/core/mirror.ts +222 -182
- package/src/core/notify-sink.ts +93 -0
- package/src/core/outbox.ts +10 -9
- package/src/core/permission.ts +627 -301
- package/src/core/question-form.ts +230 -0
- package/src/core/queue-view.ts +661 -0
- package/src/core/send-media.ts +32 -0
- package/src/core/storage.ts +34 -0
- package/src/core/watchdog.ts +513 -0
- package/src/core/zombie-reaper.ts +127 -0
- package/src/index.ts +140 -52
- package/src/opencode/client.ts +206 -27
- package/src/opencode/eventstream.ts +94 -12
- package/src/opencode/history.ts +4 -2
- package/src/opencode/mirror.ts +15 -2
- package/src/opencode/sessions.ts +135 -37
- package/src/plugin-entry.ts +120 -112
- package/src/qq/api.ts +165 -61
- package/src/qq/gateway.ts +80 -17
- package/src/qq/media.ts +5 -1
- package/src/qq/sender.ts +30 -18
- package/src/qq/types.ts +7 -0
package/src/bridge.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// @output: createBridge, isAllowedUser, milestoneTargets, loadWatchedMap, saveWatchedMap,
|
|
3
3
|
// (O7b 再导出)parsePermissionDecision, formatPermissionPrompt
|
|
4
4
|
// @pos: 根层 - 核心桥接: QQ 消息 -> OpenCode -> QQ 回复
|
|
5
|
+
import { storageFile } from "./core/storage.js"
|
|
5
6
|
import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs"
|
|
6
7
|
import { join } from "path"
|
|
7
8
|
import { homedir } from "os"
|
|
@@ -9,9 +10,20 @@ import type { Config } from "./config.js"
|
|
|
9
10
|
import type { MessageContext } from "./qq/types.js"
|
|
10
11
|
import { getAccessToken, sendC2CInputNotify, sendC2CMessage, sendGroupMessage } from "./qq/api.js"
|
|
11
12
|
import { prepareQQAttachments, augmentPromptWithAttachments, purgeOldQQImages } from "./qq/media.js"
|
|
12
|
-
import
|
|
13
|
-
import {
|
|
13
|
+
import { normalizeForCommandGate } from "./qq/gateway.js"
|
|
14
|
+
import type { OpencodeClient, SessionMessage, PermissionRequest } from "./opencode/client.js"
|
|
15
|
+
import {
|
|
16
|
+
decideReap,
|
|
17
|
+
decideDispatchStall,
|
|
18
|
+
sessionExistsFromProbeError,
|
|
19
|
+
DISPATCH_STALL_MS,
|
|
20
|
+
REAPER_MIN_AGE_MS,
|
|
21
|
+
REAPER_SILENCE_MS,
|
|
22
|
+
resolveReaperMs,
|
|
23
|
+
} from "./core/zombie-reaper.js"
|
|
24
|
+
import { SupersededError, turnStateOf } from "./opencode/client.js"
|
|
14
25
|
import { createEventStream, type V2Event } from "./opencode/eventstream.js"
|
|
26
|
+
|
|
15
27
|
import { summarizeInput, redactSecrets } from "./opencode/history.js"
|
|
16
28
|
import { SessionManager } from "./opencode/sessions.js"
|
|
17
29
|
import {
|
|
@@ -20,41 +32,68 @@ import {
|
|
|
20
32
|
handlePendingSelection,
|
|
21
33
|
isCommand,
|
|
22
34
|
type CommandContext,
|
|
35
|
+
type LedgerApi,
|
|
23
36
|
type MirrorApi,
|
|
24
37
|
type PendingSelection,
|
|
25
38
|
type WatchApi,
|
|
26
39
|
} from "./commands.js"
|
|
27
40
|
import { createMirror } from "./core/mirror.js"
|
|
28
|
-
import { MessageQueue, previewText, agoLabel, intentKeyOf } from "./core/message-queue.js"
|
|
41
|
+
import { MessageQueue, laneKeyOf, laneScope, sessionIdOfLane, userIdOfLane, previewText, agoLabel, intentKeyOf } from "./core/message-queue.js"
|
|
29
42
|
import { classifyProviderError, rescueText } from "./core/error-rescue.js"
|
|
30
43
|
|
|
31
44
|
const QUEUE_MAX = 20 // Q1:忙碌队列上限(学习 pi-qqbot queue.max 默认)
|
|
45
|
+
// 2026-11-05:队列完成回执("队列 #N 完成(剩余 M 条)")默认关闭——批量排空时
|
|
46
|
+
// 会放大主动消息配额消耗;排障/验收期设 QQ_QUEUE_RECEIPTS=1 打开。
|
|
47
|
+
const QUEUE_RECEIPTS_ENABLED = /^(1|true|on)$/i.test(process.env.QQ_QUEUE_RECEIPTS ?? "")
|
|
32
48
|
import {
|
|
33
49
|
createPermissionGate,
|
|
50
|
+
createPushGate,
|
|
51
|
+
resolvePermDeferMs,
|
|
34
52
|
parsePermissionDecision,
|
|
35
53
|
formatPermissionPrompt,
|
|
54
|
+
formatPermissionConflictNotice,
|
|
36
55
|
DECISION_LABELS,
|
|
56
|
+
type PermOrigin,
|
|
37
57
|
} from "./core/permission.js"
|
|
38
58
|
import { truncate } from "./core/util.js"
|
|
39
|
-
import { createDelivery } from "./core/delivery.js"
|
|
59
|
+
import { createDelivery, QQ_LIST_FORMAT_HINT } from "./core/delivery.js"
|
|
60
|
+
import { createNotifySink } from "./core/notify-sink.js"
|
|
40
61
|
import { handleApprovalInteraction, sendApprovalCard } from "./core/card-approval.js"
|
|
41
62
|
import { createFormBridge, renderFormPrompt } from "./core/form-bridge.js"
|
|
42
63
|
import { recordMessage, resolveQuote, scopeKeyOf, extractEmbeddedQuote } from "./core/context-buffer.js"
|
|
43
64
|
import {
|
|
44
|
-
|
|
45
|
-
recordInflight,
|
|
46
|
-
settleInflight,
|
|
47
|
-
pendingInflight,
|
|
65
|
+
createInflightJournal,
|
|
48
66
|
classifyInflight,
|
|
49
|
-
markInflightPromptId,
|
|
50
67
|
INFLIGHT_MAX_AGE_MS,
|
|
51
68
|
redispatchMaxAgeMs,
|
|
69
|
+
type InflightEntry,
|
|
70
|
+
type SettleReason,
|
|
52
71
|
} from "./core/inflight-journal.js"
|
|
72
|
+
import {
|
|
73
|
+
deriveQueueView,
|
|
74
|
+
resolveOrphanMs,
|
|
75
|
+
resolveLedgerNumericArg,
|
|
76
|
+
decideOrphanNotify,
|
|
77
|
+
type OrphanNotifyState,
|
|
78
|
+
formatQueueReply,
|
|
79
|
+
formatQueueFullReceipt,
|
|
80
|
+
formatLedgerReply,
|
|
81
|
+
formatStatusLine,
|
|
82
|
+
shortId,
|
|
83
|
+
type QueueView,
|
|
84
|
+
} from "./core/queue-view.js"
|
|
53
85
|
import { messageFingerprint } from "./core/inbound-dedupe.js"
|
|
86
|
+
import { isPidAlive } from "./core/watchdog.js"
|
|
54
87
|
import { extractSendFileMarkers, sendLocalFile } from "./core/send-media.js"
|
|
55
88
|
import type { InteractionEvent } from "./qq/types.js"
|
|
56
89
|
// O7b:解析/格式化保持经 bridge 再导出——单测与既有调用方导入路径不变
|
|
57
|
-
export { parsePermissionDecision, formatPermissionPrompt } from "./core/permission.js"
|
|
90
|
+
export { parsePermissionDecision, formatPermissionPrompt, formatPermissionConflictNotice } from "./core/permission.js"
|
|
91
|
+
|
|
92
|
+
/** 会话正有 active prompt(-32603,他端/桌面端并发占用)判定(纯函数,导出供测试)。 */
|
|
93
|
+
export function isSessionBusyError(error: unknown): boolean {
|
|
94
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
95
|
+
return /active prompt|[-−]32603/.test(message)
|
|
96
|
+
}
|
|
58
97
|
|
|
59
98
|
// E 闲置回收纯函数(导出供测试,2026-10-29):返回应回收的闲置会话 id——
|
|
60
99
|
// 超过 idleMs 无活动且未被 /watch 显式盯住的会话。
|
|
@@ -110,7 +149,199 @@ export function stallNudgeDecision(
|
|
|
110
149
|
return now - base >= need ? "nudge" : "wait"
|
|
111
150
|
}
|
|
112
151
|
|
|
113
|
-
|
|
152
|
+
// 停滞提醒数据快照(2026-11-09 立规,导出供测试):一次取齐「展示用」执行/空闲分钟,
|
|
153
|
+
// 再返回下一次间隔的基准。顺序错乱会产出「执行 69 分钟|已 0 分钟无进展」这类假数据
|
|
154
|
+
//(2026-11-09 事故实证:先置 lastProgressAt=now 再计算 idleMin)。
|
|
155
|
+
export function stallSnapshot(
|
|
156
|
+
now: number,
|
|
157
|
+
lastProgressAt: number,
|
|
158
|
+
turnStartedAt: number,
|
|
159
|
+
): { idleMin: number; execMin: number; nextProgressAt: number } {
|
|
160
|
+
return {
|
|
161
|
+
idleMin: Math.max(0, Math.round((now - lastProgressAt) / 60_000)),
|
|
162
|
+
execMin: Math.max(0, Math.round((now - turnStartedAt) / 60_000)),
|
|
163
|
+
nextProgressAt: now,
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ===== 后台进度心跳(2026-11-10 owner 裁定方案 A:长任务过程可见性)=====
|
|
168
|
+
// 背景:停滞提醒只在「零进展」时触发——活跃的长任务全程零可见(昨晚 69 分钟报告实证),
|
|
169
|
+
// 用户体验=「任务一下子没了」。裁定:转后台后每 15min 推送一条进度心跳,不设次数上限
|
|
170
|
+
// (直至完成/24h 放弃);内容与停滞自检合流——心跳内联「无进展分钟」,任务假活时
|
|
171
|
+
// 用户从心跳文案即可看出;停滞提醒仍独立触发(同 tick 内提醒优先,避免双发)。
|
|
172
|
+
export const BG_HEARTBEAT_MS = 15 * 60_000
|
|
173
|
+
|
|
174
|
+
/** 心跳决策:距上次心跳(或挂起起点)满 interval 即推送。纯函数供测试。 */
|
|
175
|
+
export function heartbeatDecision(lastHeartbeatAt: number, now: number, intervalMs: number = BG_HEARTBEAT_MS): "beat" | "wait" {
|
|
176
|
+
return now - lastHeartbeatAt >= intervalMs ? "beat" : "wait"
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 心跳文案:进行中 + 已运行 + 最近动作 + 内联停滞自检(idle≥30min 明示疑似停滞)。纯函数供测试。 */
|
|
180
|
+
export function heartbeatText(execMin: number, idleMin: number, lastAction?: string): string {
|
|
181
|
+
const action = lastAction ? `,刚才在处理【${lastAction}】` : ""
|
|
182
|
+
const stale = idleMin >= 30 ? `。⚠️ 注意:已 ${idleMin} 分钟没有任何动静,疑似卡住——可发 /stop 中止后重发` : ""
|
|
183
|
+
return `⏳ 你的任务还在后台执行:已用时 ${execMin} 分钟${action}${stale}。完成后我会自动把结果发给你。`
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ===== 无 idle 兜底(2026-11-10 僵尸心跳事故根修)=====
|
|
187
|
+
// 事故链:同一 msgId 被重复派发(08:43/08:47)→ 第二次 prompt 按接管语义打断第一次回合 →
|
|
188
|
+
// 该回合随后又被新消息接管致死——被杀的回合永远不产生 idle 行 → 完成检查 hasIdle 恒 false →
|
|
189
|
+
// 后台等待僵尸化 39 分钟假心跳(09:13/09:29 实证)。口径修正:「边界内有正文」即回合实质已完
|
|
190
|
+
// (与防线 A 同原则)——正文在但 idle 缺失且超过宽限期 → 按完成投递。
|
|
191
|
+
export const MISSING_IDLE_GRACE_MS = 10 * 60_000
|
|
192
|
+
|
|
193
|
+
/** 无-idle 完成判定:有正文 + 超过宽限期无新进展。纯函数供测试。 */
|
|
194
|
+
export function missingIdleDone(
|
|
195
|
+
turn: { hasIdle: boolean; text: string },
|
|
196
|
+
lastProgressAt: number,
|
|
197
|
+
now: number,
|
|
198
|
+
graceMs: number = MISSING_IDLE_GRACE_MS,
|
|
199
|
+
): boolean {
|
|
200
|
+
return !turn.hasIdle && Boolean(turn.text) && now - lastProgressAt >= graceMs
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ===== 后台流活性监督(2026-11-19 owner 裁定:与后台探知同 tick 执行)=====
|
|
204
|
+
// 背景:死回合(SSE 断连/提供商悬挂)与长跑任务在「消息无进展」信号上同形,
|
|
205
|
+
// bot 观测不到「模型是否还在生成」——昨夜 BG101A 实证:首 token 后 3 秒流停止,
|
|
206
|
+
// 90 分钟零产出无终结,心跳却在如实报「还在执行」。本层补上判别器:
|
|
207
|
+
// 判死 = 锚定边界内 assistant 最后活动(streamed 或 created)超阈值
|
|
208
|
+
// 且回合未终结(idle/全部 completed 归完成判据管)。
|
|
209
|
+
// 工具豁免(有界):工具执行中(tool state=running)streamed 必然冻结是健康形态——
|
|
210
|
+
// 但卡死的工具 part 同样恒 running(BG101A 实证:question 工具悬挂 2.5h),故豁免
|
|
211
|
+
// 只保活到 QQ_BG_TOOL_GRACE_MS(默认 60min,覆盖 2100s 睡眠类长工具),超时照样判死。
|
|
212
|
+
// 处置(owner 裁定「先关而后断点继续」):session.abort 死回合 →
|
|
213
|
+
// 续作(同会话新回合重发原 prompt,单任务上限 3 次)/ 超限 expired 结清 + 放行队列。
|
|
214
|
+
// 阈值 env QQ_BG_STREAM_DEAD_MS(合法域 1min~60min),默认 15min——
|
|
215
|
+
// 须大于健康工具调用间隙、小于僵尸收割 40min 年龄门。
|
|
216
|
+
export const BG_STREAM_DEAD_MS_DEFAULT = 15 * 60_000
|
|
217
|
+
export const BG_TOOL_GRACE_MS_DEFAULT = 60 * 60_000
|
|
218
|
+
|
|
219
|
+
export function resolveStreamDeadMs(envValue: string | undefined): number {
|
|
220
|
+
const raw = Number(envValue ?? "")
|
|
221
|
+
return Number.isFinite(raw) && raw >= 60_000 && raw <= 3_600_000 ? Math.floor(raw) : BG_STREAM_DEAD_MS_DEFAULT
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** 工具豁免窗解析(纯函数供测试):默认 60min,合法域 5min 至 4h;不得小于健康长工具实测(2100s 睡眠)。 */
|
|
225
|
+
export function resolveToolGraceMs(envValue: string | undefined): number {
|
|
226
|
+
if (envValue === undefined || envValue.trim() === "") return BG_TOOL_GRACE_MS_DEFAULT
|
|
227
|
+
const raw = Number(envValue)
|
|
228
|
+
return Number.isFinite(raw) && raw >= 300_000 && raw <= 14_400_000 ? Math.floor(raw) : BG_TOOL_GRACE_MS_DEFAULT
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export type StreamLiveness = "alive" | "dead" | "none"
|
|
232
|
+
|
|
233
|
+
/** 续作上限解析(纯函数供测试):env QQ_BG_RESUME_MAX,默认 3 次;0=关闭自动续作;合法域 0 至 5。 */
|
|
234
|
+
export function resolveResumeMax(envValue: string | undefined): number {
|
|
235
|
+
// 注意 Number("")===0——必须先判空再 Number(resolvePermDeferMs 同款陷阱注释)
|
|
236
|
+
if (envValue === undefined || envValue.trim() === "") return 3
|
|
237
|
+
const raw = Number(envValue)
|
|
238
|
+
return Number.isFinite(raw) && raw >= 0 && raw <= 5 ? Math.floor(raw) : 3
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** 续作决策(纯函数供测试):已消耗次数 < 上限 → 续作;否则 giveup 交 finishDead。 */
|
|
242
|
+
export function resumeDecision(resumeCount: number, max: number): "resume" | "giveup" {
|
|
243
|
+
return max > 0 && resumeCount < max ? "resume" : "giveup"
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* 流活性判定(纯函数供测试)。msgs=同一次后台探知的拉取结果;
|
|
248
|
+
* promptId/baseline=本回合锚点(与 turnStateOf 同口径)。
|
|
249
|
+
* none=边界内无 assistant 消息(等待模型开始,归停滞提醒管)。
|
|
250
|
+
*/
|
|
251
|
+
export function streamLiveness(
|
|
252
|
+
msgs: SessionMessage[],
|
|
253
|
+
promptId: string,
|
|
254
|
+
baseline: number,
|
|
255
|
+
now: number,
|
|
256
|
+
deadMs: number,
|
|
257
|
+
/** 工具豁免窗(默认 60min):工具执行中 streamed 冻结属健康,但卡死工具 part 也恒 running——豁免有界。 */
|
|
258
|
+
toolGraceMs: number = BG_TOOL_GRACE_MS_DEFAULT,
|
|
259
|
+
): StreamLiveness {
|
|
260
|
+
const turn = turnStateOf(msgs, promptId, baseline)
|
|
261
|
+
// 完成判据优先:有 idle 或全部 assistant 已终结 → 不归活性监督
|
|
262
|
+
if (turn.hasIdle) return "alive"
|
|
263
|
+
const ordered = [...msgs].sort((a, b) => (a.time?.created ?? 0) - (b.time?.created ?? 0))
|
|
264
|
+
// 回合边界(与 turnStateOf 同构:promptId 精确锚 > 200ms 时间锚)
|
|
265
|
+
let startIdx = 0
|
|
266
|
+
if (turn.anchored) {
|
|
267
|
+
let userIdx = ordered.findIndex((m) => m.type === "user" && m.id === promptId)
|
|
268
|
+
if (userIdx < 0 && baseline > 0) {
|
|
269
|
+
let best = -1
|
|
270
|
+
let bestDelta = Number.POSITIVE_INFINITY
|
|
271
|
+
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
272
|
+
if (ordered[i].type !== "user") continue
|
|
273
|
+
const delta = Math.abs((ordered[i].time?.created ?? 0) - baseline)
|
|
274
|
+
if (delta < bestDelta) { bestDelta = delta; best = i }
|
|
275
|
+
}
|
|
276
|
+
if (best >= 0 && bestDelta <= 200) userIdx = best
|
|
277
|
+
}
|
|
278
|
+
startIdx = userIdx >= 0 ? userIdx + 1 : 0
|
|
279
|
+
}
|
|
280
|
+
let latestActivity = 0
|
|
281
|
+
let anyUncompleted = false
|
|
282
|
+
let anyRunningTool = false
|
|
283
|
+
for (let i = startIdx; i < ordered.length; i++) {
|
|
284
|
+
const m = ordered[i]
|
|
285
|
+
if (m.type !== "assistant") continue
|
|
286
|
+
if (!turn.anchored && (m.time?.created ?? 0) < baseline) continue
|
|
287
|
+
const activity = m.time?.streamed ?? m.time?.created ?? 0
|
|
288
|
+
if (activity > latestActivity) latestActivity = activity
|
|
289
|
+
if (!m.time?.completed) anyUncompleted = true
|
|
290
|
+
for (const p of [...(m.parts ?? []), ...(m.content ?? [])] as Array<{ type?: string; state?: { status?: string } }>) {
|
|
291
|
+
if ((p.type === "tool" || p.type === undefined) && p.state?.status === "running") anyRunningTool = true
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (latestActivity === 0) return "none"
|
|
295
|
+
if (!anyUncompleted) return "alive"
|
|
296
|
+
// 工具豁免(有界):running 工具只在豁免窗内保活;窗外与无工具同口径按流陈旧度判死
|
|
297
|
+
//(卡死工具 part 恒 running——BG101A 实证 question 工具悬挂 2.5h,无界豁免=永远假活)。
|
|
298
|
+
if (anyRunningTool && now - latestActivity < toolGraceMs) return "alive"
|
|
299
|
+
return now - latestActivity >= deadMs ? "dead" : "alive"
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ===== 终稿提取(2026-11-10 工作稿误投事故根修)=====
|
|
303
|
+
// 事故:owner 收到「📤…结果如下:更新测试(新文案+missingIdleDone 用例):」——那是被打断回合
|
|
304
|
+
// 的【工作稿】(同消息文本段后带工具段),不是答案。口径:同消息含工具段=工作稿,不作答案投递;
|
|
305
|
+
// 只取边界内最后一条「纯文本 assistant 消息」;一条都没有=未产出,走 superseded 如实交代。
|
|
306
|
+
function assistantTextOf(m: SessionMessage): string {
|
|
307
|
+
return (m.content ?? [])
|
|
308
|
+
.filter((p) => p.type === "text" && p.text?.trim())
|
|
309
|
+
.map((p) => p.text ?? "")
|
|
310
|
+
.join("\n")
|
|
311
|
+
.trim()
|
|
312
|
+
}
|
|
313
|
+
function hasToolPart(m: SessionMessage): boolean {
|
|
314
|
+
return (m.parts ?? []).some((p) => p.type === "tool") || (m.content ?? []).some((p) => p.type === "tool")
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function finalAnswerText(msgs: SessionMessage[], promptId: string, baseline: number): string {
|
|
318
|
+
const ordered = [...msgs].sort((a, b) => (a.time?.created ?? 0) - (b.time?.created ?? 0))
|
|
319
|
+
let userIdx = promptId ? ordered.findIndex((m) => m.type === "user" && m.id === promptId) : -1
|
|
320
|
+
if (userIdx < 0 && baseline > 0) {
|
|
321
|
+
let best = -1
|
|
322
|
+
let bestDelta = Number.POSITIVE_INFINITY
|
|
323
|
+
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
324
|
+
if (ordered[i].type !== "user") continue
|
|
325
|
+
const delta = Math.abs((ordered[i].time?.created ?? 0) - baseline)
|
|
326
|
+
if (delta < bestDelta) { bestDelta = delta; best = i }
|
|
327
|
+
}
|
|
328
|
+
if (best >= 0 && bestDelta <= 200) userIdx = best
|
|
329
|
+
}
|
|
330
|
+
const inBoundary = (m: SessionMessage, idx: number): boolean => {
|
|
331
|
+
if (userIdx >= 0) return idx > userIdx
|
|
332
|
+
return (m.time?.created ?? 0) >= baseline
|
|
333
|
+
}
|
|
334
|
+
let text = ""
|
|
335
|
+
for (let i = 0; i < ordered.length; i++) {
|
|
336
|
+
const m = ordered[i]
|
|
337
|
+
if (m.type !== "assistant" || !inBoundary(m, i)) continue
|
|
338
|
+
const t = assistantTextOf(m)
|
|
339
|
+
if (t && !hasToolPart(m)) text = t // 工作稿(含工具段)跳过
|
|
340
|
+
}
|
|
341
|
+
return text
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export interface Bridge {
|
|
114
345
|
handleMessage: (ctx: MessageContext) => Promise<void>
|
|
115
346
|
// HC2(2026-10-26):暴露事件流句柄,index 侧链路自愈巡检需对其热换基
|
|
116
347
|
eventStream: ReturnType<typeof createEventStream>
|
|
@@ -124,14 +355,34 @@ export function createBridge(
|
|
|
124
355
|
config: Config,
|
|
125
356
|
client: OpencodeClient,
|
|
126
357
|
sessions: SessionManager,
|
|
358
|
+
/** 多角色(2026-11-17):本 bridge 所属角色的 appId。传入后所有角色作用域
|
|
359
|
+
* 数据文件(台账/审批/表单/配额/观察/问候)落 ~/.openqq/roles/<appId>/;
|
|
360
|
+
* 缺省 = legacy 全局路径,单角色部署行为零变化。 */
|
|
361
|
+
storageAppId?: string,
|
|
127
362
|
): Bridge {
|
|
363
|
+
// 角色作用域数据根(storage.ts:legacy 根 or roles/<appId>/ 子目录)
|
|
364
|
+
const roleFile = (name: string): string => storageFile(name, storageAppId)
|
|
365
|
+
// 在途台账按角色绑定实例(同进程多角色并发不互踩,见 inflight-journal 工厂)
|
|
366
|
+
const inflight = createInflightJournal(storageAppId ? roleFile("inflight.json") : undefined)
|
|
128
367
|
// H2 停滞提醒文案状态开关就用现成 env 读取风格;这里同步实现⑦开关——
|
|
129
368
|
// 2026-11-03 用户拍板:「已收到」回执默认不发(非调试无价值),调试期在
|
|
130
369
|
// ~/.openqq/.env 设 QQ_ACK_RECEIPT=1 开启。loadEnvFile 全量注入 process.env,
|
|
131
370
|
// 排队回执「已排队 #N」为功能性提示不受此开关影响。
|
|
132
371
|
const ackReceiptEnabled = /^(1|true|on)$/i.test(process.env.QQ_ACK_RECEIPT ?? "")
|
|
133
372
|
|
|
373
|
+
// 会话隔离(owner 2026-11-14 裁定,DEF-qqbot-20261112-01 修法①):
|
|
374
|
+
// busyUsers/draining 存 lane 键(userId|sessionId)——官方 per-peer 串行的会话级
|
|
375
|
+
// 细腻化;僵尸/长回合只堵所在 lane。票号仍 per-user 单调(message-queue 内)。
|
|
134
376
|
const busyUsers = new Set<string>()
|
|
377
|
+
const laneOf = (userId: string, sessionId: string | null | undefined): string => laneKeyOf(userId, sessionId)
|
|
378
|
+
/** 该用户是否有任一 lane 在忙(/status 展示用) */
|
|
379
|
+
const anyLaneBusy = (userId: string): boolean => {
|
|
380
|
+
for (const k of busyUsers) if (userIdOfLane(k) === userId) return true
|
|
381
|
+
return false
|
|
382
|
+
}
|
|
383
|
+
/** 出站推送门(design §3.4):QQ 只呈现当前绑定会话——锚定≠绑定即不推 */
|
|
384
|
+
const isBoundSession = (userId: string, sessionId: string): boolean =>
|
|
385
|
+
sessions.getSession(userId)?.sessionId === sessionId
|
|
135
386
|
// 队列 drain 会重入 handleMessage;标记本 ctx 已认领,避免把合法出队当成平台重投。
|
|
136
387
|
const claimedContexts = new WeakSet<MessageContext>()
|
|
137
388
|
// 修复⑦:队列 drain 重入的 ctx——受理回执跳过(drain 已有「开始执行队列」节点,
|
|
@@ -142,16 +393,22 @@ export function createBridge(
|
|
|
142
393
|
// Q1:忙碌消息队列(该用户当前回合结束后自动 drain)
|
|
143
394
|
const msgQueue = new MessageQueue(QUEUE_MAX)
|
|
144
395
|
const draining = new Set<string>()
|
|
396
|
+
// 队列 drain 重入的 ctx → 队列编号(完成回执/诊断用;WeakMap 不阻回收)
|
|
397
|
+
const queueIdOfCtx = new WeakMap<MessageContext, number>()
|
|
145
398
|
// Persist greeted users to disk so restarting the bot doesn't re-send the
|
|
146
399
|
// full command list to every user on their next message.
|
|
147
|
-
const greeted = loadGreetedSet()
|
|
400
|
+
const greeted = loadGreetedSet(storageAppId ? roleFile("greeted.json") : undefined)
|
|
148
401
|
const pendingSelections = new Map<string, PendingSelection>()
|
|
149
402
|
|
|
150
403
|
// ===== 实时观察 / 回合过程推送 =====
|
|
151
404
|
// 单条 SSE 连接按 sessionID 分流,多订阅者共享(同会话同 userId Set 去重不双发)。
|
|
152
405
|
// 里程碑投递 = /watch 专属(2026-10-14 拍板);sessionSubs 只管 SSE 活性与去重。
|
|
153
406
|
const eventStream = createEventStream(client.baseUrl)
|
|
154
|
-
|
|
407
|
+
// 弹卡延迟窗(owner 2026-11-10 拍板,QQ_PERM_DEFER_MS 可调):桌面端 autoApprove 实测
|
|
408
|
+
// 20~500ms 内秒回 once——asked 后延迟判定,窗口内被处置的 ask 不推 QQ 卡(与桌面静默放行一致)。
|
|
409
|
+
const PERM_DEFER_MS = resolvePermDeferMs(process.env.QQ_PERM_DEFER_MS)
|
|
410
|
+
const permPushGate = createPushGate(PERM_DEFER_MS)
|
|
411
|
+
const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
|
|
155
412
|
const sessionUnsubs = new Map<string, () => void>() // sessionID -> SSE 退订
|
|
156
413
|
const activeWatches = new Map<string, string>() // userId -> sessionID(/watch 显式订阅)
|
|
157
414
|
const lastCtx = new Map<string, MessageContext>() // userId -> 最近消息 ctx(推送通道选择依据)
|
|
@@ -226,7 +483,7 @@ export function createBridge(
|
|
|
226
483
|
if (!line) return
|
|
227
484
|
// 2026-10-14 用户拍板:里程碑只投 /watch 显式订阅者——自身回合回显与
|
|
228
485
|
// 会话订阅表的其他来源一律不再隐式携带(镜像只发📋摘要卡)。
|
|
229
|
-
for (const userId of milestoneTargets(activeWatches, sessionID)) enqueuePush(userId, line)
|
|
486
|
+
for (const userId of milestoneTargets(activeWatches, sessionID)) enqueuePush(userId, line, sessionID)
|
|
230
487
|
}
|
|
231
488
|
|
|
232
489
|
// ===== 摘要镜像域已随 O7d 收进 core/mirror.ts(订阅/在途标记/解锁/摘要投递)=====
|
|
@@ -235,7 +492,10 @@ export function createBridge(
|
|
|
235
492
|
// SSE execution.succeeded 即时触发 + 5 分钟轮询兜底(防 SSE 断连漏事件),
|
|
236
493
|
// 上限 24 小时。用户在同一会话发起新回合时被取代(避免同一结果投递两次)。
|
|
237
494
|
const BG_WAIT_MAX_MS = 24 * 60 * 60 * 1000
|
|
238
|
-
|
|
495
|
+
// P0-1(2026-11-09 69 分钟答案丢失事故):完成检测 = SSE 即时 + 轮询兜底。
|
|
496
|
+
// 轮询从 5min 收紧到 1min——SSE 断连窗口内完成判定最坏延迟 5min→1min,
|
|
497
|
+
// 与「新输入接管(cancel)」竞态的丢失窗口同步收窄。
|
|
498
|
+
const BG_POLL_MS = 60_000
|
|
239
499
|
|
|
240
500
|
// H2(2026-10-30,昨晚卡死事故复盘):桌面审批/选择弹窗对 bot 无通道(V2 无
|
|
241
501
|
// question API,C 项已证伪)——共享会话会被"桌面弹窗挂起"传导性卡死,且静默。
|
|
@@ -244,15 +504,39 @@ export function createBridge(
|
|
|
244
504
|
const STALL_NUDGE_INTERVAL_MS = 30 * 60 * 1000
|
|
245
505
|
const STALL_NUDGE_MAX = 3
|
|
246
506
|
|
|
247
|
-
function startBackgroundWait(
|
|
507
|
+
function startBackgroundWait(
|
|
508
|
+
sessionId: string,
|
|
509
|
+
ctx: MessageContext,
|
|
510
|
+
baseline: number,
|
|
511
|
+
trackId?: string,
|
|
512
|
+
promptId = "",
|
|
513
|
+
turnStartedAt?: number,
|
|
514
|
+
/** DEF-20261112-1 权限链目录:续作重派 promptAndWait 的 x-opencode-directory(缺省=裸查旧行为) */
|
|
515
|
+
anchorDirectory?: string,
|
|
516
|
+
/** 续作次数初值:启动对账重挂时从台账 resumeCount 续算(重启不洗白 owner 上限裁定) */
|
|
517
|
+
resumeCountInitial = 0,
|
|
518
|
+
): void {
|
|
248
519
|
// 同会话只允许一个后台等待:恢复多条在途账/超时重挂不得留下多个完成回调重复投递。
|
|
249
520
|
bgWaits.get(sessionId)?.cancel()
|
|
521
|
+
// 流活性监督阈值(env 惰性读取:.env 运行时才注入;owner 2026-11-19 裁定层)
|
|
522
|
+
const STREAM_DEAD_MS = resolveStreamDeadMs(process.env.QQ_BG_STREAM_DEAD_MS)
|
|
523
|
+
const TOOL_GRACE_MS = resolveToolGraceMs(process.env.QQ_BG_TOOL_GRACE_MS)
|
|
524
|
+
// 死回合自动续作上限(owner 2026-11-19 裁定:单任务续作不能超过三次;0=关闭)
|
|
525
|
+
const MAX_RESUME = resolveResumeMax(process.env.QQ_BG_RESUME_MAX)
|
|
526
|
+
let resumeCount = resumeCountInitial
|
|
250
527
|
let cancelled = false
|
|
251
528
|
let finished = false
|
|
252
529
|
const startedAt = Date.now()
|
|
530
|
+
// 2026-11-09 修正:执行时长按「回合真实起点」展示(跨重启用台账 at),
|
|
531
|
+
// 重启不再把 69 分钟的任务显示成 30 分钟;停滞提醒的调度仍从本次挂起算起,
|
|
532
|
+
// 避免重启后立刻对健康回合误报停滞。
|
|
533
|
+
const execStartAt = turnStartedAt && turnStartedAt > 0 ? turnStartedAt : startedAt
|
|
253
534
|
let lastProgressAt = startedAt
|
|
254
535
|
let nudges = 0
|
|
255
536
|
let lastMarker = ""
|
|
537
|
+
let lastHeartbeatAt = startedAt // 方案 A:进度心跳调度起点
|
|
538
|
+
let probeFails = 0 // 服务不可达计数(≥5 一次性告警)
|
|
539
|
+
let unreachableAlerted = false
|
|
256
540
|
|
|
257
541
|
const cleanup = (): void => {
|
|
258
542
|
cancelled = true
|
|
@@ -260,28 +544,61 @@ export function createBridge(
|
|
|
260
544
|
clearInterval(pollTimer)
|
|
261
545
|
clearTimeout(giveupTimer)
|
|
262
546
|
bgWaits.delete(sessionId)
|
|
263
|
-
//
|
|
264
|
-
|
|
547
|
+
// 被新回合取代(cancel 路径)时结清旧账——否则后台空账永久残留:安全重启
|
|
548
|
+
// 永远等不到空闲、重启恢复会误重挂/补投旧答案(2026-11-05 实证两条僵尸账)。
|
|
549
|
+
// finish 路径会先置 finished=true 并按 answered/expired 结清,此处不再覆盖。
|
|
550
|
+
if (!finished && trackId) {
|
|
551
|
+
// P0-1(2026-11-09 69 分钟答案丢失事故根修):接管前必须先核实旧回合是否
|
|
552
|
+
// 「已完成未投递」——旧实现直接 superseded 销账,完成于竞态窗口内的答案
|
|
553
|
+
//(如长报告)会被无声丢弃(用户侧=卡在在途后永远无回复)。
|
|
554
|
+
void rescueThenSettle(trackId)
|
|
555
|
+
} else {
|
|
556
|
+
mirror.scheduleUnlock(sessionId)
|
|
557
|
+
}
|
|
265
558
|
}
|
|
266
559
|
|
|
267
|
-
/**
|
|
268
|
-
function
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
560
|
+
/** 接管前抢救:旧回合已有产出 → 先投递结果再按 answered 销账;否则 superseded。 */
|
|
561
|
+
async function rescueThenSettle(tid: string): Promise<void> {
|
|
562
|
+
try {
|
|
563
|
+
const probe = await client.session.messages({ path: { id: sessionId } })
|
|
564
|
+
if (finished) return // 探测期间 finish 已赢 race(已结算/已投递),不得双投
|
|
565
|
+
// 终稿提取(2026-11-10 工作稿误投事故):只取纯文本终稿;工作稿不算结果
|
|
566
|
+
const rescuedText = finalAnswerText(probe?.data ?? [], promptId, baseline)
|
|
567
|
+
if (rescuedText) {
|
|
568
|
+
finished = true
|
|
569
|
+
inflight.settle(tid, undefined, "answered")
|
|
570
|
+
mirror.scheduleUnlock(sessionId)
|
|
571
|
+
void drainQueue(ctx.userId, sessionId)
|
|
572
|
+
// 投递失败不得上抛:账已结清,补投失败由 deliver 层自己的重试/降级负责
|
|
573
|
+
await safeDeliver(ctx, `📤 你发来新消息前,上一回合已完成,结果如下:\n\n${rescuedText}`).catch(() => {})
|
|
574
|
+
console.log(`[bridge] 接管前抢救:后台回合已完成且未投递,结果已补投 session=${sessionId}`)
|
|
575
|
+
return
|
|
576
|
+
}
|
|
577
|
+
} catch {
|
|
578
|
+
/* 探测失败落到 superseded 结算(原语义) */
|
|
579
|
+
}
|
|
580
|
+
inflight.settle(tid, undefined, "superseded")
|
|
581
|
+
mirror.scheduleUnlock(sessionId)
|
|
274
582
|
}
|
|
275
583
|
|
|
276
|
-
async function finish(kind: "done" | "giveup"): Promise<void> {
|
|
584
|
+
async function finish(kind: "done" | "giveup" | "superseded"): Promise<void> {
|
|
277
585
|
if (cancelled || finished) return
|
|
278
586
|
// 修复⑧防早交:SSE 的 execution.succeeded / 别回合 idle 可能唬人——
|
|
279
587
|
// promptId 锚点可用时先核实本回合是否真的有 idle 终结标记。
|
|
588
|
+
// DEF-qqbot-20261107-P2:核实同时检查「被同会话新输入接管」——SSE 完成事件
|
|
589
|
+
// 落在死回合上时改按被打断终态结算,不交付「后台任务完成」假结果。
|
|
280
590
|
if (kind === "done" && promptId) {
|
|
281
591
|
try {
|
|
282
592
|
const probe = await client.session.messages({ path: { id: sessionId } })
|
|
283
593
|
const turn = turnStateOf(probe?.data ?? [], promptId, baseline)
|
|
284
|
-
if (turn.anchored &&
|
|
594
|
+
if (turn.anchored && turn.superseded) return finish("superseded")
|
|
595
|
+
// 2026-11-10 修正:无 idle 但有正文=被杀回合实质已完(重复派发→接管打断链不产生 idle),
|
|
596
|
+
// 不得再以「本回合尚未结束」为由忽略——正文在即交付(与防线 A 同口径)。
|
|
597
|
+
// DEF-qqbot-20261112-2 追加同口径守卫:正文所在消息必须已终结(time.completed)——
|
|
598
|
+
// 权限挂起中工具阻塞的消息已流式出正文但回合未完(引擎 step.ended/failed/
|
|
599
|
+
// interrupted 均落 completed,被杀回合不受影响),此类「无 idle 有未完成正文」
|
|
600
|
+
// 不得在 finish 时被 SSE 完成事件误结(2026-11-12 实证交付「无文本产出」假完成)。
|
|
601
|
+
if (turn.anchored && !turn.hasIdle && (!turn.text || !turn.textCompleted)) {
|
|
285
602
|
console.log(`[bridge] 忽略他回合完成事件(本后台回合尚未结束)session=${sessionId}`)
|
|
286
603
|
return
|
|
287
604
|
}
|
|
@@ -290,11 +607,19 @@ export function createBridge(
|
|
|
290
607
|
}
|
|
291
608
|
}
|
|
292
609
|
finished = true
|
|
610
|
+
// R 项:先销账再清理——cleanup 对未完成(被取代)路径按 superseded 结清,
|
|
611
|
+
// 顺序必须账清在前,否则原因会被 superseded 覆盖(settle 幂等,后写不生效)。
|
|
612
|
+
if (trackId) inflight.settle(trackId, undefined, kind === "done" ? "answered" : kind === "giveup" ? "expired" : "superseded")
|
|
293
613
|
cleanup()
|
|
294
|
-
//
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
614
|
+
// Q1:后台等待终态 → 放行该 lane 队列(此前为串行而挂起;会话隔离后只放本会话 lane)
|
|
615
|
+
void drainQueue(ctx.userId, sessionId)
|
|
616
|
+
if (kind === "superseded") {
|
|
617
|
+
// DEF-qqbot-20261107-P2:后台等到的回合已被同会话新输入接管——任务已死,
|
|
618
|
+
// 明确交代而非沉默到 24 小时 giveup。
|
|
619
|
+
console.log(`[bridge] 后台回合被同会话新输入接管(superseded)session=${sessionId}`)
|
|
620
|
+
await safeDeliver(ctx, "⚠️ 后台任务被同会话的新输入打断,未产出结果;如需结果请重新发送")
|
|
621
|
+
return
|
|
622
|
+
}
|
|
298
623
|
if (kind === "giveup") {
|
|
299
624
|
await safeDeliver(ctx, "⚠️ 后台任务 24 小时仍未完成,停止自动跟进;结果可随时用 /history 查询")
|
|
300
625
|
return
|
|
@@ -303,23 +628,96 @@ export function createBridge(
|
|
|
303
628
|
await new Promise((r) => setTimeout(r, 2000))
|
|
304
629
|
try {
|
|
305
630
|
const listJson = await client.session.messages({ path: { id: sessionId } })
|
|
306
|
-
const
|
|
631
|
+
const msgs = listJson?.data ?? []
|
|
632
|
+
// 终稿提取:与 rescue 同口径——工作稿(含工具段)不作答案投递
|
|
633
|
+
const text = finalAnswerText(msgs, promptId, baseline)
|
|
307
634
|
await safeDeliver(
|
|
308
635
|
ctx,
|
|
309
636
|
text
|
|
310
637
|
? `📤 后台任务完成,结果如下:\n\n${text}`
|
|
311
638
|
: "📤 后台任务完成(无文本产出),详情可用 /history 查看",
|
|
312
|
-
)
|
|
639
|
+
).catch((error) => console.error("[bridge] 后台完成结果投递失败(账已结清):", error))
|
|
313
640
|
console.log(`[bridge] 会话 ${sessionId} 后台等待已交付`)
|
|
314
641
|
} catch (error) {
|
|
315
642
|
console.error("[bridge] 后台完成结果获取失败:", error)
|
|
316
643
|
}
|
|
317
644
|
}
|
|
318
645
|
|
|
646
|
+
/** 死回合处置(owner 2026-11-19「先关而后断点继续」):abort 由调用方发出,此处结清+交代+放行队列。 */
|
|
647
|
+
async function finishDead(): Promise<void> {
|
|
648
|
+
if (cancelled || finished) return
|
|
649
|
+
finished = true
|
|
650
|
+
if (trackId) inflight.settle(trackId, undefined, "expired")
|
|
651
|
+
cleanup()
|
|
652
|
+
// 断点继续:释放 lane 后立即 drain——队列里排在后面的消息接着执行
|
|
653
|
+
void drainQueue(ctx.userId, sessionId)
|
|
654
|
+
await safeDeliver(
|
|
655
|
+
ctx,
|
|
656
|
+
`⚠️ 后台任务底层执行多次失去响应(已自动续作 ${resumeCount} 次仍失败),停止自动跟进;队列已放行。如仍需要该结果请重新发送`,
|
|
657
|
+
).catch(() => {})
|
|
658
|
+
console.log(`[bridge] 后台回合流活性丧失:续作${resumeCount}次仍死,expired 结清 session=${sessionId} msg=${shortId(trackId)}`)
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* 死回合自动续作(owner 2026-11-19 裁定:单任务续作上限 3 次)——
|
|
663
|
+
* 「继续」的落地形态=同会话注入新回合重发原 prompt,模型读会话历史接着做;
|
|
664
|
+
* 不是断点续跑(LLM 回合执行体已随 abort 销毁,无从续起)。
|
|
665
|
+
* 本 bgWait 不换班:onAccepted 切换锚点后继续盯梢新回合,盯到完成/再死/被取代。
|
|
666
|
+
* 副作用口径:模型从历史可见死前已执行的动作,自行决定去重——与人工「重发」等价。
|
|
667
|
+
*/
|
|
668
|
+
async function resumeDead(): Promise<void> {
|
|
669
|
+
if (cancelled || finished) return
|
|
670
|
+
resumeCount += 1
|
|
671
|
+
console.log(`[bridge] 后台死回合自动续作 #${resumeCount}/${MAX_RESUME} session=${sessionId} msg=${shortId(trackId)}`)
|
|
672
|
+
await safeDeliver(ctx, `⚠️ 后台任务底层执行失去响应,已自动中止并续作(第 ${resumeCount}/${MAX_RESUME} 次);继续后台跟踪,完成自动回传`).catch(() => {})
|
|
673
|
+
try {
|
|
674
|
+
const prepared = ctx.preparedAttachments ?? await prepareQQAttachments(ctx.attachments, () =>
|
|
675
|
+
getAccessToken(config.qq.appId, config.qq.clientSecret),
|
|
676
|
+
)
|
|
677
|
+
const { text: promptBody, files } = augmentPromptWithAttachments(ctx.content, prepared)
|
|
678
|
+
const promptText =
|
|
679
|
+
(ctx.quoteText ? `> 引用上文:${ctx.quoteText}\n\n${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT
|
|
680
|
+
// 不阻塞 tick:promptAndWait 异步跑,onAccepted 切换锚点后由本 bgWait 的
|
|
681
|
+
// 既有 tick(完成/停滞/流活性/superseded 全判据)继续监督新回合。
|
|
682
|
+
void client.promptAndWait(sessionId, promptText, {
|
|
683
|
+
files: files.length ? files : undefined,
|
|
684
|
+
directory: anchorDirectory,
|
|
685
|
+
onAccepted: (info) => {
|
|
686
|
+
promptId = info.promptId
|
|
687
|
+
baseline = info.baseline
|
|
688
|
+
if (trackId) inflight.markResume(trackId, info.promptId, resumeCount)
|
|
689
|
+
lastProgressAt = Date.now()
|
|
690
|
+
lastHeartbeatAt = Date.now()
|
|
691
|
+
lastMarker = ""
|
|
692
|
+
console.log(`[bridge] 续作新回合已受理 msg=${shortId(trackId)} prompt=${shortId(info.promptId)}`)
|
|
693
|
+
},
|
|
694
|
+
onPermission: (req) => perm.waitForDecision(ctx, req, sessionId),
|
|
695
|
+
onPermissionReplied: (d) => {
|
|
696
|
+
const text = d === "reject" ? "已拒绝,该操作不会执行;AI 将继续其余步骤" : `已${DECISION_LABELS[d]},AI 将继续执行…`
|
|
697
|
+
void safeDeliver(ctx, text)
|
|
698
|
+
},
|
|
699
|
+
// 续作路径降级:冲突即时告警保留,10 分钟零进展保险网不再叠加
|
|
700
|
+
// (原 dispatch 路径的完整保险网不受影响)。
|
|
701
|
+
onPermissionConflict: (decision) => {
|
|
702
|
+
const notice = formatPermissionConflictNotice(decision)
|
|
703
|
+
if (notice) void safeDeliver(ctx, notice)
|
|
704
|
+
},
|
|
705
|
+
}).catch((error) => {
|
|
706
|
+
console.error("[bridge] 续作重派失败:", error)
|
|
707
|
+
// 续作本身失败:计一次消耗并交下轮判死/续作或 giveup(不静默)
|
|
708
|
+
void safeDeliver(ctx, `⚠️ 续作重派失败:${toErrorMessage(error)};后台监督继续,将再次尝试或按上限停止`).catch(() => {})
|
|
709
|
+
})
|
|
710
|
+
} catch (error) {
|
|
711
|
+
console.error("[bridge] 续作 prompt 构造失败:", error)
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
319
715
|
async function tick(): Promise<void> {
|
|
320
716
|
if (cancelled || finished) return
|
|
321
717
|
try {
|
|
322
718
|
const listJson = await client.session.messages({ path: { id: sessionId } })
|
|
719
|
+
probeFails = 0
|
|
720
|
+
unreachableAlerted = false
|
|
323
721
|
const msgs = listJson?.data ?? []
|
|
324
722
|
|
|
325
723
|
// H2 停滞检测:消息数或最新 created 变化=有进展;零进展超窗则提醒用户。
|
|
@@ -339,26 +737,71 @@ export function createBridge(
|
|
|
339
737
|
stallNudgeDecision(startedAt, lastProgressAt, nudges, now, STALL_FIRST_NUDGE_MS, STALL_NUDGE_INTERVAL_MS, STALL_NUDGE_MAX) === "nudge"
|
|
340
738
|
) {
|
|
341
739
|
nudges += 1
|
|
342
|
-
lastProgressAt
|
|
740
|
+
// 2026-11-09 修数据错:原实现先把 lastProgressAt 置为 now 再算 idleMin,
|
|
741
|
+
// 导致提醒恒为「已 0 分钟无进展」。先取快照再重置(重置只用于下次间隔)。
|
|
742
|
+
const snap = stallSnapshot(now, lastProgressAt, execStartAt)
|
|
743
|
+
lastProgressAt = snap.nextProgressAt
|
|
343
744
|
const st = turnStats.get(sessionId)
|
|
344
745
|
const lastAction = st?.lastTool && st?.lastAt ? `${st.lastTool}(${agoLabel(st.lastAt)})` : undefined
|
|
345
|
-
console.log(`[bridge] 后台任务状态通告 #${nudges} session=${sessionId} anchored=${turn.anchored}`)
|
|
746
|
+
console.log(`[bridge] 后台任务状态通告 #${nudges} session=${sessionId} anchored=${turn.anchored} idleMin=${snap.idleMin}`)
|
|
346
747
|
void safeDeliver(
|
|
347
748
|
ctx,
|
|
348
|
-
stallNudgeText(
|
|
749
|
+
stallNudgeText(snap.execMin, {
|
|
349
750
|
anchored: turn.anchored,
|
|
350
751
|
roundRunning: turn.anchored && !turn.hasIdle,
|
|
351
|
-
idleMin:
|
|
752
|
+
idleMin: snap.idleMin,
|
|
352
753
|
lastAction,
|
|
353
754
|
}),
|
|
354
755
|
).catch(() => {})
|
|
756
|
+
} else if (heartbeatDecision(lastHeartbeatAt, now) === "beat") {
|
|
757
|
+
// 方案 A 进度心跳(2026-11-10 owner 裁定):活跃长任务的过程可见性。
|
|
758
|
+
// 无次数上限(至完成/24h 放弃);内联 idle 自检——任务假活时用户可从
|
|
759
|
+
// 文案直接看出;同 tick 停滞提醒优先(else-if 天然互斥,不双发)。
|
|
760
|
+
lastHeartbeatAt = now
|
|
761
|
+
const hbIdleMin = Math.max(0, Math.round((now - lastProgressAt) / 60_000))
|
|
762
|
+
const hbExecMin = Math.max(0, Math.round((now - execStartAt) / 60_000))
|
|
763
|
+
const hbSt = turnStats.get(sessionId)
|
|
764
|
+
const hbAction = hbSt?.lastTool && hbSt?.lastAt ? `${hbSt.lastTool}(${agoLabel(hbSt.lastAt)})` : undefined
|
|
765
|
+
console.log(`[bridge] 后台任务进度心跳 session=${sessionId} execMin=${hbExecMin} idleMin=${hbIdleMin}`)
|
|
766
|
+
void safeDeliver(ctx, heartbeatText(hbExecMin, hbIdleMin, hbAction)).catch(() => {})
|
|
355
767
|
}
|
|
356
768
|
|
|
357
|
-
|
|
769
|
+
// 流活性监督(owner 2026-11-19 裁定:与后台探知同 tick、同一拉取结果)——
|
|
770
|
+
// 死回合与长跑任务在「无进展」信号上同形(昨夜 BG101A 实证:流停 3s 后
|
|
771
|
+
// 90 分钟假活)。判死 → 先关(abort 死回合)后断点继续(finishDead)。
|
|
772
|
+
const live = streamLiveness(msgs, promptId, baseline, now, STREAM_DEAD_MS, TOOL_GRACE_MS)
|
|
773
|
+
if (live === "dead") {
|
|
774
|
+
// 先关(owner 裁定):abort 死回合,幂等容忍失败
|
|
775
|
+
await client.session.abort({ path: { id: sessionId } }).catch(() => undefined)
|
|
776
|
+
// 后断点继续:续作上限内自动重发原 prompt(新回合),超限才 expired 放弃
|
|
777
|
+
if (resumeDecision(resumeCount, MAX_RESUME) === "resume") {
|
|
778
|
+
await resumeDead()
|
|
779
|
+
} else {
|
|
780
|
+
await finishDead()
|
|
781
|
+
}
|
|
782
|
+
return
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
if (turn.superseded) {
|
|
786
|
+
// DEF-qqbot-20261107-P2:死回合立即按被打断终态结算(交付+销账在 finish)
|
|
787
|
+
await finish("superseded")
|
|
788
|
+
} else if (turn.hasIdle || missingIdleDone(turn, lastProgressAt, now)) {
|
|
789
|
+
// 2026-11-10 僵尸事故根修:被杀回合无 idle(重复派发→接管打断链),
|
|
790
|
+
// 有正文+超宽限即实质已完,按完成投递,杜绝假心跳僵尸。
|
|
358
791
|
await finish("done")
|
|
359
792
|
}
|
|
360
793
|
} catch (error) {
|
|
361
|
-
|
|
794
|
+
probeFails += 1
|
|
795
|
+
console.error(`[bridge] 后台等待轮询失败(第${probeFails}次):`, error)
|
|
796
|
+
// 挂死分级处置(2026-11-10 方案 A 配套):OpenCode 服务不可达时一次性明示,
|
|
797
|
+
// 用户知晓「状态未知」而非误以为任务在进行;恢复后自动续跳并重置计数。
|
|
798
|
+
if (probeFails >= 5 && !unreachableAlerted) {
|
|
799
|
+
unreachableAlerted = true
|
|
800
|
+
void safeDeliver(
|
|
801
|
+
ctx,
|
|
802
|
+
"⚠️ OpenCode 服务连续不可达:后台任务状态未知(可能仍在执行)。服务恢复后自动继续跟踪;也可用 /history 查看会话进展。",
|
|
803
|
+
).catch(() => {})
|
|
804
|
+
}
|
|
362
805
|
}
|
|
363
806
|
}
|
|
364
807
|
|
|
@@ -368,6 +811,7 @@ export function createBridge(
|
|
|
368
811
|
const pollTimer = setInterval(() => void tick(), BG_POLL_MS)
|
|
369
812
|
const giveupTimer = setTimeout(() => void finish("giveup"), BG_WAIT_MAX_MS)
|
|
370
813
|
bgWaits.set(sessionId, { cancel: cleanup })
|
|
814
|
+
if (trackId) inflight.markStage(trackId, "background", { sessionId })
|
|
371
815
|
console.log(`[bridge] 会话 ${sessionId} 转入后台等待(最长 ${BG_WAIT_MAX_MS / 3_600_000} 小时)`)
|
|
372
816
|
}
|
|
373
817
|
|
|
@@ -378,7 +822,7 @@ export function createBridge(
|
|
|
378
822
|
activeWatches.set(userId, sessionID)
|
|
379
823
|
lastCtx.set(userId, ctx)
|
|
380
824
|
subscribeSession(sessionID, userId)
|
|
381
|
-
saveWatchedMap(activeWatches) // R2-P1-3:落盘,重启恢复
|
|
825
|
+
saveWatchedMap(activeWatches, storageAppId ? roleFile("watch.json") : undefined) // R2-P1-3:落盘,重启恢复
|
|
382
826
|
return [
|
|
383
827
|
`👁 已开启观察:${sessionID}`,
|
|
384
828
|
"该会话的工具调用/执行完成会实时推送摘要,/watch off 停止。",
|
|
@@ -390,7 +834,7 @@ export function createBridge(
|
|
|
390
834
|
if (!sid) return "当前没有开启观察"
|
|
391
835
|
activeWatches.delete(userId)
|
|
392
836
|
unsubscribeSession(sid, userId)
|
|
393
|
-
saveWatchedMap(activeWatches) // R2-P1-3:落盘,重启不复活
|
|
837
|
+
saveWatchedMap(activeWatches, storageAppId ? roleFile("watch.json") : undefined) // R2-P1-3:落盘,重启不复活
|
|
394
838
|
return `已停止观察:${sid}`
|
|
395
839
|
},
|
|
396
840
|
status(userId) {
|
|
@@ -400,20 +844,79 @@ export function createBridge(
|
|
|
400
844
|
}
|
|
401
845
|
|
|
402
846
|
// O7c:投递域门面(统一投递/降级/配额/节流队列/被动回复全在 core/delivery.ts)
|
|
403
|
-
const { enqueuePush, safeDeliver, sendReply, deliver } = createDelivery(
|
|
847
|
+
const { enqueuePush, safeDeliver, sendReply, deliver } = createDelivery(
|
|
848
|
+
config,
|
|
849
|
+
lastCtx,
|
|
850
|
+
isBoundSession,
|
|
851
|
+
storageAppId ? roleFile("quota.json") : undefined,
|
|
852
|
+
)
|
|
853
|
+
// DEF-1 修复(2026-11-04,UAT 实证):通知类发送永不阻断主流程——受理回执/
|
|
854
|
+
// K2 拦截/排队提示/问候等裸 sendReply 一旦被平台拒(40034024/超时)会直接
|
|
855
|
+
// 中断 handleMessage(实证:回执失败 → 回合未派发给 AI 即结算,用户消息被吞)。
|
|
856
|
+
// 统一走 notifyUser 兜底:发送失败仅告警,主流程继续。
|
|
857
|
+
const notifyUser = async (ctx: MessageContext, text: string): Promise<void> => {
|
|
858
|
+
// 出站推送门同口径(owner 2026-11-14):锚定≠当前绑定不推(排队回执/ drain 通知等)
|
|
859
|
+
if (ctx.anchorSessionId && !isBoundSession(ctx.userId, ctx.anchorSessionId)) {
|
|
860
|
+
console.log(`[push-gate] 通知拦截:绑定已切走 anchor=${ctx.anchorSessionId.slice(0, 12)}… chars=${text.length}`)
|
|
861
|
+
return
|
|
862
|
+
}
|
|
863
|
+
try {
|
|
864
|
+
await sendReply(ctx, text)
|
|
865
|
+
} catch (error) {
|
|
866
|
+
console.warn("[bridge] 通知发送失败(不阻断主流程):", toErrorMessage(error))
|
|
867
|
+
}
|
|
868
|
+
}
|
|
404
869
|
|
|
405
870
|
// O7b:审批域门面(挂起槽/等待/裁决/跨重启恢复全在 core/permission.ts)
|
|
871
|
+
// ★ 结合部契约(2026-11-17 固化):onPermission(回合内即时推送,SSE permission.asked)
|
|
872
|
+
// 与常驻交互监听(桌面端源审批 pushExternal)是同一挂起槽的两个入口——裁决/TTL/
|
|
873
|
+
// 清槽必须两入口等价;clearIfResolved 保证桌面先决时 QQ 卡自动关闭(不双发)。
|
|
874
|
+
// 多角色:本 gate 绑本角色 storageAppId(pending 落 roles/<appId>/),
|
|
875
|
+
// 跨角色审批隔离=文件级+槽位 userId 级双保险,改造时不得合并。
|
|
406
876
|
const perm = createPermissionGate({
|
|
407
877
|
client,
|
|
408
878
|
sendReply,
|
|
409
879
|
safeDeliver,
|
|
410
|
-
//
|
|
411
|
-
|
|
412
|
-
|
|
880
|
+
// DEF-qqbot-20261112-1:裁决/超时拒答 reply 的 x-opencode-directory 来源
|
|
881
|
+
//(引擎待审按 location 实例分仓;映射 directory 缺省时 reply 退化为裸发=旧行为)
|
|
882
|
+
directoryOf: (userId) => sessions.getSession(userId)?.directory,
|
|
883
|
+
// 2026-11-05 举一反三:审批槽清空(裁决/TTL)即唤醒该用户队列——否则挂起期间
|
|
884
|
+
// 入队的消息要等用户再发一条才会动(drainQueue 的 pendingPerm 守卫无人解除)。
|
|
885
|
+
onDecision: (userId) => {
|
|
886
|
+
// 会话隔离:审批裁决放行该用户全部有货 lane(drainQueue 自身对忙 lane 空转安全)
|
|
887
|
+
for (const lk of msgQueue.laneKeysOf(userId)) void drainQueue(userId, sessionIdOfLane(lk))
|
|
888
|
+
},
|
|
889
|
+
// A 项:审批卡片发送(失败自动降级文字菜单,permission 域内处理);origin 穿透到卡片正文
|
|
890
|
+
sendApprovalPrompt: (ctx, request, mainSessionId, origin) =>
|
|
891
|
+
sendApprovalCard({ appId: config.qq.appId, clientSecret: config.qq.clientSecret }, ctx, request, mainSessionId, origin),
|
|
892
|
+
// 多角色:审批态按角色分文件(缺省 legacy 全局)
|
|
893
|
+
persistFile: storageAppId ? roleFile("pending-permissions.json") : undefined,
|
|
413
894
|
})
|
|
414
895
|
|
|
415
896
|
// O7d:摘要镜像域门面(订阅/回合标记/延迟解锁/摘要投递全在 core/mirror.ts)
|
|
416
|
-
const mirror = createMirror({
|
|
897
|
+
const mirror = createMirror({
|
|
898
|
+
sessions,
|
|
899
|
+
eventStream,
|
|
900
|
+
client,
|
|
901
|
+
lastCtx,
|
|
902
|
+
safeDeliver,
|
|
903
|
+
bgWaits,
|
|
904
|
+
busyUsers,
|
|
905
|
+
// 多角色:镜像开关按角色分文件(缺省 legacy 全局)
|
|
906
|
+
settingsFile: storageAppId ? roleFile("settings.json") : undefined,
|
|
907
|
+
})
|
|
908
|
+
|
|
909
|
+
// openqq notify 外部入队通道(feature:headless 定时任务结果推送,2026-11-05 外部提案 Part1):
|
|
910
|
+
// cron/CI 任意进程经 `openqq notify` 写 ~/.openqq/outbox.json(只入队),bot 进程消费投递。
|
|
911
|
+
// delivery 全量复用(配额/降级/分条/24h 同文去重);TTL 过期丢弃;失败退避重试到上限。
|
|
912
|
+
createNotifySink({
|
|
913
|
+
config,
|
|
914
|
+
deliver: (ctx, text) => deliver(ctx, text),
|
|
915
|
+
...(process.env.QQ_OUTBOX_FILE ? { filePath: process.env.QQ_OUTBOX_FILE } : {}),
|
|
916
|
+
// 多角色(2026-11-18 补漏):outbox 按角色分文件——此前 multibot 改造漏了 notify 通道,
|
|
917
|
+
// 两角色 sink 共享 legacy 全局 outbox.json 会互相代发/抢发。
|
|
918
|
+
...(storageAppId && !process.env.QQ_OUTBOX_FILE ? { filePath: roleFile("outbox.json") } : {}),
|
|
919
|
+
})
|
|
417
920
|
|
|
418
921
|
// L 项(2026-10-30):表单桥(选择弹窗 A/B/C/D 的 QQ 同步与作答回传)。
|
|
419
922
|
// 与审批共用"每用户单一交互槽"心智:表单挂起时优先消费用户回复。
|
|
@@ -422,6 +925,8 @@ export function createBridge(
|
|
|
422
925
|
client,
|
|
423
926
|
sendReply,
|
|
424
927
|
safeDeliver,
|
|
928
|
+
// 多角色:表单日志按角色分文件(缺省 legacy 全局)
|
|
929
|
+
journalPath: storageAppId ? roleFile("forms.json") : undefined,
|
|
425
930
|
sendFormCard: async (ctx, form, keyboard) => {
|
|
426
931
|
try {
|
|
427
932
|
const token = await getAccessToken(config.qq.appId, config.qq.clientSecret)
|
|
@@ -461,21 +966,42 @@ export function createBridge(
|
|
|
461
966
|
|
|
462
967
|
async function interactionTick(): Promise<void> {
|
|
463
968
|
try {
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
969
|
+
// 权限轮询兜底(SSE permission.asked 即时推送为主,轮询为断线兜底,双防线)。
|
|
970
|
+
// DEF-qqbot-20261112-4(抄袭桌面形态):改按会话端点(GET /session/:id/permission,
|
|
971
|
+
// 引擎按会话自身实例路由)逐绑定会话轮询——零 directory 簿记;只有绑定会话才
|
|
972
|
+
// 可能映射 QQ 用户(usersOfSession),未绑定会话的待审本就不该推 QQ。
|
|
973
|
+
{
|
|
974
|
+
const seen = new Map<string, PermissionRequest>()
|
|
975
|
+
const lists = await Promise.all(
|
|
976
|
+
sessions.all().map((entry) => client.permission.forSession(entry.sessionId).catch(() => undefined)),
|
|
977
|
+
)
|
|
978
|
+
for (const res of lists) {
|
|
979
|
+
for (const req of res?.data ?? []) {
|
|
980
|
+
if (!seen.has(req.id)) seen.set(req.id, req)
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
for (const req of seen.values()) {
|
|
984
|
+
for (const uid of usersOfSession(req.sessionID)) {
|
|
985
|
+
if (perm.hasPending(uid)) continue // 单一槽:在挂起(含同 id)即跳过
|
|
986
|
+
// 出站推送门:绑定已切走的用户不推审批卡(owner 2026-11-14;历史/桌面端可裁决)
|
|
987
|
+
if (!isBoundSession(uid, req.sessionID)) {
|
|
988
|
+
console.log(`[push-gate] 审批卡拦截(轮询兜底):绑定已切走 uid=${uid.slice(0, 8)}… sid=${shortId(req.sessionID)}`)
|
|
989
|
+
continue
|
|
990
|
+
}
|
|
991
|
+
perm.pushExternal(uid, ctxForUser(uid), req, req.sessionID)
|
|
992
|
+
}
|
|
469
993
|
}
|
|
470
994
|
}
|
|
471
|
-
//
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
995
|
+
// 表单轮询兜底(REST 表单通道,form-bridge 承接渲染/回执)
|
|
996
|
+
{
|
|
997
|
+
for (const entry of sessions.all()) {
|
|
998
|
+
const forms = (await client.form.list({ sessionID: entry.sessionId }).catch(() => undefined))?.data ?? []
|
|
999
|
+
for (const form of forms) {
|
|
1000
|
+
// 会话级列表返回 Form.Info(无 state);带 state 时只推 pending
|
|
1001
|
+
const state = (form as { state?: { status?: string } }).state
|
|
1002
|
+
if (state && state.status !== "pending") continue
|
|
1003
|
+
formBridge.pushForm(entry.userId, ctxForUser(entry.userId), form)
|
|
1004
|
+
}
|
|
479
1005
|
}
|
|
480
1006
|
}
|
|
481
1007
|
} catch (error) {
|
|
@@ -488,27 +1014,388 @@ export function createBridge(
|
|
|
488
1014
|
console.log(`[interaction-watch] 常驻交互监听已启动(每 ${INTERACTION_WATCH_MS / 1000}s 轮询权限+表单)`)
|
|
489
1015
|
}
|
|
490
1016
|
|
|
1017
|
+
// 事件驱动权限推送(2026-11-08,DEF-qqbot-20261107-1 根因修复)。
|
|
1018
|
+
// 桌面端走 /api/event 的 permission.asked 即时弹窗,引擎会停在裁决前;
|
|
1019
|
+
// bot 原先只靠 12s 轮询,取到时请求常已被引擎自行放行。这里复用同一条 SSE:
|
|
1020
|
+
// 事件到达即推 QQ 卡,12s 轮询保留为断线兜底(双防线)。
|
|
1021
|
+
eventStream.subscribeAll((ev) => {
|
|
1022
|
+
if (ev.type === "permission.replied") {
|
|
1023
|
+
// 联动清槽(2026-11-09):源头(桌面端/引擎/账号规则)已解决该请求 →
|
|
1024
|
+
// 同步撤销 QQ 挂起槽并回执,消除「桌面板了 QQ 卡悬空/TTL 误杀」的双通道孤岛。
|
|
1025
|
+
const d = (ev.data ?? {}) as { sessionID?: string; requestID?: string; reply?: unknown }
|
|
1026
|
+
if (d?.requestID) {
|
|
1027
|
+
// 弹卡延迟闸:asked 后 defer 窗口内被处置 → 撤定时器不推卡(与桌面静默放行一致)
|
|
1028
|
+
permPushGate.cancel(d.requestID)
|
|
1029
|
+
perm.clearIfResolved(d.sessionID, d.requestID, d.reply)
|
|
1030
|
+
}
|
|
1031
|
+
return
|
|
1032
|
+
}
|
|
1033
|
+
if (ev.type !== "permission.asked") return
|
|
1034
|
+
const req = ev.data as unknown as PermissionRequest | undefined
|
|
1035
|
+
if (!req?.id || !req.sessionID) return
|
|
1036
|
+
for (const uid of usersOfSession(req.sessionID)) {
|
|
1037
|
+
if (perm.hasPending(uid)) continue
|
|
1038
|
+
// 出站推送门:绑定已切走不推卡(owner 2026-11-14)——usersOfSession 按映射反查,
|
|
1039
|
+
// 未绑定会话自然不在列;此处防的是「映射还在但用户已切走」的残留窗口。
|
|
1040
|
+
if (!isBoundSession(uid, req.sessionID)) {
|
|
1041
|
+
console.log(`[push-gate] 审批卡拦截(SSE asked):绑定已切走 uid=${uid.slice(0, 8)}… sid=${shortId(req.sessionID)} request=${req.id}`)
|
|
1042
|
+
continue
|
|
1043
|
+
}
|
|
1044
|
+
console.log(
|
|
1045
|
+
`[perm-event] permission.asked 即时推送(延迟 ${PERM_DEFER_MS}ms 判定)user=${uid.slice(0, 8)}… request=${req.id}`,
|
|
1046
|
+
)
|
|
1047
|
+
permPushGate.schedule(uid, req.id, () => void flushPermPush(uid, req))
|
|
1048
|
+
}
|
|
1049
|
+
})
|
|
1050
|
+
|
|
1051
|
+
// 延迟闸到点:确认请求仍悬置才推卡。双保险=REST 查待审列表(防 SSE 漏事件);
|
|
1052
|
+
// 查询失败按悬置处理继续推(展示面 fail-open,不吞真人裁决入口)。
|
|
1053
|
+
// DEF-qqbot-20261112-1:反查必须带会话自身目录——引擎待审按 location 实例分仓,
|
|
1054
|
+
// 裸查只命中服务端 cwd 实例,项目会话的请求永远查空 → 恒弃推(ZERO2 实证挂起 5h24m 被误弃)。
|
|
1055
|
+
async function flushPermPush(uid: string, req: PermissionRequest): Promise<void> {
|
|
1056
|
+
const bound = sessions.getSession(uid)
|
|
1057
|
+
try {
|
|
1058
|
+
const res = await client.permission.list({ directory: bound?.directory })
|
|
1059
|
+
const still = (res?.data ?? []).some((r) => r.id === req.id)
|
|
1060
|
+
if (!still) {
|
|
1061
|
+
console.log(`[perm-event] 延迟判定:请求已被处置,弃推 user=${uid.slice(0, 8)}… request=${req.id}`)
|
|
1062
|
+
return
|
|
1063
|
+
}
|
|
1064
|
+
} catch {
|
|
1065
|
+
/* 查询失败不阻断推卡 */
|
|
1066
|
+
}
|
|
1067
|
+
// DEF-qqbot-20261110-4(实战实证):来源标注按回合归属判定——该会话正有 bot
|
|
1068
|
+
// 前台回合在跑(QQ 发起)时不得标「桌面端回合」(此前一律 external,回执
|
|
1069
|
+
// 「已由桌面端处理」与事实不符);真·桌面回合(该会话 lane 未命中)才标 external。
|
|
1070
|
+
const origin: PermOrigin =
|
|
1071
|
+
bound?.sessionId === req.sessionID && busyUsers.has(laneOf(uid, req.sessionID)) ? "bot" : "external"
|
|
1072
|
+
perm.pushExternal(uid, ctxForUser(uid), req, req.sessionID, origin)
|
|
1073
|
+
}
|
|
1074
|
+
|
|
491
1075
|
const mirrorApi: MirrorApi = mirror.api
|
|
492
1076
|
|
|
493
|
-
// Q1
|
|
1077
|
+
// Q1:队列/台账派生视图(三源 join:内存队列 + 磁盘台账 + 运行态)
|
|
1078
|
+
function queueViewFor(userId: string): QueueView {
|
|
1079
|
+
const journal = inflight.view()
|
|
1080
|
+
return deriveQueueView({
|
|
1081
|
+
entries: [...journal.inflight, ...journal.settled].filter((e) => e.userId === userId),
|
|
1082
|
+
jobs: msgQueue.listUser(userId),
|
|
1083
|
+
orphanMs: resolveOrphanMs(process.env.QQ_ORPHAN_MS),
|
|
1084
|
+
queueMax: QUEUE_MAX,
|
|
1085
|
+
runtime: {
|
|
1086
|
+
// 会话隔离:busyLanes 即 busyUsers(lane 键集合);running 按条目自身会话判定
|
|
1087
|
+
busyLanes: busyUsers,
|
|
1088
|
+
draining: draining.size > 0,
|
|
1089
|
+
bgSessions: new Set(bgWaits.keys()),
|
|
1090
|
+
},
|
|
1091
|
+
})
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// Q1:队列命令实现(2026-11-05:/queue 默认 join 台账,不再只看内存)
|
|
494
1095
|
const queueApi = {
|
|
495
|
-
list: (userId: string): string => {
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
1096
|
+
list: (userId: string): string => formatQueueReply(queueViewFor(userId), { limit: QUEUE_MAX }),
|
|
1097
|
+
listAll: (userId: string, page = 1): string =>
|
|
1098
|
+
formatQueueReply(queueViewFor(userId), { all: true, page, limit: QUEUE_MAX }),
|
|
1099
|
+
summary: (userId: string): string => formatStatusLine(queueViewFor(userId)),
|
|
1100
|
+
clear: (userId: string): number => {
|
|
1101
|
+
const jobs = [...msgQueue.listUser(userId)]
|
|
1102
|
+
for (const job of jobs) {
|
|
1103
|
+
if (job.ctx.msgId) inflight.settle(job.ctx.msgId, undefined, "cancelled")
|
|
1104
|
+
}
|
|
1105
|
+
const n = msgQueue.clear(userId)
|
|
1106
|
+
if (n > 0) console.log(`[queue] clear user=${userId.slice(0, 8)}… count=${n} settle=cancelled`)
|
|
1107
|
+
return n
|
|
1108
|
+
},
|
|
1109
|
+
drop: (userId: string, id: number): string => {
|
|
1110
|
+
const job = msgQueue.find(userId, id)
|
|
1111
|
+
if (!job) return `队列里没有 #${id}`
|
|
1112
|
+
if (job.ctx.msgId) inflight.settle(job.ctx.msgId, undefined, "dropped")
|
|
1113
|
+
msgQueue.drop(userId, id)
|
|
1114
|
+
console.log(`[queue] drop user=${userId.slice(0, 8)}… qid=${id} settle=dropped`)
|
|
1115
|
+
return `已删除队列 #${id}(台账已结清)`
|
|
1116
|
+
},
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
// DEF-qqbot-20261105-P1 防线 B(2026-11-07):/cancel 彻底复位。abort 只杀
|
|
1120
|
+
// opencode 侧回合;bot 侧悬挂的前台等待与残留台账账仍冻结 drain(11-06
|
|
1121
|
+
// 复现:cancel 后队列死锁 12 分钟直至重启)。此处统一:清队列 + abort +
|
|
1122
|
+
// 杀后台等待 + 结清该用户全部在途账 + 立即 drain 拉起。
|
|
1123
|
+
async function stopAllForUser(userId: string): Promise<{ cleared: number; title: string | undefined }> {
|
|
1124
|
+
const cleared = queueApi.clear(userId)
|
|
1125
|
+
const session = sessions.getSession(userId)
|
|
1126
|
+
if (session) {
|
|
1127
|
+
bgWaits.get(session.sessionId)?.cancel()
|
|
1128
|
+
try {
|
|
1129
|
+
await client.session.abort({ path: { id: session.sessionId } })
|
|
1130
|
+
} catch {
|
|
1131
|
+
/* 悬挂回合可能已自行终结,abort 失败不阻断复位 */
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
let settled = 0
|
|
1135
|
+
for (const e of inflight.pending()) {
|
|
1136
|
+
if (e.userId !== userId) continue
|
|
1137
|
+
inflight.settle(e.msgId, undefined, "cancelled")
|
|
1138
|
+
settled++
|
|
1139
|
+
}
|
|
1140
|
+
// 内存忙标志复位:悬挂的前台等待不退出时 busyUsers/draining 永久挡 drain
|
|
1141
|
+
// (11-06 实证 cancel 后死锁 12 分钟)。复位后 opencode 会话串行约束仍在
|
|
1142
|
+
// (服务端排队),bot 侧账幂等,不会出现重复投递。
|
|
1143
|
+
// 会话隔离:清该用户全部 lane,并逐 lane 续排。
|
|
1144
|
+
for (const k of [...busyUsers]) if (userIdOfLane(k) === userId) busyUsers.delete(k)
|
|
1145
|
+
for (const k of [...draining]) if (userIdOfLane(k) === userId) draining.delete(k)
|
|
1146
|
+
if (settled > 0) console.log(`[bridge] stopAll 结清在途账 user=${userId.slice(0, 8)}… count=${settled}`)
|
|
1147
|
+
for (const lk of msgQueue.laneKeysOf(userId)) void drainQueue(userId, sessionIdOfLane(lk))
|
|
1148
|
+
return { cleared, title: session?.title }
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
// 台账诊断命令实现(/ledger /ledger check /ledger settle)
|
|
1152
|
+
const ledgerApi: LedgerApi = {
|
|
1153
|
+
view: async (userId: string, args: string): Promise<string> => {
|
|
1154
|
+
const view = queueViewFor(userId)
|
|
1155
|
+
const parts = args.trim().split(/\s+/).filter(Boolean)
|
|
1156
|
+
const sub = parts[0]?.toLowerCase() ?? ""
|
|
1157
|
+
if (/^\d+$/.test(sub)) {
|
|
1158
|
+
// DEF-qqbot-20261110-8:数字先按尾号消解(唯一命中→详情/多条→歧义),零命中才当页码
|
|
1159
|
+
const resolution = resolveLedgerNumericArg(sub, [...view.inflightEntries, ...view.settledRecent])
|
|
1160
|
+
if (resolution.kind === "detail") return formatLedgerReply(view, { detail: resolution.entry })
|
|
1161
|
+
if (resolution.kind === "ambiguous") return `尾号「${sub}」匹配到 ${resolution.count} 条,请给更长的尾号`
|
|
1162
|
+
return formatLedgerReply(view, { page: resolution.page })
|
|
1163
|
+
}
|
|
1164
|
+
if (sub === "orphan" || sub === "rejected" || sub === "inflight" || sub === "settled") {
|
|
1165
|
+
const page = Number(parts[1] ?? "1")
|
|
1166
|
+
return formatLedgerReply(view, {
|
|
1167
|
+
filter: sub,
|
|
1168
|
+
page: Number.isInteger(page) && page > 0 ? page : 1,
|
|
1169
|
+
})
|
|
1170
|
+
}
|
|
1171
|
+
if (sub && sub !== "all") {
|
|
1172
|
+
const pool = [...view.inflightEntries, ...view.settledRecent]
|
|
1173
|
+
const hit = pool.find((e) => e.msgId === sub || e.msgId.endsWith(sub) || shortId(e.msgId) === sub)
|
|
1174
|
+
if (!hit) return `台账里没有匹配「${sub}」的条目(发 /ledger 查看尾号)`
|
|
1175
|
+
return formatLedgerReply(view, { detail: hit })
|
|
1176
|
+
}
|
|
1177
|
+
return formatLedgerReply(view)
|
|
1178
|
+
},
|
|
1179
|
+
check: async (userId: string): Promise<string> => {
|
|
1180
|
+
const view = queueViewFor(userId)
|
|
1181
|
+
if (view.inflightEntries.length === 0) return "台账在途:0 条,无需对账"
|
|
1182
|
+
const lines = [`台账对账 · 在途 ${view.inflightEntries.length} 条`]
|
|
1183
|
+
let answered = 0
|
|
1184
|
+
let running = 0
|
|
1185
|
+
let lost = 0
|
|
1186
|
+
let failed = 0
|
|
1187
|
+
for (const e of view.inflightEntries.slice(0, 20)) {
|
|
1188
|
+
const label = `${shortId(e.msgId)}「${previewText(e.text, 20)}」`
|
|
1189
|
+
if (!e.sessionId) {
|
|
1190
|
+
lost++
|
|
1191
|
+
lines.push(` · ${label} → lost(从未进入会话;可 /ledger settle ${shortId(e.msgId)} confirm 结清)`)
|
|
1192
|
+
continue
|
|
1193
|
+
}
|
|
1194
|
+
try {
|
|
1195
|
+
const msgs = await fetchRecoveryMessages(client, e.sessionId)
|
|
1196
|
+
const cls = classifyInflight({ text: e.text, at: e.at }, msgs)
|
|
1197
|
+
if (cls.kind === "answered") {
|
|
1198
|
+
answered++
|
|
1199
|
+
lines.push(` · ${label} → answered(答案已在库里,重启会补投)`)
|
|
1200
|
+
} else if (cls.kind === "running") {
|
|
1201
|
+
running++
|
|
1202
|
+
lines.push(` · ${label} → running(回合在跑/未终结)`)
|
|
1203
|
+
} else {
|
|
1204
|
+
lost++
|
|
1205
|
+
lines.push(` · ${label} → lost(会话历史找不到;可重发或结清)`)
|
|
1206
|
+
}
|
|
1207
|
+
} catch (error) {
|
|
1208
|
+
failed++
|
|
1209
|
+
lines.push(` · ${label} → 对账失败:${toErrorMessage(error)}`)
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
if (view.inflightEntries.length > 20) lines.push(` …其余 ${view.inflightEntries.length - 20} 条未展开`)
|
|
1213
|
+
lines.push(`汇总:answered ${answered} · running ${running} · lost ${lost}${failed ? ` · 失败 ${failed}` : ""}`)
|
|
1214
|
+
lines.push("修复:/ledger settle <尾号> confirm 人工结清;重启对账会自动补投/重挂")
|
|
1215
|
+
console.log(
|
|
1216
|
+
`[journal] check user=${userId.slice(0, 8)}… inflight=${view.inflightEntries.length} answered=${answered} running=${running} lost=${lost} failed=${failed}`,
|
|
501
1217
|
)
|
|
502
|
-
return
|
|
503
|
-
busy,
|
|
504
|
-
`队列:${jobs.length} 条(上限 ${QUEUE_MAX})`,
|
|
505
|
-
...lines,
|
|
506
|
-
"发 /queue clear 清空,/queue drop <编号> 删除一条。",
|
|
507
|
-
].join("\n")
|
|
1218
|
+
return lines.join("\n")
|
|
508
1219
|
},
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
1220
|
+
settle: (userId: string, key: string, confirm: boolean): string => {
|
|
1221
|
+
const view = queueViewFor(userId)
|
|
1222
|
+
const hits = view.inflightEntries.filter(
|
|
1223
|
+
(e) =>
|
|
1224
|
+
e.msgId === key ||
|
|
1225
|
+
e.msgId.endsWith(key) ||
|
|
1226
|
+
// DEF-qqbot-20261112-6:QQ msgId 恒以 "!" 结尾,人工/Agent 抄尾号时极易
|
|
1227
|
+
// 丢 "!"(2026-11-12 实证:settle 三连"没有匹配"的根因)——容忍 bang 丢失
|
|
1228
|
+
e.msgId.endsWith(`${key}!`) ||
|
|
1229
|
+
shortId(e.msgId) === key,
|
|
1230
|
+
)
|
|
1231
|
+
if (hits.length === 0) return `台账在途里没有匹配「${key}」的条目`
|
|
1232
|
+
if (hits.length > 1) return `尾号「${key}」匹配到 ${hits.length} 条,请给更长的尾号`
|
|
1233
|
+
const hit = hits[0]
|
|
1234
|
+
if (!hit) return `台账在途里没有匹配「${key}」的条目`
|
|
1235
|
+
if (!confirm) {
|
|
1236
|
+
return `将结清:${shortId(hit.msgId)}「${previewText(hit.text, 30)}」\n确认请发 /ledger settle ${key} confirm`
|
|
1237
|
+
}
|
|
1238
|
+
const ok = inflight.settle(hit.msgId, undefined, "manual")
|
|
1239
|
+
const job = msgQueue.listUser(userId).find((j) => j.ctx.msgId === hit.msgId)
|
|
1240
|
+
if (job) msgQueue.drop(userId, job.id)
|
|
1241
|
+
console.log(`[journal] settle-manual user=${userId.slice(0, 8)}… msg=${shortId(hit.msgId)} ok=${ok}`)
|
|
1242
|
+
return ok ? `已结清:${shortId(hit.msgId)}(人工)` : "该条目已不在在途状态"
|
|
1243
|
+
},
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
// 孤儿巡检:每 60s 扫一次台账;仅对新增孤儿且距上次提醒 >10min 的用户发一条汇总。
|
|
1247
|
+
const ORPHAN_SCAN_MS = (() => {
|
|
1248
|
+
const n = Number(process.env.QQ_ORPHAN_SCAN_SECONDS ?? "60")
|
|
1249
|
+
return Number.isFinite(n) && n > 0 ? Math.floor(n * 1000) : 0
|
|
1250
|
+
})()
|
|
1251
|
+
const ORPHAN_NOTIFY_GAP_MS = 10 * 60_000
|
|
1252
|
+
const orphanNotifyState = new Map<string, OrphanNotifyState>()
|
|
1253
|
+
if (ORPHAN_SCAN_MS > 0) {
|
|
1254
|
+
setInterval(() => {
|
|
1255
|
+
try {
|
|
1256
|
+
const now = Date.now()
|
|
1257
|
+
const users = new Set(inflight.view().inflight.map((e) => e.userId))
|
|
1258
|
+
for (const uid of users) {
|
|
1259
|
+
const view = queueViewFor(uid)
|
|
1260
|
+
// design §3.4:仅新增孤儿且距上次提醒 >10min 发汇总(decideOrphanNotify 纯函数决策)
|
|
1261
|
+
const dec = decideOrphanNotify(
|
|
1262
|
+
orphanNotifyState.get(uid),
|
|
1263
|
+
view.orphan.map((o) => o.msgId),
|
|
1264
|
+
now,
|
|
1265
|
+
ORPHAN_NOTIFY_GAP_MS,
|
|
1266
|
+
)
|
|
1267
|
+
orphanNotifyState.set(uid, dec.state)
|
|
1268
|
+
if (!dec.notify) continue
|
|
1269
|
+
console.log(`[queue] orphan-scan user=${uid.slice(0, 8)}… count=${view.counts.orphan}`)
|
|
1270
|
+
void safeDeliver(
|
|
1271
|
+
ctxForUser(uid),
|
|
1272
|
+
`⚠️ 台账发现 ${view.counts.orphan} 条孤儿消息(受理后未入队/未派发)。发 /queue 查看;/ledger settle <尾号> confirm 可人工结清。`,
|
|
1273
|
+
).catch(() => {})
|
|
1274
|
+
}
|
|
1275
|
+
} catch (error) {
|
|
1276
|
+
console.error("[queue] 孤儿巡检失败:", toErrorMessage(error))
|
|
1277
|
+
}
|
|
1278
|
+
}, ORPHAN_SCAN_MS)
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
// 僵尸收割(DEF-qqbot-20261112-02 修法②,owner 2026-11-14 授权):60s 独立巡检,
|
|
1282
|
+
// 收割 busy lane 悬挂态——前台时限/bgWait 双层自保都漏过的形态(11-12 实证 busy 挂 27min)。
|
|
1283
|
+
// 决策核纯函数在 core/zombie-reaper.ts(三级门,宁漏杀勿误杀);此处只做探针与动作。
|
|
1284
|
+
const REAPER_SCAN_MS = (() => {
|
|
1285
|
+
const n = Number(process.env.QQ_REAPER_SCAN_SECONDS ?? "60")
|
|
1286
|
+
return Number.isFinite(n) && n > 0 ? Math.floor(n * 1000) : 0
|
|
1287
|
+
})()
|
|
1288
|
+
const REAPER_MIN_AGE = resolveReaperMs(process.env.QQ_REAPER_MIN_AGE_MS, REAPER_MIN_AGE_MS)
|
|
1289
|
+
const REAPER_SILENCE = resolveReaperMs(process.env.QQ_REAPER_SILENCE_MS, REAPER_SILENCE_MS)
|
|
1290
|
+
const DISPATCH_STALL = (() => {
|
|
1291
|
+
const n = Number(process.env.QQ_DISPATCH_STALL_MS ?? String(DISPATCH_STALL_MS))
|
|
1292
|
+
return Number.isFinite(n) && n >= 30_000 && n <= 3_600_000 ? n : DISPATCH_STALL_MS
|
|
1293
|
+
})()
|
|
1294
|
+
const REAPER_LANE_COOLDOWN_MS = 5 * 60_000
|
|
1295
|
+
const reaperCooldown = new Map<string, number>()
|
|
1296
|
+
|
|
1297
|
+
async function reaperTick(): Promise<void> {
|
|
1298
|
+
const now = Date.now()
|
|
1299
|
+
let budget = 1 // 单 tick 至多 1 收:收割器自己绝不制造风暴
|
|
1300
|
+
for (const lane of [...busyUsers]) {
|
|
1301
|
+
if (budget <= 0) break
|
|
1302
|
+
const uid = userIdOfLane(lane)
|
|
1303
|
+
const laneSid = sessionIdOfLane(lane)
|
|
1304
|
+
// QQ_LANE_SCOPE=per-peer(design §2.3):lane 退化为 per-user 与 null lane 同形,
|
|
1305
|
+
// 不能按「无 sid 不收割」跳过——真实会话从在途账回填。
|
|
1306
|
+
const perPeer = laneScope() === "per-peer"
|
|
1307
|
+
// null lane=派发窗口极短不收割(仅 per-session-peer 档;per-peer 档 lane 恒为 per-peer 形)
|
|
1308
|
+
if (!perPeer && !laneSid) continue
|
|
1309
|
+
// 账已不在但 lane 忙=纯悬挂标志(27min 实证形态),清锁放行即完成使命
|
|
1310
|
+
const entry = inflight.pending().find(
|
|
1311
|
+
(e) => e.userId === uid && e.state === "inflight" && (perPeer || e.sessionId === laneSid),
|
|
1312
|
+
)
|
|
1313
|
+
if (!entry) {
|
|
1314
|
+
busyUsers.delete(lane)
|
|
1315
|
+
console.log(`[reaper] 悬挂标志清理(无在途账)user=${uid.slice(0, 8)}… lane=${laneSid ? shortId(laneSid) : "per-user"}`)
|
|
1316
|
+
void drainQueue(uid, laneSid)
|
|
1317
|
+
continue
|
|
1318
|
+
}
|
|
1319
|
+
// per-peer 档:探针/abort/补投一律用账的真实会话(lane 键里没有会话信息)
|
|
1320
|
+
const sid = entry.sessionId
|
|
1321
|
+
// bgWait 会话有自带 giveup/停滞保险网
|
|
1322
|
+
if (!sid || bgWaits.has(sid)) continue
|
|
1323
|
+
// 引擎探针:会话消息列表 + turnStateOf(与 bgWait finish 同判据);失败=本轮不动手
|
|
1324
|
+
const probe = await client.session.messages({ path: { id: sid } }).catch(() => undefined)
|
|
1325
|
+
const msgs = probe?.data
|
|
1326
|
+
const lastMsgAt = msgs?.length ? Math.max(...msgs.map((m) => m.time?.created ?? 0)) : entry.at
|
|
1327
|
+
const turn = msgs ? turnStateOf(msgs, entry.promptId ?? "", entry.at) : null
|
|
1328
|
+
const dec = decideReap({
|
|
1329
|
+
entry,
|
|
1330
|
+
turn,
|
|
1331
|
+
lastMsgAt,
|
|
1332
|
+
cooldownUntil: reaperCooldown.get(lane) ?? 0,
|
|
1333
|
+
now,
|
|
1334
|
+
minAgeMs: REAPER_MIN_AGE,
|
|
1335
|
+
silenceMs: REAPER_SILENCE,
|
|
1336
|
+
})
|
|
1337
|
+
if (dec.kind !== "reap-completed" && dec.kind !== "reap-stalled") continue
|
|
1338
|
+
// L2:回合未完且静默超时 → 单会话精准 abort(失败容忍:账侧仍按清障处理)
|
|
1339
|
+
if (dec.kind === "reap-stalled") {
|
|
1340
|
+
await client.session.abort({ path: { id: sid } }).catch(() => undefined)
|
|
1341
|
+
}
|
|
1342
|
+
// 动作前重验:lane 仍忙 + 账仍 inflight + 同一 attemptId——防竞态杀到新生回合
|
|
1343
|
+
if (!busyUsers.has(lane)) continue
|
|
1344
|
+
const cur = inflight.pending().find((e) => e.msgId === entry.msgId)
|
|
1345
|
+
if (!cur || cur.attemptId !== entry.attemptId) continue
|
|
1346
|
+
busyUsers.delete(lane)
|
|
1347
|
+
const ctx: MessageContext = { ...ctxForUser(uid), anchorSessionId: sid }
|
|
1348
|
+
if (dec.kind === "reap-completed" && dec.text) {
|
|
1349
|
+
// L1:回合实已完成 → 终稿补投(delivery 去重天然防双投)+ answered
|
|
1350
|
+
inflight.settle(entry.msgId, undefined, "answered")
|
|
1351
|
+
await safeDeliver(ctx, `📤 你卡住的回合其实已完成,结果补投如下:\n\n${dec.text}`).catch(() => {})
|
|
1352
|
+
} else {
|
|
1353
|
+
// 完成无正文(被杀回合)或 L2 静默强杀 → expired + 可见交代
|
|
1354
|
+
inflight.settle(entry.msgId, undefined, "expired")
|
|
1355
|
+
await safeDeliver(ctx, "⚠️ 检测到一个卡死的回合(长时间无进展),已自动清理;如未收到预期结果请重新发送").catch(() => {})
|
|
1356
|
+
}
|
|
1357
|
+
console.log(
|
|
1358
|
+
`[reaper] ${dec.kind} user=${uid.slice(0, 8)}… lane=${shortId(sid)} msg=${shortId(entry.msgId)} age=${Math.round((now - entry.at) / 60_000)}m`,
|
|
1359
|
+
)
|
|
1360
|
+
reaperCooldown.set(lane, now + REAPER_LANE_COOLDOWN_MS)
|
|
1361
|
+
void drainQueue(uid, sid)
|
|
1362
|
+
budget--
|
|
1363
|
+
}
|
|
1364
|
+
// DEF-qqbot-20261114-04(派发悬挂哨兵):stage=dispatched 且无 promptId、超龄的账——
|
|
1365
|
+
// 幽灵派发(会话不存在)/派发未达引擎会把 lane 挂死冻结全队列(00:57 seed 实证)。
|
|
1366
|
+
// 与 busy-lane 收割同预算/同冷却键;probe 失败(网络)不动手,下轮再判。
|
|
1367
|
+
for (const entry of inflight.pending()) {
|
|
1368
|
+
if (budget <= 0) break
|
|
1369
|
+
if (entry.state !== "inflight" || entry.stage !== "dispatched" || entry.promptId || !entry.sessionId) continue
|
|
1370
|
+
const lane = laneOf(entry.userId, entry.sessionId)
|
|
1371
|
+
const until = reaperCooldown.get(lane) ?? 0
|
|
1372
|
+
if (now < until) continue
|
|
1373
|
+
const probe = await client.session.messages({ path: { id: entry.sessionId } }).catch((error: unknown) => error)
|
|
1374
|
+
const sessionExists = probe instanceof Error ? sessionExistsFromProbeError(probe.message) : true
|
|
1375
|
+
const dec = decideDispatchStall({ entry, sessionExists, now, stallMs: DISPATCH_STALL })
|
|
1376
|
+
if (dec.kind !== "reap-ghost" && dec.kind !== "reap-lost") continue
|
|
1377
|
+
// 动作前重验:账仍 inflight 同 attemptId;lane 若忙(该会话正被别的回合占用)一并释放
|
|
1378
|
+
const cur = inflight.pending().find((e) => e.msgId === entry.msgId)
|
|
1379
|
+
if (!cur || cur.attemptId !== entry.attemptId) continue
|
|
1380
|
+
busyUsers.delete(lane)
|
|
1381
|
+
inflight.settle(entry.msgId, undefined, "error")
|
|
1382
|
+
const ctx: MessageContext = { ...ctxForUser(entry.userId), anchorSessionId: entry.sessionId }
|
|
1383
|
+
await safeDeliver(
|
|
1384
|
+
ctx,
|
|
1385
|
+
`⚠️ 一条消息派发失败(${dec.kind === "reap-ghost" ? "目标会话已不存在" : "派发未到达引擎"},已自动清理,不阻塞后续消息)。需要的话请重发:「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」`,
|
|
1386
|
+
).catch(() => {})
|
|
1387
|
+
console.log(
|
|
1388
|
+
`[reaper] ${dec.kind} user=${entry.userId.slice(0, 8)}… lane=${shortId(entry.sessionId)} msg=${shortId(entry.msgId)} age=${Math.round((now - entry.at) / 1000)}s`,
|
|
1389
|
+
)
|
|
1390
|
+
reaperCooldown.set(lane, now + REAPER_LANE_COOLDOWN_MS)
|
|
1391
|
+
void drainQueue(entry.userId, entry.sessionId)
|
|
1392
|
+
budget--
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
if (REAPER_SCAN_MS > 0) {
|
|
1396
|
+
setInterval(() => {
|
|
1397
|
+
void reaperTick().catch((error) => console.error("[reaper] 巡检失败:", toErrorMessage(error)))
|
|
1398
|
+
}, REAPER_SCAN_MS)
|
|
512
1399
|
}
|
|
513
1400
|
|
|
514
1401
|
// Q2:手动进度查询(本地事件统计,零模型调用)
|
|
@@ -517,7 +1404,7 @@ export function createBridge(
|
|
|
517
1404
|
const session = sessions.getSession(userId)
|
|
518
1405
|
if (!session) return "当前还没有会话,发消息即可开始"
|
|
519
1406
|
const st = turnStats.get(session.sessionId)
|
|
520
|
-
const busy =
|
|
1407
|
+
const busy = anyLaneBusy(userId) ? "处理中" : "空闲"
|
|
521
1408
|
const bg = bgWaits.has(session.sessionId) ? " · 后台等待在途" : ""
|
|
522
1409
|
if (!st) return `当前会话:${busy}${bg}\n暂无工具调用记录(本会话新起或尚无动作类里程碑)`
|
|
523
1410
|
return [
|
|
@@ -540,7 +1427,9 @@ export function createBridge(
|
|
|
540
1427
|
watch: watchApi,
|
|
541
1428
|
mirror: mirrorApi,
|
|
542
1429
|
queue: queueApi,
|
|
1430
|
+
ledger: ledgerApi,
|
|
543
1431
|
progress: progressApi,
|
|
1432
|
+
stopAll: stopAllForUser,
|
|
544
1433
|
}
|
|
545
1434
|
|
|
546
1435
|
// R2 修复批次启动项(2026-10-14)
|
|
@@ -549,7 +1438,7 @@ export function createBridge(
|
|
|
549
1438
|
}
|
|
550
1439
|
// R2-P1-3:恢复持久化的 /watch 订阅(里程碑已改 /watch 专属,重启不得静默丢)
|
|
551
1440
|
{
|
|
552
|
-
const saved = loadWatchedMap()
|
|
1441
|
+
const saved = loadWatchedMap(storageAppId ? roleFile("watch.json") : undefined)
|
|
553
1442
|
const known = new Set(sessions.all().map((x) => x.sessionId))
|
|
554
1443
|
let pruned = false
|
|
555
1444
|
for (const [uid, sid] of Object.entries(saved)) {
|
|
@@ -561,7 +1450,7 @@ export function createBridge(
|
|
|
561
1450
|
subscribeSession(sid, uid)
|
|
562
1451
|
console.log(`[watch] 恢复订阅 ${uid.slice(0, 8)}… → ${sid}`)
|
|
563
1452
|
}
|
|
564
|
-
if (pruned) saveWatchedMap(activeWatches)
|
|
1453
|
+
if (pruned) saveWatchedMap(activeWatches, storageAppId ? roleFile("watch.json") : undefined)
|
|
565
1454
|
}
|
|
566
1455
|
|
|
567
1456
|
// O2(P2-4a):恢复重启前挂起的审批(逻辑随 O7b 收进 core/permission.ts)
|
|
@@ -575,18 +1464,36 @@ export function createBridge(
|
|
|
575
1464
|
const handleMessage = async (ctx: MessageContext): Promise<void> => {
|
|
576
1465
|
let claimedMsgId = ""
|
|
577
1466
|
const intentKey = intentKeyOf(ctx)
|
|
1467
|
+
// 会话隔离(owner 2026-11-14,DEF-qqbot-20261112-01 修法①):锚定会话=入队快照
|
|
1468
|
+
// (drain 重入已带)或当前绑定;队列/忙锁按 (userId, 锚定会话) lane 粒度。
|
|
1469
|
+
// 声明于函数最顶:外层 catch 也引用 lane——放晚了错误路径会撞 TDZ;
|
|
1470
|
+
// 快照先于一切 await,之后绑定切走也不改本消息归属。
|
|
1471
|
+
const anchorSid = ctx.anchorSessionId ?? sessions.getSession(ctx.userId)?.sessionId ?? null
|
|
1472
|
+
const lane = laneOf(ctx.userId, anchorSid)
|
|
1473
|
+
// drain 重入/重启恢复的 ctx 已带受理账;若它在派发前的早退点(表单消费/命令/
|
|
1474
|
+
// 序号选择/审批挂起)被拦截,必须结清该账——否则台账残留 inflight,孤儿巡检
|
|
1475
|
+
// 会每 10 分钟刷一次告警(2026-11-05 实证:审批挂起导致队列 #1 卡成孤儿)。
|
|
1476
|
+
const releaseClaimed = (reason: SettleReason, note?: string): void => {
|
|
1477
|
+
if (!ctx.msgId || !claimedContexts.has(ctx)) return
|
|
1478
|
+
inflight.settle(ctx.msgId, undefined, reason)
|
|
1479
|
+
console.log(`[queue] release-early msg=${shortId(ctx.msgId)} reason=${reason}${note ? ` note=${note}` : ""}`)
|
|
1480
|
+
}
|
|
578
1481
|
try {
|
|
579
1482
|
// P1 修复(2026-11-03,外部复盘核验):拒绝时记录 openid——新用户无任何
|
|
580
1483
|
// 途径获取自己的 openid 填 ALLOWED_USERS,首配死锁;白名单内不打印(无需)。
|
|
581
1484
|
if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
|
|
582
1485
|
console.log(`[security] 拒绝非白名单用户:openid=${ctx.userId}(把它加入 ~/.openqq/.env 的 ALLOWED_USERS 后重启即开通)`)
|
|
583
|
-
await
|
|
1486
|
+
await notifyUser(ctx, "你不在允许使用的名单里")
|
|
584
1487
|
return
|
|
585
1488
|
}
|
|
586
1489
|
|
|
587
1490
|
const content = ctx.content.trim()
|
|
588
|
-
//
|
|
1491
|
+
// 纯图消息(无文字但有附件)同样放行;真空消息才丢。
|
|
1492
|
+
// DEF-qqbot-20261111-P2(owner 2026-11-12 裁定):纯表情不回静默——有据提示。
|
|
589
1493
|
if (!content && !ctx.attachments?.length) {
|
|
1494
|
+
if (ctx.emojiOnly) {
|
|
1495
|
+
await notifyUser(ctx, "收到表情 🙂 纯表情我无法理解,请补充文字(表情+文字一起发也可以)")
|
|
1496
|
+
}
|
|
590
1497
|
return
|
|
591
1498
|
}
|
|
592
1499
|
// 记录最近消息上下文:观察/过程推送的通道选择(被动优先)
|
|
@@ -596,8 +1503,8 @@ export function createBridge(
|
|
|
596
1503
|
// 不跳过会双发相同内容(2026-11-02 用户实证:首次 /help 回复两次)。
|
|
597
1504
|
if (!greeted.has(ctx.userId) && !isCommand(content)) {
|
|
598
1505
|
greeted.add(ctx.userId)
|
|
599
|
-
saveGreetedSet(greeted)
|
|
600
|
-
await
|
|
1506
|
+
saveGreetedSet(greeted, storageAppId ? roleFile("greeted.json") : undefined)
|
|
1507
|
+
await notifyUser(ctx, buildHelpText())
|
|
601
1508
|
}
|
|
602
1509
|
|
|
603
1510
|
// 权限审批决策优先于命令/普通消息:原 prompt 在 promptAndWait 里
|
|
@@ -610,29 +1517,48 @@ export function createBridge(
|
|
|
610
1517
|
return
|
|
611
1518
|
}
|
|
612
1519
|
|
|
613
|
-
// L 项:表单作答消费(选择弹窗 A/B/C/D
|
|
614
|
-
//
|
|
615
|
-
//
|
|
616
|
-
|
|
1520
|
+
// L 项:表单作答消费(选择弹窗 A/B/C/D)。命令一律放行——表单挂起期间
|
|
1521
|
+
// /queue /cancel 等管理命令不得被表单吞掉(DEF-qqbot-20261106-P3:表单
|
|
1522
|
+
// pending 曾把全部命令当答案消费,统一回「没看懂」且会话失能数分钟)。
|
|
1523
|
+
// 文字"允许"与表单答案的歧义:parsePermissionDecision 先行且要求存在
|
|
1524
|
+
// 待审权限才会消费;表单槽只消费非命令输入,互不串线。
|
|
1525
|
+
if (!isCommand(content) && formBridge.tryResolveText(ctx.userId, content)) {
|
|
1526
|
+
releaseClaimed("answered")
|
|
617
1527
|
return
|
|
618
1528
|
}
|
|
619
1529
|
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
1530
|
+
// 2026-11-10 夜间 UAT 实证修复(135 实测「😀/status」落入聊天分支):命令门判定
|
|
1531
|
+
// 前先经表情规范化——faceType 实体 + emoji 字符都剥,剥后形似命令则以命令受理。
|
|
1532
|
+
const gateContent = normalizeForCommandGate(content)
|
|
1533
|
+
if (isCommand(gateContent)) {
|
|
1534
|
+
const gateCtx = gateContent === content ? ctx : { ...ctx, content: gateContent }
|
|
1535
|
+
const reply = await handleCommand(gateCtx, commandContext)
|
|
1536
|
+
await notifyUser(ctx, reply)
|
|
1537
|
+
releaseClaimed("dropped")
|
|
623
1538
|
return
|
|
624
1539
|
}
|
|
625
1540
|
|
|
626
1541
|
const pendingReply = await maybeHandlePendingSelection(ctx, commandContext)
|
|
627
1542
|
if (pendingReply !== null) {
|
|
628
|
-
await
|
|
1543
|
+
await notifyUser(ctx, pendingReply)
|
|
1544
|
+
releaseClaimed("dropped")
|
|
629
1545
|
return
|
|
630
1546
|
}
|
|
631
1547
|
|
|
632
|
-
// 审批待决时,普通消息不进新 prompt
|
|
1548
|
+
// 审批待决时,普通消息不进新 prompt(会话正阻塞在审批上),重发审批菜单。
|
|
1549
|
+
// 菜单重发也走卡片优先(2026-11-05:只发文字会让用户永远看不到按钮入口)。
|
|
633
1550
|
const pendingPerm = perm.getPending(ctx.userId)
|
|
634
1551
|
if (pendingPerm) {
|
|
635
|
-
await
|
|
1552
|
+
const sentByCard = await sendApprovalCard(
|
|
1553
|
+
{ appId: config.qq.appId, clientSecret: config.qq.clientSecret },
|
|
1554
|
+
ctx,
|
|
1555
|
+
pendingPerm.request,
|
|
1556
|
+
pendingPerm.mainSessionId,
|
|
1557
|
+
).catch(() => false)
|
|
1558
|
+
if (!sentByCard) {
|
|
1559
|
+
await notifyUser(ctx, formatPermissionPrompt(pendingPerm.request, pendingPerm.mainSessionId))
|
|
1560
|
+
}
|
|
1561
|
+
releaseClaimed("blocked", "审批挂起,消息未派发")
|
|
636
1562
|
return
|
|
637
1563
|
}
|
|
638
1564
|
|
|
@@ -643,7 +1569,7 @@ export function createBridge(
|
|
|
643
1569
|
// 都是重复气泡);duplicate-intent 给一句短提示(首投方不会发,不构成重复)。
|
|
644
1570
|
if (ctx.msgId) {
|
|
645
1571
|
if (!claimedContexts.has(ctx)) {
|
|
646
|
-
const admitted =
|
|
1572
|
+
const admitted = inflight.claimDetailed(
|
|
647
1573
|
{ msgId: ctx.msgId, userId: ctx.userId, sessionId: "", text: content.slice(0, 300), at: Date.now() },
|
|
648
1574
|
{ fingerprint: messageFingerprint(ctx.userId, intentKey) },
|
|
649
1575
|
)
|
|
@@ -654,9 +1580,9 @@ export function createBridge(
|
|
|
654
1580
|
if (admitted === "duplicate-intent") {
|
|
655
1581
|
console.log(`[admit-dedupe] 同内容意图在途,本次重发已忽略 msgId=${ctx.msgId}`)
|
|
656
1582
|
// P3(2026-11-03,外部复盘核验 R4):提示带在途内容摘要提升体感
|
|
657
|
-
const pend =
|
|
1583
|
+
const pend = inflight.pending().find((e) => e.fingerprint === messageFingerprint(ctx.userId, intentKey))
|
|
658
1584
|
const digest = pend ? `(在途内容:${previewText(pend.text)})` : ""
|
|
659
|
-
await
|
|
1585
|
+
await notifyUser(ctx, `你的相同问题正在处理中${digest},本次重发已忽略`)
|
|
660
1586
|
return
|
|
661
1587
|
}
|
|
662
1588
|
claimedContexts.add(ctx)
|
|
@@ -664,16 +1590,16 @@ export function createBridge(
|
|
|
664
1590
|
claimedMsgId = ctx.msgId
|
|
665
1591
|
}
|
|
666
1592
|
|
|
667
|
-
if (busyUsers.has(
|
|
668
|
-
const duplicateIntent = activeIntents.get(
|
|
1593
|
+
if (busyUsers.has(lane) && !claimedContexts.has(ctx)) {
|
|
1594
|
+
const duplicateIntent = activeIntents.get(lane) === intentKey || msgQueue.hasIntent(lane, intentKey)
|
|
669
1595
|
if (duplicateIntent) {
|
|
670
|
-
|
|
1596
|
+
inflight.settle(ctx.msgId, undefined, "duplicate-intent") // 重复意图已有原回合负责,直接结清,禁止恢复时再跑
|
|
671
1597
|
console.log(`[bridge] 相同意图已在执行/队列,跳过 msgId=${ctx.msgId}`)
|
|
672
1598
|
return
|
|
673
1599
|
}
|
|
674
1600
|
}
|
|
675
1601
|
|
|
676
|
-
if (busyUsers.has(
|
|
1602
|
+
if (busyUsers.has(lane)) {
|
|
677
1603
|
// Q1(学习 pi-qqbot 队列 UX):忙碌不再拒绝——FIFO 排队,回合结束自动执行
|
|
678
1604
|
// 自检补强:入队即下载附件——QQ 签名 URL 短时效,drain 时下载必过期
|
|
679
1605
|
if (ctx.attachments?.length && !ctx.preparedAttachments) {
|
|
@@ -681,22 +1607,30 @@ export function createBridge(
|
|
|
681
1607
|
getAccessToken(config.qq.appId, config.qq.clientSecret),
|
|
682
1608
|
)
|
|
683
1609
|
}
|
|
684
|
-
const queued = msgQueue.push(ctx.userId, ctx)
|
|
1610
|
+
const queued = msgQueue.push(lane, ctx.userId, anchorSid ?? undefined, ctx)
|
|
685
1611
|
if (!queued) {
|
|
686
|
-
if (claimedMsgId)
|
|
687
|
-
|
|
1612
|
+
if (claimedMsgId) inflight.settle(claimedMsgId, undefined, "queue-full") // 已满回执即终态,不能留账让启动对账再次执行
|
|
1613
|
+
console.log(`[queue] reject user=${ctx.userId.slice(0, 8)}… msg=${shortId(ctx.msgId)} reason=full size=${msgQueue.size(lane)}/${QUEUE_MAX}`)
|
|
1614
|
+
await notifyUser(ctx, formatQueueFullReceipt(QUEUE_MAX))
|
|
688
1615
|
return
|
|
689
1616
|
}
|
|
1617
|
+
if (ctx.msgId) {
|
|
1618
|
+
// 入队即锚定落账:queued 级也带 sessionId(重启恢复按 lane 归组)
|
|
1619
|
+
inflight.markStage(ctx.msgId, "queued", { queueId: queued.job.id, enqueuedAt: queued.job.enqueuedAt, ...(anchorSid ? { sessionId: anchorSid } : {}) })
|
|
1620
|
+
}
|
|
1621
|
+
console.log(
|
|
1622
|
+
`[queue] enqueue user=${ctx.userId.slice(0, 8)}… lane=${anchorSid ? shortId(anchorSid) : "∅"} qid=${queued.job.id} msg=${shortId(ctx.msgId)} ahead=${queued.ahead} size=${msgQueue.size(lane)}/${QUEUE_MAX}`,
|
|
1623
|
+
)
|
|
690
1624
|
// 入队前已由 claimInflight 落账;drain 重入时回填 sessionId,不重复写账。
|
|
691
|
-
await
|
|
1625
|
+
await notifyUser(
|
|
692
1626
|
ctx,
|
|
693
|
-
`已排队 #${queued.job.id}${queued.ahead > 0 ?
|
|
1627
|
+
`已排队 #${queued.job.id}(第 ${queued.ahead + 1} 位${queued.ahead > 0 ? `,前面还有 ${queued.ahead} 条` : ""}),当前任务结束后自动执行。\n发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`,
|
|
694
1628
|
)
|
|
695
1629
|
return
|
|
696
1630
|
}
|
|
697
1631
|
|
|
698
|
-
activeIntents.set(
|
|
699
|
-
busyUsers.add(
|
|
1632
|
+
activeIntents.set(lane, intentKey)
|
|
1633
|
+
busyUsers.add(lane)
|
|
700
1634
|
|
|
701
1635
|
// 修复⑦(2026-11-03):受理即回执——前台回合立刻短句确认,消除静默期
|
|
702
1636
|
// (expA 实证:无受理回执时用户观感=「没有任何回复」)。Queue 路径此前
|
|
@@ -704,7 +1638,7 @@ export function createBridge(
|
|
|
704
1638
|
// 通知——这三处都不进本分支,同一 intent 不重复点头。
|
|
705
1639
|
// (同日迭代:改为开关制、默认不发——见顶部 ackReceiptEnabled。)
|
|
706
1640
|
if (ackReceiptEnabled && ctx.msgId && !drainReentries.has(ctx)) {
|
|
707
|
-
await
|
|
1641
|
+
await notifyUser(ctx, "✅ 已收到,正在处理,完成后自动回复你")
|
|
708
1642
|
}
|
|
709
1643
|
|
|
710
1644
|
// B3(2026-10-29 同步升级):C2C typing 指示——长回合处理中给用户
|
|
@@ -720,10 +1654,26 @@ export function createBridge(
|
|
|
720
1654
|
let turnStart = 0
|
|
721
1655
|
let trackId = "" // R 项:在途台账跟踪键(try/catch 跨块可见)
|
|
722
1656
|
let promptId = "" // 修复⑧:本回合 user 消息 id(直答归属锚点)
|
|
1657
|
+
let anchorDirectory: string | undefined = undefined // 权限链目录(catch 转后台续作也要用,随 try 内赋值)
|
|
723
1658
|
try {
|
|
724
|
-
|
|
725
|
-
|
|
1659
|
+
// 会话隔离:派发跟锚定不跟漂移——锚定会话直发(哪怕绑定已切走);
|
|
1660
|
+
// 无锚定(null lane,从未绑定)才 getOrCreate 解析并落新绑定。
|
|
1661
|
+
if (anchorSid) {
|
|
1662
|
+
sessionId = anchorSid
|
|
1663
|
+
} else {
|
|
1664
|
+
const session = await sessions.getOrCreate(ctx.userId)
|
|
1665
|
+
sessionId = session.sessionId
|
|
1666
|
+
}
|
|
1667
|
+
ctx.anchorSessionId = sessionId
|
|
726
1668
|
sessionLastActivity.set(sessionId, Date.now())
|
|
1669
|
+
// DEF-qqbot-20261112-1 同口径:权限链目录必须是「锚定会话自身」的目录——
|
|
1670
|
+
// 锚定≠绑定时映射缓存指向错会话,从服务端回读锚定会话目录(失败回落绑定缓存)。
|
|
1671
|
+
anchorDirectory = sessions.getSession(ctx.userId)?.directory
|
|
1672
|
+
if (sessions.getSession(ctx.userId)?.sessionId !== sessionId) {
|
|
1673
|
+
anchorDirectory =
|
|
1674
|
+
(await client.session.get({ path: { id: sessionId } }).catch(() => undefined))?.data?.location?.directory ??
|
|
1675
|
+
anchorDirectory
|
|
1676
|
+
}
|
|
727
1677
|
|
|
728
1678
|
// 缺口 1(引用上下文,吸收自官方 quote-ref 中间件):本条消息的引用解析
|
|
729
1679
|
// 先于本条登记(顺序不可反:本条入缓存后才能被后续消息引用)
|
|
@@ -751,27 +1701,72 @@ export function createBridge(
|
|
|
751
1701
|
// 缺口 1:引用上文注入——让 AI 明确知道用户引用了哪条消息
|
|
752
1702
|
// Q4 回退(用户评审三连否):远程备注注入会渲染成独立用户消息、造成"一事两交互",
|
|
753
1703
|
// 画蛇添足。不再注入任何前缀;场景上下文如需要改走 opencode 隐式 instructions 通道。
|
|
754
|
-
const promptText =
|
|
1704
|
+
const promptText =
|
|
1705
|
+
(ctx.quoteText ? `> 引用上文:${ctx.quoteText}\n\n${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT
|
|
755
1706
|
// R 项(2026-10-30):在途台账落账——派发前记录,送达才销账;
|
|
756
1707
|
// 进程中途死亡时启动对账据此恢复。重派回合无真实 msgId,用合成键跟踪。
|
|
757
1708
|
trackId = ctx.msgId || `redispatch-${sessionId}-${turnStart}`
|
|
758
|
-
|
|
759
|
-
|
|
1709
|
+
inflight.record({ msgId: trackId, userId: ctx.userId, sessionId, text: content.slice(0, 300), at: Date.now() })
|
|
1710
|
+
inflight.markStage(trackId, "dispatched", { sessionId })
|
|
1711
|
+
console.log(`[journal] dispatch user=${ctx.userId.slice(0, 8)}… msg=${shortId(trackId)} sid=${shortId(sessionId)}`)
|
|
1712
|
+
let replyText: string
|
|
1713
|
+
{
|
|
1714
|
+
replyText = await client.promptAndWait(sessionId, promptText, {
|
|
760
1715
|
files: files.length ? files : undefined,
|
|
1716
|
+
// DEF-qqbot-20261112-1:权限轮询/裁决携带会话项目目录(引擎待审按
|
|
1717
|
+
// location 实例分仓,裸查失明/裸 reply 404——见 design §3.6 权限实例上下文)。
|
|
1718
|
+
// 会话隔离:目录=锚定会话自身目录(锚定≠绑定时已从服务端回读)。
|
|
1719
|
+
directory: anchorDirectory,
|
|
761
1720
|
// 修复⑧:受领即落台账锚点 + 本地闭合变量(前台超时转后台等待要带上)
|
|
762
1721
|
onAccepted: (info) => {
|
|
763
1722
|
promptId = info.promptId
|
|
764
|
-
|
|
1723
|
+
inflight.markPromptId(trackId, info.promptId)
|
|
1724
|
+
// DEF-20261118-P6 来源身份守卫:promptId=用户消息 id,入镜像 QQ 派发册——
|
|
1725
|
+
// 网关 RESUME 迟到重放的完成事件穿透时序锁后,仍被身份核对拦下(不重复摘要)。
|
|
1726
|
+
mirror.markQqPrompt(sessionId, info.promptId)
|
|
1727
|
+
console.log(`[journal] running msg=${shortId(trackId)} prompt=${shortId(info.promptId)}`)
|
|
765
1728
|
},
|
|
766
1729
|
onPermission: (req) => perm.waitForDecision(ctx, req, sessionId),
|
|
767
1730
|
onPermissionReplied: (d) => {
|
|
768
|
-
|
|
1731
|
+
// 拒绝与允许的后续语义不同:拒绝=该动作不执行,回合继续走其余步骤。
|
|
1732
|
+
const text = d === "reject"
|
|
1733
|
+
? "已拒绝,该操作不会执行;AI 将继续其余步骤"
|
|
1734
|
+
: `已${DECISION_LABELS[d]},AI 将继续执行…`
|
|
1735
|
+
void safeDeliver(ctx, text)
|
|
769
1736
|
},
|
|
770
|
-
onPermissionConflict: () => {
|
|
771
|
-
|
|
1737
|
+
onPermissionConflict: (decision) => {
|
|
1738
|
+
// 债务D2:请求已被其他端(桌面/自动规则)先处理——不是错误,任务继续。
|
|
1739
|
+
// 2026-11-05 实证修正:立即告警是净噪音(用户点击后任务正常完成仍收到
|
|
1740
|
+
// "状态不明请重发"的恐吓文案)。改为 10 分钟零进展保险网——届时会话仍
|
|
1741
|
+
// 无任何新消息才告警;任务正常产出时保持安静。
|
|
1742
|
+
// 2026-11-07 例外(DEF-qqbot-20261107-1):用户点了「拒绝」却 404 =
|
|
1743
|
+
// 引擎先放行后执行,必须立刻明说,不能静默(否则用户误以为已阻断)。
|
|
1744
|
+
console.log(`[bridge] 审批冲突(他端已处理),任务继续 msgId=${shortId(ctx.msgId)} decision=${decision}`)
|
|
1745
|
+
const notice = formatPermissionConflictNotice(decision)
|
|
1746
|
+
if (notice) void safeDeliver(ctx, notice)
|
|
1747
|
+
const conflictAt = Date.now()
|
|
1748
|
+
setTimeout(() => {
|
|
1749
|
+
void (async () => {
|
|
1750
|
+
try {
|
|
1751
|
+
const listJson = await client.session.messages({ path: { id: sessionId } })
|
|
1752
|
+
const msgs = listJson?.data ?? []
|
|
1753
|
+
const progressed = msgs.some((m) => (m.time?.created ?? 0) >= conflictAt)
|
|
1754
|
+
if (!progressed) {
|
|
1755
|
+
await safeDeliver(
|
|
1756
|
+
ctx,
|
|
1757
|
+
"⚠️ 该审批请求状态不明(可能在桌面端处理或已超时),且任务长时间无进展。如命令未执行,请重新发起原操作",
|
|
1758
|
+
)
|
|
1759
|
+
}
|
|
1760
|
+
} catch {
|
|
1761
|
+
/* 保险网探测失败不打扰用户 */
|
|
1762
|
+
}
|
|
1763
|
+
})()
|
|
1764
|
+
}, 10 * 60_000).unref?.()
|
|
772
1765
|
},
|
|
773
|
-
|
|
1766
|
+
})
|
|
1767
|
+
}
|
|
774
1768
|
|
|
1769
|
+
let turnDelivered = false // DEF-qqbot-20261110-9:实际出站与否决定销账口径
|
|
775
1770
|
if (replyText.trim()) {
|
|
776
1771
|
// 缺口 4:AI 主动发文件——QQ_SEND_FILE 标记行拦截发送文件,剩余文本照送
|
|
777
1772
|
const extracted = extractSendFileMarkers(replyText)
|
|
@@ -786,11 +1781,51 @@ export function createBridge(
|
|
|
786
1781
|
}
|
|
787
1782
|
}
|
|
788
1783
|
// 超长回合可能已超被动窗口:deliver 被动失败自动降级主动,答案不丢
|
|
789
|
-
|
|
1784
|
+
// 直答出口统一脱敏(DEF-qqbot-20261106-2):与 history/mirror/form 同一脱敏器,
|
|
1785
|
+
// 防 AI 复述的密钥/令牌经直答气泡明文外泄。
|
|
1786
|
+
if (extracted.text) turnDelivered = await safeDeliver(ctx, redactSecrets(extracted.text))
|
|
1787
|
+
}
|
|
1788
|
+
// DEF-qqbot-20261110-9(2026-11-10 回归实证):有正文但被 24h 去重拦截时
|
|
1789
|
+
// 不得记 answered——那是「台账假已答、用户侧零内容」。改记 error 并给用户交代。
|
|
1790
|
+
// 会话隔离(owner 2026-11-14):推送门拦截≠未送达——结果已入锚定会话历史
|
|
1791
|
+
// (QQ 只呈现当前绑定会话),按 answered 结清;仅 24h 去重拦截记 error。
|
|
1792
|
+
if (replyText.trim() && !turnDelivered) {
|
|
1793
|
+
if (ctx.anchorSessionId && !isBoundSession(ctx.userId, ctx.anchorSessionId)) {
|
|
1794
|
+
console.log(`[push-gate] 回合结果按历史可回读结清 answered msg=${shortId(trackId)}`)
|
|
1795
|
+
inflight.settle(trackId, undefined, "answered")
|
|
1796
|
+
} else {
|
|
1797
|
+
await safeDeliver(ctx, "⚠️ 本轮结果与 24h 内已发送内容重复,已被防重拦截(未重复投递)。如非预期请重发或换个说法")
|
|
1798
|
+
inflight.settle(trackId, undefined, "error")
|
|
1799
|
+
}
|
|
1800
|
+
} else {
|
|
1801
|
+
inflight.settle(trackId, undefined, "answered")
|
|
790
1802
|
}
|
|
791
|
-
settleInflight(trackId) // R 项:回合处理到终态(答案已投递尝试),销账
|
|
792
1803
|
} catch (error) {
|
|
793
|
-
if (
|
|
1804
|
+
if (error instanceof SupersededError) {
|
|
1805
|
+
// DEF-qqbot-20261107-P2:同会话新输入(桌面端/他端直注)接管了本回合——
|
|
1806
|
+
// runner 接管语义下本回合已被打断且不会有正文。给用户可见交代并按
|
|
1807
|
+
// superseded 销账:不转后台(任务已死,「继续执行」是谎言)、不占位符、
|
|
1808
|
+
// 不挂 30 分钟超时。账本结清后 finally 正常 drain 队列。
|
|
1809
|
+
// P0-1 补修(与 bgWait rescueThenSettle 同族):前台被接管同样先核实
|
|
1810
|
+
// 「已完成未投递」——完成于竞态窗口的答案先补投,不得谎称未产出。
|
|
1811
|
+
let rescuedText = ""
|
|
1812
|
+
try {
|
|
1813
|
+
const probe = await client.session.messages({ path: { id: sessionId } })
|
|
1814
|
+
const turn = turnStateOf(probe?.data ?? [], promptId, 0)
|
|
1815
|
+
if (turn.text) rescuedText = turn.text
|
|
1816
|
+
} catch {
|
|
1817
|
+
/* 探测失败落到原 superseded 交代 */
|
|
1818
|
+
}
|
|
1819
|
+
if (rescuedText) {
|
|
1820
|
+
console.log(`[bridge] 前台接管前抢救:回合已完成未投递,先补投 msg=${shortId(trackId)}`)
|
|
1821
|
+
await safeDeliver(ctx, `📤 你发来新消息前,上一回合已完成,结果如下:\n\n${rescuedText}`).catch(() => {})
|
|
1822
|
+
inflight.settle(trackId, undefined, "answered")
|
|
1823
|
+
} else {
|
|
1824
|
+
console.log(`[bridge] 回合被同会话新输入接管(superseded)msg=${shortId(trackId)} sid=${shortId(sessionId)}`)
|
|
1825
|
+
await safeDeliver(ctx, "⚠️ 上一条任务被同会话的新输入打断,未产出结果;如需结果请重新发送")
|
|
1826
|
+
inflight.settle(trackId, undefined, "superseded")
|
|
1827
|
+
}
|
|
1828
|
+
} else if (sessionId && turnStart > 0 && error instanceof Error && error.message.includes("响应超时")) {
|
|
794
1829
|
// 前台时限到 ≠ 放弃:任务继续跑,转入后台等待(SSE + 5 分钟轮询兜底,
|
|
795
1830
|
// 最长 24 小时),完成时经 deliver 被动/主动回传 —— 12 小时长任务的答案也不丢。
|
|
796
1831
|
// R 项:不销账——bgWait 完成投递时才销(完成前死亡由启动对账接管)。
|
|
@@ -798,29 +1833,45 @@ export function createBridge(
|
|
|
798
1833
|
ctx,
|
|
799
1834
|
"⏳ 回合超过前台时限,已转后台等待:任务继续执行,完成即回传结果(最长 24 小时)。期间可用 /history 查看进展。",
|
|
800
1835
|
)
|
|
801
|
-
startBackgroundWait(sessionId, ctx, turnStart, trackId, promptId)
|
|
1836
|
+
startBackgroundWait(sessionId, ctx, turnStart, trackId, promptId, turnStart, anchorDirectory)
|
|
1837
|
+
} else if (isSessionBusyError(error)) {
|
|
1838
|
+
// 会话被占用(-32603,可能来自桌面端/他端并发)。不再把 Internal error 原样
|
|
1839
|
+
// 甩给用户,给可操作路径;每用户串行队列已挡掉我方自撞,这条只兜他端占用。
|
|
1840
|
+
console.error(`[bridge] 会话被占用(active prompt)sid=${shortId(sessionId)}: ${toErrorMessage(error)}`)
|
|
1841
|
+
await safeDeliver(
|
|
1842
|
+
ctx,
|
|
1843
|
+
"⏳ 该会话正有回合在执行(可能是桌面端在跑,或上一轮尚未结束),本轮未重复发起。\n发 /stop 可中止当前回合后重试。",
|
|
1844
|
+
)
|
|
1845
|
+
inflight.settle(trackId, undefined, "error")
|
|
802
1846
|
} else {
|
|
803
1847
|
// Q3:额度/鉴权错误给救援话术(报类别+原文+恢复路径),不死胡同报错
|
|
804
1848
|
const errText = toErrorMessage(error)
|
|
805
1849
|
const rescue = rescueText(classifyProviderError(errText), errText)
|
|
806
1850
|
await safeDeliver(ctx, rescue ?? `处理失败:${errText}`)
|
|
807
|
-
|
|
1851
|
+
inflight.settle(trackId, undefined, "error") // R 项:失败反馈已送达 = 终态,销账
|
|
808
1852
|
}
|
|
809
1853
|
} finally {
|
|
810
1854
|
if (sessionId) unsubscribeSession(sessionId, ctx.userId) // /watch 若仍挂着则保留订阅
|
|
811
1855
|
// 镜像解锁:转后台的任务由 bgWait 完成时解锁,其余延迟 5 秒(SSE 事件宽限)
|
|
812
1856
|
if (sessionId && !bgWaits.has(sessionId)) mirror.scheduleUnlock(sessionId)
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
1857
|
+
// 会话隔离:释放本消息 lane;派发解析出的会话与锚定不同(null lane 新建会话)时一并释放
|
|
1858
|
+
busyUsers.delete(lane)
|
|
1859
|
+
if (sessionId && laneOf(ctx.userId, sessionId) !== lane) busyUsers.delete(laneOf(ctx.userId, sessionId))
|
|
1860
|
+
if (activeIntents.get(lane) === intentKey) activeIntents.delete(lane)
|
|
1861
|
+
// 队列完成回执(默认关闭):只对 drain 重入的条目发,普通消息不刷屏。
|
|
1862
|
+
const finishedQueueId = queueIdOfCtx.get(ctx)
|
|
1863
|
+
if (finishedQueueId !== undefined && QUEUE_RECEIPTS_ENABLED) {
|
|
1864
|
+
await notifyUser(ctx, `队列 #${finishedQueueId} 完成(剩余 ${msgQueue.sizeUser(ctx.userId)} 条)`)
|
|
1865
|
+
}
|
|
1866
|
+
// Q1:回合结束(成功/失败/转后台)→ 自动执行该 lane 下一条;
|
|
816
1867
|
// 转后台等待的会话保持串行——由 bgWait 完成时再 drain(不与前序后台任务并发)
|
|
817
|
-
if (sessionId && !bgWaits.has(sessionId)) void drainQueue(ctx.userId)
|
|
1868
|
+
if (sessionId && !bgWaits.has(sessionId)) void drainQueue(ctx.userId, sessionId)
|
|
818
1869
|
}
|
|
819
1870
|
} catch (error) {
|
|
820
1871
|
// 认领后、内层回合兜底之前的异常(如排队附件预下载失败)也必须结清,
|
|
821
1872
|
// 否则重启对账会把已反馈失败的消息再执行一次。
|
|
822
|
-
if (claimedMsgId)
|
|
823
|
-
if (activeIntents.get(
|
|
1873
|
+
if (claimedMsgId) inflight.settle(claimedMsgId, undefined, "error")
|
|
1874
|
+
if (activeIntents.get(lane) === intentKey) activeIntents.delete(lane)
|
|
824
1875
|
console.error("[bridge] handleMessage failed:", error)
|
|
825
1876
|
try {
|
|
826
1877
|
await sendReply(ctx, `处理消息失败:${toErrorMessage(error)}`)
|
|
@@ -832,30 +1883,113 @@ export function createBridge(
|
|
|
832
1883
|
|
|
833
1884
|
// R 项(2026-10-30 重启丢消息事故修复):启动对账——查在途台账里"已派发未销账"
|
|
834
1885
|
// 的回合,按会话历史分类处置:已有答案→补投;仍在执行→重挂后台等待;
|
|
835
|
-
// 从未到达 opencode
|
|
836
|
-
//
|
|
1886
|
+
// 从未到达 opencode→窗口内自动重派(超期通知请用户重发)。
|
|
1887
|
+
// 2026-11-05(队列/台账可观测性):从未进会话的在途账 = 重启前还在排队,
|
|
1888
|
+
// 先按 enqueuedAt/at 重建内存队列(保留 #id 与顺序),不再直接结清丢弃。
|
|
837
1889
|
async function recoverInflightRounds(): Promise<void> {
|
|
838
|
-
const pending =
|
|
1890
|
+
const pending = inflight.pending()
|
|
839
1891
|
if (pending.length === 0) return
|
|
840
1892
|
console.log(`[bridge] 启动对账:${pending.length} 条在途消息待恢复`)
|
|
1893
|
+
|
|
1894
|
+
const restoreWindow = redispatchMaxAgeMs()
|
|
1895
|
+
const restorable = new Set<string>()
|
|
1896
|
+
const queueCandidates = pending.filter(
|
|
1897
|
+
(e) => !e.sessionId && !e.promptId && Date.now() - e.at <= restoreWindow,
|
|
1898
|
+
)
|
|
1899
|
+
if (queueCandidates.length > 0) {
|
|
1900
|
+
// 会话隔离(owner 2026-11-14):按 (userId, 锚定 sessionId) 分 lane 重建——
|
|
1901
|
+
// 2026-11-14 起 queued 级入队即落 sessionId 快照;旧账无 sessionId 归 null lane。
|
|
1902
|
+
const byLane = new Map<string, InflightEntry[]>()
|
|
1903
|
+
for (const e of queueCandidates) {
|
|
1904
|
+
const lk = laneOf(e.userId, e.sessionId)
|
|
1905
|
+
const list = byLane.get(lk) ?? []
|
|
1906
|
+
list.push(e)
|
|
1907
|
+
byLane.set(lk, list)
|
|
1908
|
+
}
|
|
1909
|
+
for (const [lk, list] of byLane) {
|
|
1910
|
+
const uid = userIdOfLane(lk)
|
|
1911
|
+
list.sort((a, b) => (a.enqueuedAt ?? a.at) - (b.enqueuedAt ?? b.at))
|
|
1912
|
+
const jobs = list.map((e) => ({
|
|
1913
|
+
...(e.queueId !== undefined ? { id: e.queueId } : {}),
|
|
1914
|
+
// 锚定取条目自身会话(QQ_LANE_SCOPE=per-peer 时同 lane 混多会话,lane 级 sid 为空会丢锚)
|
|
1915
|
+
...(e.sessionId ? { sessionId: e.sessionId } : {}),
|
|
1916
|
+
ctx: {
|
|
1917
|
+
type: "c2c" as const,
|
|
1918
|
+
userId: uid,
|
|
1919
|
+
msgId: e.msgId,
|
|
1920
|
+
content: e.text,
|
|
1921
|
+
timestamp: String(e.at),
|
|
1922
|
+
...(e.sessionId ? { anchorSessionId: e.sessionId } : {}),
|
|
1923
|
+
},
|
|
1924
|
+
text: e.text,
|
|
1925
|
+
enqueuedAt: e.enqueuedAt ?? e.at,
|
|
1926
|
+
}))
|
|
1927
|
+
const restored = msgQueue.restore(lk, uid, sessionIdOfLane(lk), jobs)
|
|
1928
|
+
if (restored > 0) {
|
|
1929
|
+
const restoredJobs = msgQueue.list(lk).slice(-restored)
|
|
1930
|
+
for (const job of restoredJobs) {
|
|
1931
|
+
// drain 重入必须跳过重复认领,否则 duplicate-msgid 会把恢复条目静默丢掉。
|
|
1932
|
+
claimedContexts.add(job.ctx)
|
|
1933
|
+
// force:旧 stage(如 dispatched 空账)在进程换代后不再可信,恢复即回到 queued。
|
|
1934
|
+
// 会话回填取 job 锚定(QQ_LANE_SCOPE=user 时 lane 级 sid 为空,锚在 job 上)
|
|
1935
|
+
const jobSid = job.sessionId
|
|
1936
|
+
inflight.markStage(job.ctx.msgId, "queued", { queueId: job.id, enqueuedAt: job.enqueuedAt, ...(jobSid ? { sessionId: jobSid } : {}) }, { force: true })
|
|
1937
|
+
restorable.add(job.ctx.msgId)
|
|
1938
|
+
}
|
|
1939
|
+
console.log(
|
|
1940
|
+
`[queue] restore user=${uid.slice(0, 8)}… lane=${sessionIdOfLane(lk) ? shortId(sessionIdOfLane(lk)!) : "∅"} count=${restored} window=${Math.round(restoreWindow / 60_000)}m`,
|
|
1941
|
+
)
|
|
1942
|
+
await deliver(
|
|
1943
|
+
ctxForUser(uid),
|
|
1944
|
+
`🔄 重启恢复:${restored} 条排队消息已恢复(发 /queue 查看;/queue clear 可清空)`,
|
|
1945
|
+
)
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
// DEF 队列容量拒收文案误标修复(owner 2026-11-14「全修剩下缺陷」批,P6):
|
|
1951
|
+
// 窗口内候选被 QUEUE_MAX 截断的真实原因=队列已满,非「超过恢复窗口」——先单独结清
|
|
1952
|
+
// queue-full + 准确文案,防止流进下方空账分支吃误标归因(00:24 seed 实测 27 进 20 截 7)。
|
|
1953
|
+
const capacityRejected = queueCandidates.filter((e) => !restorable.has(e.msgId))
|
|
1954
|
+
if (capacityRejected.length > 0) {
|
|
1955
|
+
const byUser = new Map<string, InflightEntry[]>()
|
|
1956
|
+
for (const e of capacityRejected) {
|
|
1957
|
+
const list = byUser.get(e.userId) ?? []
|
|
1958
|
+
list.push(e)
|
|
1959
|
+
byUser.set(e.userId, list)
|
|
1960
|
+
}
|
|
1961
|
+
for (const [uid, list] of byUser) {
|
|
1962
|
+
const first = list[0]!
|
|
1963
|
+
const preview = first.text.length > 50 ? `${first.text.slice(0, 50)}…` : first.text
|
|
1964
|
+
await deliver(
|
|
1965
|
+
ctxForUser(uid),
|
|
1966
|
+
`🔄 重启恢复:${list.length} 条排队消息因队列已满(上限 ${QUEUE_MAX} 条)未恢复(如「${preview}」)。等队列消化后再发,或 /queue clear 后重发`,
|
|
1967
|
+
)
|
|
1968
|
+
}
|
|
1969
|
+
for (const e of capacityRejected) {
|
|
1970
|
+
inflight.settle(e.msgId, undefined, "queue-full")
|
|
1971
|
+
console.log(`[bridge] 启动对账:容量拒收结清 queue-full msgId=${e.msgId}`)
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
|
|
841
1975
|
for (const entry of pending) {
|
|
1976
|
+
if (restorable.has(entry.msgId)) continue
|
|
842
1977
|
const ageMs = Date.now() - entry.at
|
|
843
1978
|
if (ageMs > INFLIGHT_MAX_AGE_MS) {
|
|
844
|
-
|
|
1979
|
+
inflight.settle(entry.msgId, undefined, "expired") // 超 24h:清账不追溯
|
|
845
1980
|
continue
|
|
846
1981
|
}
|
|
847
1982
|
// 恢复投递走主动通道(原 msgId 的被动窗口早已过期)
|
|
848
1983
|
const ctx: MessageContext = { type: "c2c", userId: entry.userId, msgId: "", content: entry.text }
|
|
849
|
-
// 修复③(2026-11-03):排队空账治本——sessionId
|
|
850
|
-
//
|
|
851
|
-
// 且按用户重投哲学不得自动重派执行——只清账通知,请用户重发。
|
|
1984
|
+
// 修复③(2026-11-03):排队空账治本——sessionId 为空=「从未进过会话」。
|
|
1985
|
+
// 2026-11-05:窗口内的已在上方恢复进队列;走到这里的只剩超窗空账,只清账通知。
|
|
852
1986
|
if (!entry.sessionId) {
|
|
853
|
-
|
|
1987
|
+
inflight.settle(entry.msgId, undefined, "expired")
|
|
854
1988
|
await deliver(
|
|
855
1989
|
ctx,
|
|
856
|
-
`⚠️
|
|
1990
|
+
`⚠️ 重启前队列里有一条消息超过恢复窗口未执行(「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」)。为避免执行陈旧意图未自动重派,需要的话请重发一次`,
|
|
857
1991
|
)
|
|
858
|
-
console.log(`[bridge]
|
|
1992
|
+
console.log(`[bridge] 启动对账:超窗排队空账已通知销账 msgId=${entry.msgId}`)
|
|
859
1993
|
continue
|
|
860
1994
|
}
|
|
861
1995
|
try {
|
|
@@ -863,22 +1997,42 @@ export function createBridge(
|
|
|
863
1997
|
const cls = classifyInflight(entry, listJson.data)
|
|
864
1998
|
if (cls.kind === "answered") {
|
|
865
1999
|
await deliver(ctx, `🔄 重启补投:你之前的消息已有答案\n\n${cls.answer}`)
|
|
866
|
-
|
|
2000
|
+
inflight.settle(entry.msgId, undefined, "answered")
|
|
867
2001
|
console.log(`[bridge] 启动对账:已补投答案 msgId=${entry.msgId}`)
|
|
868
2002
|
} else if (cls.kind === "running") {
|
|
2003
|
+
// 2026-11-09 透明度补强:原执行进程已死时,回合「存活」以服务端为准——
|
|
2004
|
+
// 后台等待有 REST 轮询兜底,但不再是「同一个活着的回合」,日志必须说清。
|
|
2005
|
+
if (entry.ownerPid !== undefined && !isPidAlive(entry.ownerPid)) {
|
|
2006
|
+
console.log(
|
|
2007
|
+
`[bridge] 启动对账:原执行进程 ${entry.ownerPid} 已退出,回合状态以服务端会话为准(后台等待+轮询兜底)msgId=${entry.msgId}`,
|
|
2008
|
+
)
|
|
2009
|
+
}
|
|
869
2010
|
// 跨重启也要保持 QQ 回合同一身份:后台直答完成时,镜像不得再投摘要。
|
|
870
2011
|
mirror.beginTurn(entry.sessionId)
|
|
2012
|
+
// DEF-20261118-P6:重挂的后台回合同属 QQ 派发来源,promptId 一并入册——
|
|
2013
|
+
// 重启后 RESUME 重放的完成事件同样被身份守卫拦下。
|
|
2014
|
+
if (entry.promptId) mirror.markQqPrompt(entry.sessionId, entry.promptId)
|
|
871
2015
|
// 不单独发“仍在执行”通知;完成时统一回传最终答案,避免通知也占一条回复。
|
|
872
|
-
|
|
2016
|
+
// 续作次数从台账 resumeCount 续算(重启不洗白 owner「单任务续作≤3次」裁定)。
|
|
2017
|
+
startBackgroundWait(
|
|
2018
|
+
entry.sessionId,
|
|
2019
|
+
ctx,
|
|
2020
|
+
entry.at,
|
|
2021
|
+
entry.msgId,
|
|
2022
|
+
entry.promptId ?? "",
|
|
2023
|
+
entry.at,
|
|
2024
|
+
sessions.getSession(entry.userId)?.directory,
|
|
2025
|
+
entry.resumeCount ?? 0,
|
|
2026
|
+
)
|
|
873
2027
|
console.log(`[bridge] 启动对账:在途任务已重挂后台等待 msgId=${entry.msgId}`)
|
|
874
2028
|
} else if (ageMs <= redispatchMaxAgeMs()) {
|
|
875
|
-
|
|
2029
|
+
inflight.settle(entry.msgId, undefined, "redispatch") // 旧账结清,重派回合走新账(合成 trackId)
|
|
876
2030
|
await deliver(ctx, `🔄 重启恢复:重新处理你之前的消息「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」`)
|
|
877
2031
|
void handleMessage(ctx)
|
|
878
2032
|
console.log(`[bridge] 启动对账:丢失消息已重派 msgId=${entry.msgId}`)
|
|
879
2033
|
} else {
|
|
880
2034
|
await deliver(ctx, `⚠️ 此前重启期间丢失一条你的消息「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」(超过自动重派窗口未重发),需要的话请重发一次`)
|
|
881
|
-
|
|
2035
|
+
inflight.settle(entry.msgId, undefined, "expired")
|
|
882
2036
|
console.log(`[bridge] 启动对账:超期消息仅通知 msgId=${entry.msgId}`)
|
|
883
2037
|
}
|
|
884
2038
|
} catch (error) {
|
|
@@ -887,22 +2041,49 @@ export function createBridge(
|
|
|
887
2041
|
}
|
|
888
2042
|
}
|
|
889
2043
|
|
|
890
|
-
// Q1:队列 drain
|
|
2044
|
+
// Q1:队列 drain——取该 (用户,会话) lane 队首重走完整管线。draining 防重入;
|
|
891
2045
|
// handleMessage 自身的 finally 会继续 drain 下一条(链式)。
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
2046
|
+
// 会话隔离(owner 2026-11-14):drain 只动指定 lane;锚定随 ctx 传递——
|
|
2047
|
+
// 排队期间绑定切走也按入队锚定派发(消息跟原会话,不跟漂移的绑定)。
|
|
2048
|
+
async function drainQueue(userId: string, sessionId?: string): Promise<void> {
|
|
2049
|
+
const lane = laneOf(userId, sessionId)
|
|
2050
|
+
// DEF-20261118-P5 可观测性补强(19:02–19:33 实证:lane「卡住」19 分钟零日志,
|
|
2051
|
+
// 事后归因只能靠读码——三道守卫静默 return 是排障黑洞)。守卫跳过分级打印:
|
|
2052
|
+
// draining=同 lane 排水未结束(正常并发,debug 级);busy/pending=真阻塞信号。
|
|
2053
|
+
if (draining.has(lane)) {
|
|
2054
|
+
console.log(`[queue] drain-skip reason=draining user=${userId.slice(0, 8)}… lane=${sessionId ? shortId(sessionId) : "∅"}`)
|
|
2055
|
+
return
|
|
2056
|
+
}
|
|
2057
|
+
if (busyUsers.has(lane)) {
|
|
2058
|
+
console.log(`[queue] drain-skip reason=busy user=${userId.slice(0, 8)}… lane=${sessionId ? shortId(sessionId) : "∅"}`)
|
|
2059
|
+
return
|
|
2060
|
+
}
|
|
2061
|
+
// 审批挂起时不出队:此时出队只会被 handleMessage 的 pendingPerm 早退吞掉并结清
|
|
2062
|
+
// (消息白排队)。等挂起审批的回合走完 finally 自然会再次 drain。
|
|
2063
|
+
// 会话隔离:只有挂起审批属于本 lane 的会话才挡本 lane(其他会话的审批不挡)。
|
|
2064
|
+
const pending = perm.getPending(userId)
|
|
2065
|
+
if (pending && (!sessionId || pending.request.sessionID === sessionId)) {
|
|
2066
|
+
console.log(`[queue] drain-skip reason=pending-perm user=${userId.slice(0, 8)}… lane=${sessionId ? shortId(sessionId) : "∅"} request=${pending.request.id}`)
|
|
2067
|
+
return
|
|
2068
|
+
}
|
|
2069
|
+
const job = msgQueue.shift(lane)
|
|
895
2070
|
if (!job) return
|
|
896
|
-
draining.add(
|
|
2071
|
+
draining.add(lane)
|
|
2072
|
+
queueIdOfCtx.set(job.ctx, job.id)
|
|
2073
|
+
if (job.sessionId) job.ctx.anchorSessionId = job.ctx.anchorSessionId ?? job.sessionId
|
|
2074
|
+
if (job.ctx.msgId) inflight.markStage(job.ctx.msgId, "dispatched", { queueId: job.id })
|
|
2075
|
+
const remain = msgQueue.size(lane)
|
|
2076
|
+
console.log(`[queue] drain-start user=${userId.slice(0, 8)}… lane=${sessionId ? shortId(sessionId) : "∅"} qid=${job.id} remain=${remain}`)
|
|
897
2077
|
try {
|
|
898
|
-
await
|
|
2078
|
+
await notifyUser(job.ctx, `开始执行队列 #${job.id}(剩余 ${remain} 条)`)
|
|
899
2079
|
drainReentries.add(job.ctx) // 修复⑦:drain 重入跳过受理回执
|
|
900
2080
|
await handleMessage(job.ctx)
|
|
901
2081
|
} catch (error) {
|
|
902
2082
|
console.error("[bridge] 队列执行失败:", error)
|
|
903
2083
|
} finally {
|
|
904
|
-
draining.delete(
|
|
905
|
-
|
|
2084
|
+
draining.delete(lane)
|
|
2085
|
+
console.log(`[queue] drain-done user=${userId.slice(0, 8)}… qid=${job.id} remain=${msgQueue.size(lane)}`)
|
|
2086
|
+
if (msgQueue.size(lane) > 0 && !busyUsers.has(lane)) void drainQueue(userId, sessionId)
|
|
906
2087
|
}
|
|
907
2088
|
}
|
|
908
2089
|
|
|
@@ -963,7 +2144,7 @@ export function isAllowedUser(userId: string, allowedUsers: string[]): boolean {
|
|
|
963
2144
|
|
|
964
2145
|
// R2-P1-3(2026-10-14):/watch 持久化——里程碑已改 /watch 专属,重启静默丢
|
|
965
2146
|
// 订阅不可接受;与 greeted.json 同款风格(损坏即空、文件名参数化供单测)。
|
|
966
|
-
const WATCH_FILE =
|
|
2147
|
+
const WATCH_FILE = storageFile("watch.json")
|
|
967
2148
|
|
|
968
2149
|
export function loadWatchedMap(file: string = WATCH_FILE): Record<string, string> {
|
|
969
2150
|
try {
|
|
@@ -990,12 +2171,12 @@ export function saveWatchedMap(m: ReadonlyMap<string, string>, file: string = WA
|
|
|
990
2171
|
}
|
|
991
2172
|
}
|
|
992
2173
|
|
|
993
|
-
const GREETED_FILE =
|
|
2174
|
+
const GREETED_FILE = storageFile("greeted.json")
|
|
994
2175
|
|
|
995
|
-
function loadGreetedSet(): Set<string> {
|
|
2176
|
+
function loadGreetedSet(file: string = GREETED_FILE): Set<string> {
|
|
996
2177
|
try {
|
|
997
|
-
if (existsSync(
|
|
998
|
-
const raw = readFileSync(
|
|
2178
|
+
if (existsSync(file)) {
|
|
2179
|
+
const raw = readFileSync(file, "utf-8")
|
|
999
2180
|
const arr = JSON.parse(raw)
|
|
1000
2181
|
if (Array.isArray(arr)) {
|
|
1001
2182
|
return new Set(arr.filter((x): x is string => typeof x === "string"))
|
|
@@ -1007,10 +2188,10 @@ function loadGreetedSet(): Set<string> {
|
|
|
1007
2188
|
return new Set<string>()
|
|
1008
2189
|
}
|
|
1009
2190
|
|
|
1010
|
-
function saveGreetedSet(set: Set<string
|
|
2191
|
+
function saveGreetedSet(set: Set<string>, file: string = GREETED_FILE): void {
|
|
1011
2192
|
try {
|
|
1012
2193
|
mkdirSync(join(homedir(), ".openqq"), { recursive: true })
|
|
1013
|
-
writeFileSync(
|
|
2194
|
+
writeFileSync(file, JSON.stringify([...set]))
|
|
1014
2195
|
} catch (error) {
|
|
1015
2196
|
console.error("[bridge] 保存 greeted 失败:", error)
|
|
1016
2197
|
}
|