@linjz/opencode-qqbot 0.3.19 → 0.3.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PRIVACY.md +87 -0
- package/README.md +20 -3
- package/README.zh-CN.md +21 -4
- package/THIRD_PARTY_NOTICES.md +136 -0
- package/bin/openqq.js +1 -1
- package/dist/opencode-qqbot-plugin.js +124 -6
- package/dist/openqq-bot.js +1099 -231
- package/dist/openqq-cli.js +152 -16
- package/dist/openqq-watchdog.js +72 -2
- package/package.json +5 -3
- package/src/bridge.ts +156 -13
- package/src/cli/openqq-main.ts +33 -5
- package/src/core/bot-control.ts +73 -8
- package/src/core/card-approval.ts +14 -3
- package/src/core/context-buffer.ts +6 -6
- package/src/core/cron-reminders.ts +1 -1
- package/src/core/delivery.ts +131 -37
- package/src/core/instance-lock.ts +1 -1
- package/src/core/mirror-anchors.ts +145 -0
- package/src/core/mirror.ts +112 -22
- package/src/core/notices.ts +2 -2
- package/src/core/notify-sink.ts +1 -1
- package/src/core/office-text.ts +234 -0
- package/src/core/outbound-sanitize.ts +3 -1
- package/src/core/permission.ts +157 -26
- package/src/core/reply-limiter.ts +3 -2
- package/src/core/send-media.ts +6 -6
- package/src/core/stt.ts +1 -1
- package/src/core/watchdog.ts +108 -5
- package/src/index.ts +1 -1
- package/src/opencode/mirror.ts +54 -2
- package/src/opencode/sessions.ts +28 -2
- package/src/qq/api.ts +9 -1
- package/src/qq/gateway.ts +16 -5
- package/src/qq/media.ts +154 -55
- package/src/qq/sender.ts +64 -14
- package/src/qq/types.ts +4 -1
package/src/cli/openqq-main.ts
CHANGED
|
@@ -4,12 +4,13 @@
|
|
|
4
4
|
//
|
|
5
5
|
// 用法:
|
|
6
6
|
// node dist/openqq-cli.js restart [--force] [--timeout-min 60]
|
|
7
|
-
// node dist/openqq-cli.js
|
|
7
|
+
// node dist/openqq-cli.js stop [--timeout-min 60]
|
|
8
|
+
// node dist/openqq-cli.js service install|uninstall [--stop-bot] |status
|
|
8
9
|
// 2026-11-09 架构红线:取代 safe-restart.ps1 / start-openqq.ps1 / watchdog.ps1,全 TS 跨平台。
|
|
9
10
|
import { existsSync } from "fs"
|
|
10
11
|
import { dirname, join } from "path"
|
|
11
12
|
import { fileURLToPath } from "url"
|
|
12
|
-
import { restartBot } from "../core/bot-control.js"
|
|
13
|
+
import { restartBot, stopBot } from "../core/bot-control.js"
|
|
13
14
|
import {
|
|
14
15
|
serviceInstall,
|
|
15
16
|
serviceStatus,
|
|
@@ -65,6 +66,17 @@ async function main(): Promise<void> {
|
|
|
65
66
|
return
|
|
66
67
|
}
|
|
67
68
|
|
|
69
|
+
if (cmd === "stop") {
|
|
70
|
+
const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"))
|
|
71
|
+
const res = await stopBot({
|
|
72
|
+
timeoutMs: Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60_000 : undefined,
|
|
73
|
+
log: (line) => console.log(line),
|
|
74
|
+
})
|
|
75
|
+
console.log(`[stop] ${res.action}(${res.reason})killed=${res.killedPid ?? "-"}`)
|
|
76
|
+
process.exitCode = res.action === "stopped" ? 0 : 2
|
|
77
|
+
return
|
|
78
|
+
}
|
|
79
|
+
|
|
68
80
|
if (cmd === "service") {
|
|
69
81
|
const spec: ServiceSpec = {
|
|
70
82
|
runtimeCmd: runtimeCommand(),
|
|
@@ -72,7 +84,23 @@ async function main(): Promise<void> {
|
|
|
72
84
|
intervalMin: DEFAULT_INTERVAL_MIN,
|
|
73
85
|
}
|
|
74
86
|
if (sub === "install") return printResult("service install", serviceInstall(spec))
|
|
75
|
-
if (sub === "uninstall")
|
|
87
|
+
if (sub === "uninstall") {
|
|
88
|
+
const uninstall = serviceUninstall()
|
|
89
|
+
printResult("service uninstall", uninstall)
|
|
90
|
+
if (!process.argv.includes("--stop-bot")) return
|
|
91
|
+
// --stop-bot 是完整停用语义:自启注销失败(含任务本就不存在)不得阻断 bot 停止;
|
|
92
|
+
// 退出码反映两步结果——都成 0,仅停止成 1,停止未成 2。
|
|
93
|
+
const stop = await stopBot({
|
|
94
|
+
timeoutMs: (() => {
|
|
95
|
+
const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"))
|
|
96
|
+
return Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60_000 : undefined
|
|
97
|
+
})(),
|
|
98
|
+
log: (line) => console.log(line),
|
|
99
|
+
})
|
|
100
|
+
console.log(`[stop] ${stop.action}(${stop.reason})killed=${stop.killedPid ?? "-"}`)
|
|
101
|
+
process.exitCode = stop.action === "stopped" ? (uninstall.ok ? 0 : 1) : 2
|
|
102
|
+
return
|
|
103
|
+
}
|
|
76
104
|
if (sub === "status") {
|
|
77
105
|
const r = serviceStatus()
|
|
78
106
|
return printResult("service status", {
|
|
@@ -80,12 +108,12 @@ async function main(): Promise<void> {
|
|
|
80
108
|
detail: `runtime=${spec.runtimeCmd}\nscript=${spec.scriptPath}\n${r.detail}`,
|
|
81
109
|
})
|
|
82
110
|
}
|
|
83
|
-
console.error("用法:openqq service install|uninstall|status")
|
|
111
|
+
console.error("用法:openqq service install|uninstall [--stop-bot]|status")
|
|
84
112
|
process.exitCode = 2
|
|
85
113
|
return
|
|
86
114
|
}
|
|
87
115
|
|
|
88
|
-
console.error("用法:openqq-cli restart [--force] [--timeout-min N] | service install|uninstall|status")
|
|
116
|
+
console.error("用法:openqq-cli restart [--force] [--timeout-min N] | stop [--timeout-min N] | service install|uninstall [--stop-bot]|status")
|
|
89
117
|
process.exitCode = 2
|
|
90
118
|
}
|
|
91
119
|
|
package/src/core/bot-control.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @input: ~/.openqq/.env、实例锁、在途台账、core/bot-launcher(运行时解析与 detached 拉起)、
|
|
2
2
|
// core/watchdog(superviseOnce 杀/拉唯一权威)
|
|
3
|
-
// @output: resolveInstalledBotEntry, readAppId, countInflight, waitUntilIdle, startBot, restartBot
|
|
3
|
+
// @output: resolveInstalledBotEntry, readAppId, countInflight, waitUntilIdle, startBot, restartBot, stopBot
|
|
4
4
|
// @pos: core - bot 生命周期控制(跨平台;替代 safe-restart.ps1 / start-openqq.ps1)
|
|
5
5
|
//
|
|
6
6
|
// 2026-11-09 架构红线:重启是运维代码,必须随插件包分发且跨平台。
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// 2026-11-10 design §3.9.1 归一:杀/拉唯一权威 = superviseOnce。restartBot 只是它的
|
|
9
9
|
// 调用方(等空闲 → 同一 grace-kill+spawn 原语 + supervisor.json 强度账 + 审计分家 +
|
|
10
10
|
// 认领互斥),本文件不再实现任何独立杀逻辑(原 stopLockedBot 已删除)。
|
|
11
|
-
import { existsSync, readFileSync } from "fs"
|
|
11
|
+
import { existsSync, readFileSync, readdirSync } from "fs"
|
|
12
12
|
import { dirname, join } from "path"
|
|
13
13
|
import { homedir } from "os"
|
|
14
14
|
import { fileURLToPath } from "url"
|
|
@@ -69,15 +69,35 @@ export function inflightPath(): string {
|
|
|
69
69
|
return join(homedir(), ".openqq", "inflight.json")
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
-
/**
|
|
73
|
-
export function
|
|
72
|
+
/** 全部角色在途台账路径:legacy 根 + roles/<appId>/(多角色停止/重启的空闲判据必须看全量)。 */
|
|
73
|
+
export function inflightPaths(): string[] {
|
|
74
|
+
const root = join(homedir(), ".openqq")
|
|
75
|
+
const paths = [join(root, "inflight.json")]
|
|
74
76
|
try {
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
77
|
+
for (const name of readdirSync(join(root, "roles"))) {
|
|
78
|
+
const path = join(root, "roles", name, "inflight.json")
|
|
79
|
+
if (existsSync(path)) paths.push(path)
|
|
80
|
+
}
|
|
78
81
|
} catch {
|
|
79
|
-
|
|
82
|
+
/* 无 roles 目录=legacy 单角色 */
|
|
83
|
+
}
|
|
84
|
+
return paths
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 在途回合数(safe-restart/stop 的空闲判据:state=inflight 即算活跃;默认全角色合计)。 */
|
|
88
|
+
export function countInflight(paths: string | string[] = inflightPaths()): number {
|
|
89
|
+
const list = Array.isArray(paths) ? paths : [paths]
|
|
90
|
+
let total = 0
|
|
91
|
+
for (const path of list) {
|
|
92
|
+
try {
|
|
93
|
+
const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown
|
|
94
|
+
if (!Array.isArray(raw)) continue
|
|
95
|
+
total += raw.filter((e) => (e as { state?: string }).state === "inflight").length
|
|
96
|
+
} catch {
|
|
97
|
+
/* 单文件损坏不阻断其他角色判活 */
|
|
98
|
+
}
|
|
80
99
|
}
|
|
100
|
+
return total
|
|
81
101
|
}
|
|
82
102
|
|
|
83
103
|
export async function waitUntilIdle(opts?: {
|
|
@@ -164,3 +184,48 @@ export async function restartBot(opts: RestartOptions): Promise<RestartResult> {
|
|
|
164
184
|
return { action: "skipped", killedPid: null, spawnedPid: null, reason: `无需动作:${r.detail}` }
|
|
165
185
|
}
|
|
166
186
|
}
|
|
187
|
+
|
|
188
|
+
export interface StopOptions {
|
|
189
|
+
timeoutMs?: number
|
|
190
|
+
log?: (line: string) => void
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export interface StopResult {
|
|
194
|
+
action: "stopped" | "skipped"
|
|
195
|
+
killedPid: number | null
|
|
196
|
+
reason: string
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* 受控停止:默认等空闲;复用 superviseOnce 的 manual-stop(认领互斥 + 优雅杀 + 清锁 + 审计),
|
|
201
|
+
* 不拉起、不计重启强度账。bot 独立存活是故障隔离,不是脱离用户控制——stop 是显式生命周期终点。
|
|
202
|
+
*/
|
|
203
|
+
export async function stopBot(opts: StopOptions = {}): Promise<StopResult> {
|
|
204
|
+
const log = opts.log ?? (() => {})
|
|
205
|
+
const appId = readAppId()
|
|
206
|
+
if (!appId) throw new Error("缺少 ~/.openqq/.env 的角色凭据(QQ_APP_ID 或 QQ_BOTS 首角色),无法定位实例锁")
|
|
207
|
+
const idle = await waitUntilIdle({
|
|
208
|
+
timeoutMs: opts.timeoutMs,
|
|
209
|
+
onWait: (n, elapsed) => log(`[bot-control] 仍在途 ${n} 条(已等 ${Math.round(elapsed / 1000)}s),继续等待空闲后停止`),
|
|
210
|
+
})
|
|
211
|
+
if (!idle) {
|
|
212
|
+
log("[bot-control] 等待空闲超时:本次不停止(请稍后重试,或先处理在途回合)")
|
|
213
|
+
return { action: "skipped", killedPid: null, reason: "等待空闲超时" }
|
|
214
|
+
}
|
|
215
|
+
const r = await superviseOnce({
|
|
216
|
+
paths: botWatchdogPaths(appId),
|
|
217
|
+
request: "manual-stop",
|
|
218
|
+
spawn: () => {
|
|
219
|
+
throw new Error("manual-stop 不应拉起 bot")
|
|
220
|
+
},
|
|
221
|
+
log,
|
|
222
|
+
})
|
|
223
|
+
if (r.action === "stopped") {
|
|
224
|
+
return {
|
|
225
|
+
action: "stopped",
|
|
226
|
+
killedPid: r.killedPid,
|
|
227
|
+
reason: r.killedPid ? "已优雅停止并持有(巡检不拉起,restart 解除)" : "bot 未运行,已清锁并持有(巡检不拉起)",
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return { action: "skipped", killedPid: null, reason: r.detail }
|
|
231
|
+
}
|
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
// handleApprovalInteraction
|
|
6
6
|
// @pos: core - 卡片按钮审批(A 项 2026-10-29)
|
|
7
7
|
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
8
|
+
// 设计参考 dsh-qqbot 的 button-data 判别及 approval-channel 的挂起、旧卡防伪机制,
|
|
9
|
+
// 以及 @tencent-connect/qqbot-nodejs protocol/types.ts 的 KeyboardButton/InlineKeyboard 形状。
|
|
10
|
+
// 本项目改用 request.id 防伪,并扩展四键决策、文字降级和项目权限状态机;
|
|
11
|
+
// 上游来源与许可见 THIRD_PARTY_NOTICES.md。
|
|
11
12
|
// 与文字菜单并行不互拆:卡片优先,发送失败自动降级文字;文字通道原样保留。
|
|
12
13
|
// 安全基线(fail-closed):忽略按钮=不决策(权限保持挂起至 TTL);
|
|
13
14
|
// button_data 内嵌 request.id,槽位已被新请求替换时旧按钮点击直接拒识。
|
|
@@ -104,12 +105,22 @@ export async function sendApprovalCard(
|
|
|
104
105
|
request: PermissionRequest,
|
|
105
106
|
mainSessionId: string,
|
|
106
107
|
origin?: PermOrigin,
|
|
108
|
+
isCancelled?: () => boolean,
|
|
107
109
|
): Promise<boolean> {
|
|
108
110
|
try {
|
|
109
111
|
const token = await getAccessToken(deps.appId, deps.clientSecret)
|
|
112
|
+
// 死卡竞态防线:token 获取可能耗时,期间桌面端/引擎已处理——QQ API 前必须再查。
|
|
113
|
+
if (isCancelled?.()) {
|
|
114
|
+
console.log(`[card-approval] 发卡取消:请求已解决 user=${ctx.userId.slice(0, 8)}… request=${request.id}`)
|
|
115
|
+
return false
|
|
116
|
+
}
|
|
110
117
|
const keyboard = buildApprovalKeyboard(request, ctx.userId)
|
|
111
118
|
// 正文复用现有格式化(用户看到的字段与文字菜单完全一致);origin 标注发起来源
|
|
112
119
|
const text = formatPermissionPrompt(request, mainSessionId, origin)
|
|
120
|
+
if (isCancelled?.()) {
|
|
121
|
+
console.log(`[card-approval] 发卡取消:请求已解决 user=${ctx.userId.slice(0, 8)}… request=${request.id}`)
|
|
122
|
+
return false
|
|
123
|
+
}
|
|
113
124
|
if (ctx.type === "group" && ctx.groupId) {
|
|
114
125
|
await sendGroupMessage(token, ctx.groupId, text, ctx.msgId, undefined, true, keyboard)
|
|
115
126
|
} else {
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
// @output: recordMessage, resolveQuote, scopeKeyOf, resetContextBuffer(测试用)
|
|
3
3
|
// @pos: core - 消息上下文索引缓存(引用消息解析)
|
|
4
4
|
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
5
|
+
// 引用索引与回退思路参考 qqbot-nodejs 的 quote-ref 中间件。
|
|
6
|
+
// QQ C2C/群消息的引用经由 message_reference.message_id 透传;QQ 不提供 C2C 历史
|
|
7
|
+
// 消息拉取,故引用解析需本地缓存——我方发出的回复也记录(消息 id 取服务端回执
|
|
8
|
+
// MessageResponse.id;0.3.20 起同时登记 ext_info.ref_idx),保证"引用 AI 答案"可解析。此处按项目会话域以 Map 实现
|
|
9
|
+
// 每域 200 条的进程内缓存;跨重启引用解析为空属可接受降级。上游见 THIRD_PARTY_NOTICES.md。
|
|
10
10
|
interface RefEntry {
|
|
11
11
|
text: string
|
|
12
12
|
at: number
|
|
@@ -46,7 +46,7 @@ export function resolveQuote(scope: string, referencedMsgId: string): string | n
|
|
|
46
46
|
return entry?.text ?? null
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
// N 项(2026-10-30
|
|
49
|
+
// N 项(2026-10-30,参考竞品 opencode-qq-v2 的引用消息双通道思路):
|
|
50
50
|
// QQ 在 message_type=103 时把被引内容嵌在 msg_elements 里随事件透传(官方未完全
|
|
51
51
|
// 文档化结构,做防御性递归提取);命中即权威来源,不再依赖本缓存(跨重启/引用
|
|
52
52
|
// 老消息也能解析)。提取为空时调用方回落 resolveQuote 缓存通道。
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @input: 纯文本(无依赖)+ setTimeout(调度器)
|
|
2
2
|
// @output: parseCronReminder / ReminderScheduler
|
|
3
|
-
// @pos: core - 定时提醒(2026-11-23
|
|
3
|
+
// @pos: core - 定时提醒(2026-11-23 学习参考 Y-1,源=openclaw outbound/cron-scheduler.ts P0)
|
|
4
4
|
//
|
|
5
5
|
// 触发形态(AI 在正文内嵌标记,与 openclaw 同款):
|
|
6
6
|
// QQBOT_PAYLOAD: {"type":"cron_reminder","at":"in 30m","text":"去开评审会"}
|
package/src/core/delivery.ts
CHANGED
|
@@ -8,8 +8,15 @@ import { join } from "path"
|
|
|
8
8
|
import { createHash } from "node:crypto"
|
|
9
9
|
import type { Config } from "../config.js"
|
|
10
10
|
import type { MessageContext } from "../qq/types.js"
|
|
11
|
-
import {
|
|
12
|
-
|
|
11
|
+
import {
|
|
12
|
+
getAccessToken,
|
|
13
|
+
sendC2CMessage,
|
|
14
|
+
sendGroupMessage,
|
|
15
|
+
getNextMsgSeq,
|
|
16
|
+
type MessageResponse,
|
|
17
|
+
type SentMessageReceipt,
|
|
18
|
+
} from "../qq/api.js"
|
|
19
|
+
import { PartialReplyError, replyToQQ } from "../qq/sender.js"
|
|
13
20
|
import { matchFence, normalizeOutboundMarkdown } from "./markdown.js"
|
|
14
21
|
import { ReplyLimiter } from "./reply-limiter.js"
|
|
15
22
|
import { recordMessage, scopeKeyOf } from "./context-buffer.js"
|
|
@@ -57,9 +64,11 @@ function saveQuotaMap(file: string, m: ReadonlyMap<string, { day: string; count:
|
|
|
57
64
|
}
|
|
58
65
|
}
|
|
59
66
|
|
|
60
|
-
// P 项(2026-10-30
|
|
67
|
+
// P 项(2026-10-30,参考竞品 pendingNotice 模式):发送彻底失败不静默——
|
|
61
68
|
// 记"有未送达消息",下一次成功投递时前缀贴条告知用户(导出供测试)。
|
|
62
69
|
export const UNDELIVERED_NOTICE = "(此前有未能送达的消息)\n"
|
|
70
|
+
export const PARTIAL_DELIVERY_NOTICE =
|
|
71
|
+
"⚠️ 本轮消息仅部分送达。为避免重复,已阻止自动全文重发;完整结果请发 /history 查看,或重新提问。"
|
|
63
72
|
|
|
64
73
|
// QQ 渲染适配(2026-11-03 用户双端截图实证):QQ 官方 markdown 渲染器把跨
|
|
65
74
|
// 段落的有序列表续接编号(原文 1./2. 渲染成 3./4.),与桌面端所见不一致。
|
|
@@ -279,14 +288,23 @@ export function selectRideMsgId(
|
|
|
279
288
|
return last.msgId
|
|
280
289
|
}
|
|
281
290
|
|
|
291
|
+
export type OnSentMessage = (receipt: SentMessageReceipt) => void | Promise<void>
|
|
292
|
+
|
|
293
|
+
export interface DeliveryContentOptions {
|
|
294
|
+
/** 仅加到第 2 片及后续分片;切分后添加,保证身份标记不会留在上一片。 */
|
|
295
|
+
continuationPrefix?: string
|
|
296
|
+
}
|
|
297
|
+
|
|
282
298
|
export interface Delivery {
|
|
283
299
|
/** anchorSessionId=该观察行的锚定会话(出站推送门按它校验当前绑定,design §3.4) */
|
|
284
300
|
enqueuePush: (userId: string, line: string, anchorSessionId?: string) => void
|
|
285
|
-
/** 返回 true
|
|
286
|
-
deliver: (ctx: MessageContext, text: string) => Promise<boolean>
|
|
301
|
+
/** 返回 true=完整出站成功;false=24h 去重、推送门或分片部分失败(调用方据此刻画销账口径) */
|
|
302
|
+
deliver: (ctx: MessageContext, text: string, onSent?: OnSentMessage, content?: DeliveryContentOptions) => Promise<boolean>
|
|
287
303
|
/** 同 deliver;彻底失败时贴条待下次消化并返回 false */
|
|
288
|
-
safeDeliver: (ctx: MessageContext, text: string) => Promise<boolean>
|
|
289
|
-
sendReply: (ctx: MessageContext, text: string) => Promise<void>
|
|
304
|
+
safeDeliver: (ctx: MessageContext, text: string, onSent?: OnSentMessage, content?: DeliveryContentOptions) => Promise<boolean>
|
|
305
|
+
sendReply: (ctx: MessageContext, text: string, onSent?: OnSentMessage, content?: DeliveryContentOptions) => Promise<void>
|
|
306
|
+
/** 消费一次部分失败标记,供 bridge 区分「部分失败」与「24h 同文去重」。 */
|
|
307
|
+
consumePartialFailure: (ctx: MessageContext) => boolean
|
|
290
308
|
}
|
|
291
309
|
|
|
292
310
|
// 投递域门面。lastCtx 为跨域共享状态(bridge 拥有写权),本域只读——
|
|
@@ -312,8 +330,8 @@ export function createDelivery(
|
|
|
312
330
|
// 该用户最近主动发送时刻(滚动 60s 窗,内存态——重启即清空,天预算仍落盘兜底)
|
|
313
331
|
const activeMinuteLog = new Map<string, number[]>()
|
|
314
332
|
|
|
315
|
-
// B-msgid(2026-10-29
|
|
316
|
-
// "骑"该用户最近的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额)。
|
|
333
|
+
// B-msgid(2026-10-29,被动目标缓存思路参考 dsh-qqbot 的 msgid-cache):
|
|
334
|
+
// 主动降级前尝试让发送"骑"该用户最近的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额)。
|
|
317
335
|
// 窗口口径保守取 5 分钟(社区亦有 60 分钟说法;骑失败无副作用自动回落真主动,
|
|
318
336
|
// 故从保守值起步,可用 QQ_PASSIVE_RIDE_WINDOW_MS 调整)。
|
|
319
337
|
const RIDE_WINDOW_MS = (() => {
|
|
@@ -331,9 +349,11 @@ export function createDelivery(
|
|
|
331
349
|
const pushQueues = new Map<string, PushQueue>()
|
|
332
350
|
// P 项:彻底投递失败的用户集合(贴条状态),下次成功投递时消化
|
|
333
351
|
const undelivered = new Set<string>()
|
|
352
|
+
const partialFailures = new WeakSet<MessageContext>()
|
|
334
353
|
const activeQuota = new Map<string, { day: string; count: number; warned: boolean }>()
|
|
335
|
-
// B1(2026-10-29
|
|
354
|
+
// B1(2026-10-29,限额规则与降级方式参考 openclaw-qqbot reply-limiter):
|
|
336
355
|
// 单 msgId 4 次/1h 窗口,耗尽/过期直接转主动,省一次注定被拒的 API 往返。
|
|
356
|
+
// 该派生实现的上游版权与许可见 THIRD_PARTY_NOTICES.md。
|
|
337
357
|
// 记账点在 sendReply 成功路径(统一出口,bridge 直调与 deliver 共用)。
|
|
338
358
|
const passiveLimiter = new ReplyLimiter()
|
|
339
359
|
// O5:恢复落盘配额(非当日条目由 deliver 按 day 字段自然重置)
|
|
@@ -390,13 +410,33 @@ export function createDelivery(
|
|
|
390
410
|
}
|
|
391
411
|
}
|
|
392
412
|
|
|
413
|
+
function recordSent(scope: string, text: string, receipt: SentMessageReceipt): void {
|
|
414
|
+
recordMessage(scope, receipt.id, text)
|
|
415
|
+
if (receipt.refIdx && receipt.refIdx !== receipt.id) recordMessage(scope, receipt.refIdx, text)
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function emitSent(onSent: OnSentMessage | undefined, receipt: SentMessageReceipt): Promise<void> {
|
|
419
|
+
if (!onSent) return
|
|
420
|
+
try {
|
|
421
|
+
await onSent(receipt)
|
|
422
|
+
} catch (error) {
|
|
423
|
+
// QQ 已真实发送:回执簿记失败绝不能触发被动→主动降级而重复发一条。
|
|
424
|
+
console.error("[delivery] onSent 回执处理失败(QQ 消息已发送):", error)
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
393
428
|
// 统一投递:被动回复优先(ctx.msg_id,5 分钟窗口内、无配额消耗);
|
|
394
429
|
// 窗口过期/失败降级主动消息(计日配额,超限告警一次)。
|
|
395
430
|
// 观察推送与最终回复共用——超长回合(>被动窗口)的答案靠它送达
|
|
396
431
|
//(2026-10-13 实测教训:回合 >5 分钟时旧路径答案永久丢失)。
|
|
397
432
|
// P 项贴条包装:deliver 入口消化贴条状态——有待贴条则前缀拼入正文;
|
|
398
433
|
// 投递失败则把贴条放回(留待下次),成功才算消化。
|
|
399
|
-
async function deliver(
|
|
434
|
+
async function deliver(
|
|
435
|
+
ctx: MessageContext,
|
|
436
|
+
text: string,
|
|
437
|
+
onSent?: OnSentMessage,
|
|
438
|
+
content?: DeliveryContentOptions,
|
|
439
|
+
): Promise<boolean> {
|
|
400
440
|
// 出站推送门(design §3.4,owner 2026-11-14 会话隔离裁定):QQ 窗只呈现当前绑定
|
|
401
441
|
// 会话——锚定会话≠当前绑定即不推(结果已入锚定会话历史,可经历史/桌面端回读)。
|
|
402
442
|
if (ctx.anchorSessionId && pushGate && !pushGate(ctx.userId, ctx.anchorSessionId)) {
|
|
@@ -416,17 +456,36 @@ export function createDelivery(
|
|
|
416
456
|
// QQ 渲染适配:有序列表改写,防 QQ 端跨段落续编(桌面所见=QQ 所见)
|
|
417
457
|
const body = qqListNormalize(hadNotice ? UNDELIVERED_NOTICE + text : text)
|
|
418
458
|
try {
|
|
419
|
-
await deliverCore(ctx, body)
|
|
459
|
+
await deliverCore(ctx, body, onSent, content)
|
|
420
460
|
return true
|
|
421
461
|
} catch (error) {
|
|
422
|
-
|
|
462
|
+
if (error instanceof PartialReplyError) {
|
|
463
|
+
partialFailures.add(ctx)
|
|
464
|
+
console.error(
|
|
465
|
+
`[delivery] 分片部分失败,禁止全文降级 sent=${error.receipts.length} failedChunk=${error.failedChunkIndex + 1}`,
|
|
466
|
+
)
|
|
467
|
+
// 已发前缀不能重复;保留原去重占位,阻止 outbox/恢复路径立即重发同一全文。
|
|
468
|
+
try {
|
|
469
|
+
await sendActive(ctx, PARTIAL_DELIVERY_NOTICE)
|
|
470
|
+
} catch (alertError) {
|
|
471
|
+
undelivered.add(ctx.userId)
|
|
472
|
+
console.error("[delivery] 部分失败告警也未能送达:", alertError)
|
|
473
|
+
}
|
|
474
|
+
return false
|
|
475
|
+
}
|
|
476
|
+
// 完全未发出时不占去重位,后续恢复/重试仍可送达。
|
|
423
477
|
releaseDeliveryAttempt(ctx.userId, text, now)
|
|
424
478
|
if (hadNotice) undelivered.add(ctx.userId)
|
|
425
479
|
throw error
|
|
426
480
|
}
|
|
427
481
|
}
|
|
428
482
|
|
|
429
|
-
async function deliverCore(
|
|
483
|
+
async function deliverCore(
|
|
484
|
+
ctx: MessageContext,
|
|
485
|
+
text: string,
|
|
486
|
+
onSent?: OnSentMessage,
|
|
487
|
+
content?: DeliveryContentOptions,
|
|
488
|
+
): Promise<void> {
|
|
430
489
|
// B1:被动尝试前预判额度,耗尽/过期直接走主动(避免注定被拒的被动请求)
|
|
431
490
|
const passive = ctx.msgId ? passiveLimiter.checkLimit(ctx.msgId) : null
|
|
432
491
|
if (passive?.shouldFallbackToProactive) {
|
|
@@ -435,9 +494,10 @@ export function createDelivery(
|
|
|
435
494
|
)
|
|
436
495
|
} else {
|
|
437
496
|
try {
|
|
438
|
-
await sendReply(ctx, text)
|
|
497
|
+
await sendReply(ctx, text, onSent, content)
|
|
439
498
|
return
|
|
440
499
|
} catch (error) {
|
|
500
|
+
if (error instanceof PartialReplyError) throw error
|
|
441
501
|
console.warn(
|
|
442
502
|
"[bridge] 被动回复失败(可能超 5 分钟窗口),降级主动消息:",
|
|
443
503
|
error instanceof Error ? error.message : error,
|
|
@@ -445,15 +505,18 @@ export function createDelivery(
|
|
|
445
505
|
}
|
|
446
506
|
}
|
|
447
507
|
|
|
448
|
-
// B-msgid
|
|
508
|
+
// B-msgid(参考 dsh-qqbot msgid-cache 的被动目标缓存思路,2026-10-29):主动降级前尝试"骑"该用户最近
|
|
449
509
|
// 的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额、记 B1 账本);
|
|
450
510
|
// 骑失败无副作用,回落下方真主动流程。
|
|
451
511
|
const rideMsgId = selectRideMsgId(lastCtx.get(ctx.userId), ctx, Date.now(), RIDE_WINDOW_MS)
|
|
452
512
|
if (rideMsgId) {
|
|
453
513
|
try {
|
|
454
|
-
const
|
|
514
|
+
const rideReceipts = await sendActive(ctx, text, rideMsgId)
|
|
455
515
|
passiveLimiter.record(rideMsgId)
|
|
456
|
-
for (const
|
|
516
|
+
for (const receipt of rideReceipts) {
|
|
517
|
+
recordSent(scopeKeyOf(ctx), text, receipt)
|
|
518
|
+
await emitSent(onSent, receipt)
|
|
519
|
+
}
|
|
457
520
|
console.log(`[bridge] 主动降级已骑被动窗口 msgId=${rideMsgId},省一次主动配额`)
|
|
458
521
|
return
|
|
459
522
|
} catch {
|
|
@@ -480,15 +543,23 @@ export function createDelivery(
|
|
|
480
543
|
}
|
|
481
544
|
throw new Error("主动消息已达 QQ 官方日上限,本条无法送达")
|
|
482
545
|
}
|
|
483
|
-
const
|
|
484
|
-
for (const
|
|
546
|
+
const activeReceipts = await sendActive(ctx, text)
|
|
547
|
+
for (const receipt of activeReceipts) {
|
|
548
|
+
recordSent(scopeKeyOf(ctx), text, receipt)
|
|
549
|
+
await emitSent(onSent, receipt)
|
|
550
|
+
}
|
|
485
551
|
q.count++
|
|
486
552
|
saveQuotaMap(QUOTA_FILE, activeQuota) // O5:计数落盘,跨重启不归零
|
|
487
553
|
}
|
|
488
554
|
|
|
489
|
-
async function safeDeliver(
|
|
555
|
+
async function safeDeliver(
|
|
556
|
+
c: MessageContext,
|
|
557
|
+
text: string,
|
|
558
|
+
onSent?: OnSentMessage,
|
|
559
|
+
content?: DeliveryContentOptions,
|
|
560
|
+
): Promise<boolean> {
|
|
490
561
|
try {
|
|
491
|
-
return await deliver(c, text)
|
|
562
|
+
return await deliver(c, text, onSent, content)
|
|
492
563
|
} catch (error) {
|
|
493
564
|
undelivered.add(c.userId) // P 项:最终失败 → 贴条待下次消化
|
|
494
565
|
console.error("[bridge] 消息无法送达(被动+主动均失败):", error)
|
|
@@ -498,8 +569,8 @@ export function createDelivery(
|
|
|
498
569
|
|
|
499
570
|
// 主动消息(不带 msg_id):markdown 优先,失败回退纯文本。
|
|
500
571
|
// passiveMsgId(B-msgid 2026-10-29):"骑"被动窗口时传入,平台接受则按被动计。
|
|
501
|
-
//
|
|
502
|
-
async function sendActive(ctx: MessageContext, text: string, passiveMsgId?: string): Promise<
|
|
572
|
+
// 返回每个服务端消息回执(id + 可选 refIdx)。
|
|
573
|
+
async function sendActive(ctx: MessageContext, text: string, passiveMsgId?: string): Promise<SentMessageReceipt[]> {
|
|
503
574
|
// 分钟维节流(官方 20 条/分钟,2026-11-18 严格官方化):滚动窗满 → 睡到窗口滑动再发。
|
|
504
575
|
// 骑被动窗口的投递(passiveMsgId 非空)平台按被动计,不占主动分钟窗。
|
|
505
576
|
if (!passiveMsgId) {
|
|
@@ -514,45 +585,68 @@ export function createDelivery(
|
|
|
514
585
|
const isGroup = ctx.type === "group" && ctx.groupId
|
|
515
586
|
// 主动 markdown 同样走围栏归一(与被动回复同口径,防未闭合/空围栏对渲染成空卡片)
|
|
516
587
|
const mdText = normalizeOutboundMarkdown(text)
|
|
517
|
-
const record = (
|
|
588
|
+
const record = (response: MessageResponse | undefined): SentMessageReceipt[] => {
|
|
589
|
+
const receipts = response?.id ? [{
|
|
590
|
+
id: response.id,
|
|
591
|
+
...(response.ext_info?.ref_idx ? { refIdx: response.ext_info.ref_idx } : {}),
|
|
592
|
+
}] : []
|
|
518
593
|
// 发送成功才记主动分钟窗(失败不计,同被动限额器口径)
|
|
519
|
-
if (!passiveMsgId &&
|
|
520
|
-
return
|
|
594
|
+
if (!passiveMsgId && receipts.length > 0) logActiveSend(activeMinuteLog, ctx.userId, Date.now())
|
|
595
|
+
return receipts
|
|
521
596
|
}
|
|
522
597
|
try {
|
|
523
598
|
if (isGroup) {
|
|
524
599
|
const r = await sendGroupMessage(token, ctx.groupId!, mdText, passiveMsgId, seq, true)
|
|
525
|
-
return record(r
|
|
600
|
+
return record(r)
|
|
526
601
|
}
|
|
527
602
|
const r = await sendC2CMessage(token, ctx.userId, mdText, passiveMsgId, seq, true)
|
|
528
|
-
return record(r
|
|
603
|
+
return record(r)
|
|
529
604
|
} catch (error) {
|
|
530
605
|
console.error("[bridge] 主动 markdown 发送失败,回退纯文本:", error)
|
|
531
606
|
}
|
|
532
607
|
if (isGroup) {
|
|
533
608
|
const r = await sendGroupMessage(token, ctx.groupId!, text, passiveMsgId, seq, false)
|
|
534
|
-
return record(r
|
|
609
|
+
return record(r)
|
|
535
610
|
}
|
|
536
611
|
const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, false)
|
|
537
|
-
return record(r
|
|
612
|
+
return record(r)
|
|
538
613
|
}
|
|
539
614
|
|
|
540
|
-
async function sendReply(
|
|
615
|
+
async function sendReply(
|
|
616
|
+
ctx: MessageContext,
|
|
617
|
+
text: string,
|
|
618
|
+
onSent?: OnSentMessage,
|
|
619
|
+
content?: DeliveryContentOptions,
|
|
620
|
+
): Promise<void> {
|
|
541
621
|
const accessToken = await getAccessToken(config.qq.appId, config.qq.clientSecret)
|
|
542
|
-
|
|
622
|
+
const scope = scopeKeyOf(ctx)
|
|
623
|
+
// J-轻:伪流式错峰(多片时隔 300ms 逐段到达)。每片成功立即登记,后续片失败
|
|
624
|
+
// 也不丢已发片的引用缓存/摘要锚点;严禁等整批成功后才补记。
|
|
543
625
|
const result = await replyToQQ(accessToken, ctx, text, {
|
|
544
626
|
staggerMs: STREAM_STAGGER_MS,
|
|
627
|
+
continuationPrefix: content?.continuationPrefix,
|
|
628
|
+
onReceipt: async (receipt) => {
|
|
629
|
+
recordSent(scope, text, receipt)
|
|
630
|
+
await emitSent(onSent, receipt)
|
|
631
|
+
},
|
|
545
632
|
})
|
|
546
633
|
// B1:被动回复成功才记额度(失败不计,避免虚耗);按片记账——平台限额按"条"计,
|
|
547
634
|
// 多片回复此前少计 N-1(J-轻顺手修正);bridge 直调与 deliver 共用此出口
|
|
548
635
|
if (ctx.msgId) {
|
|
549
636
|
for (let i = 0; i < result.chunks; i++) passiveLimiter.record(ctx.msgId)
|
|
550
637
|
}
|
|
551
|
-
// 缺口 1:我方出站回复登记进上下文缓存(引用解析可命中 AI 答案)
|
|
552
|
-
const scope = scopeKeyOf(ctx)
|
|
553
|
-
for (const id of result.ids) recordMessage(scope, id, text)
|
|
554
638
|
}
|
|
555
639
|
|
|
556
|
-
return {
|
|
640
|
+
return {
|
|
641
|
+
enqueuePush,
|
|
642
|
+
deliver,
|
|
643
|
+
safeDeliver,
|
|
644
|
+
sendReply,
|
|
645
|
+
consumePartialFailure(ctx): boolean {
|
|
646
|
+
if (!partialFailures.has(ctx)) return false
|
|
647
|
+
partialFailures.delete(ctx)
|
|
648
|
+
return true
|
|
649
|
+
},
|
|
650
|
+
}
|
|
557
651
|
}
|
|
558
652
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// @output: acquireInstanceLock, acquireInstanceLockAt(测试用), waitInstanceLock, INSTANCE_LOCK_DISABLED_ENV
|
|
3
3
|
// @pos: core - 单实例锁(防多开:双实例互踩 QQ 网关会互踢下线)
|
|
4
4
|
//
|
|
5
|
-
// M 项(2026-10-30
|
|
5
|
+
// M 项(2026-10-30,方案参考竞品 opencode-qq-v2 的 proper-lockfile 设计,
|
|
6
6
|
// 零依赖手写以守"官方/三方包不进 dependencies"红线):
|
|
7
7
|
// - wx 原子创建锁文件(含 pid+启动时间),抢到即宿主
|
|
8
8
|
// - 持锁者每 10s 刷新 mtime 作心跳
|