@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/core/permission.ts
CHANGED
|
@@ -38,6 +38,10 @@ export interface PendingPermission {
|
|
|
38
38
|
* 属误报,只在从磁盘恢复的条目上投递。 */
|
|
39
39
|
resumedFromDisk?: boolean
|
|
40
40
|
origin?: PermOrigin // 2026-11-09:回合归属标注——bot=机器人回合,external=桌面端发起(镜像推送)
|
|
41
|
+
/** 2026-11-28:审批提示(卡片或文字菜单)已实际投递到 QQ。clearIfResolved 仅在此置位
|
|
42
|
+
* (或 resumedFromDisk)时发「自动关闭」回执——延迟判定窗/发送窗内清槽时无卡可关,
|
|
43
|
+
* 回执属误报(owner 实证:无卡却收「QQ 审批自动关闭」)。 */
|
|
44
|
+
promptDelivered?: boolean
|
|
41
45
|
/** DEF-qqbot-20261112-1:裁决 reply 的 x-opencode-directory 值(建槽时快照;
|
|
42
46
|
* 引擎待审批按 location 实例分仓,裁决/超时拒答不带目录会对项目会话 404) */
|
|
43
47
|
directory?: string
|
|
@@ -101,6 +105,15 @@ export function resolvePermDeferMs(envValue: string | undefined): number {
|
|
|
101
105
|
return Number.isFinite(n) && n >= 0 && n <= 10_000 ? n : 500
|
|
102
106
|
}
|
|
103
107
|
|
|
108
|
+
/** QQ_PERM_SEND_GRACE_MS 解析(默认 1000ms,0=关闭):审批卡真正调 QQ API 前的可取消发送窗。
|
|
109
|
+
* 默认 1000ms 与延迟判定窗 500ms 合计 1500ms 总可取消窗口(2026-11-28 owner 裁定:
|
|
110
|
+
* 覆盖桌面自动审批实测延迟分布 <500-933ms 并留余量;用户按习惯经 config.json 微调)。 */
|
|
111
|
+
export function resolvePermSendGraceMs(envValue: string | undefined): number {
|
|
112
|
+
if (envValue === undefined || envValue.trim() === "") return 1000
|
|
113
|
+
const n = Number(envValue)
|
|
114
|
+
return Number.isFinite(n) && n >= 0 && n <= 10_000 ? n : 1000
|
|
115
|
+
}
|
|
116
|
+
|
|
104
117
|
export const DECISION_LABELS: Record<PermissionDecision, string> = {
|
|
105
118
|
once: "允许(本次)",
|
|
106
119
|
always: "总是允许(已存入项目白名单)",
|
|
@@ -187,12 +200,14 @@ export interface PermissionGateDeps {
|
|
|
187
200
|
client: OpencodeClient
|
|
188
201
|
sendReply: (ctx: MessageContext, text: string) => Promise<void>
|
|
189
202
|
safeDeliver: (ctx: MessageContext, text: string) => Promise<boolean>
|
|
190
|
-
/** A 项(2026-10-29):卡片按钮审批发送通道;返回 false
|
|
203
|
+
/** A 项(2026-10-29):卡片按钮审批发送通道;返回 false 时本域自动降级文字菜单。
|
|
204
|
+
* isCancelled:发卡途中槽位被清/请求已解决时返回 true,发送层必须在 QQ API 前放弃。 */
|
|
191
205
|
sendApprovalPrompt?: (
|
|
192
206
|
ctx: MessageContext,
|
|
193
207
|
request: PermissionRequest,
|
|
194
208
|
mainSessionId: string,
|
|
195
209
|
origin?: PermOrigin,
|
|
210
|
+
isCancelled?: () => boolean,
|
|
196
211
|
) => Promise<boolean>
|
|
197
212
|
/** 槽位清空的唤醒钩子(用户裁决/TTL 自动拒绝均触发):审批挂起期间 drainQueue 被守卫
|
|
198
213
|
* 挡回,裁决后须由调用方重新放行队列——否则挂起期间入队的消息要等用户再发一条才动
|
|
@@ -200,6 +215,8 @@ export interface PermissionGateDeps {
|
|
|
200
215
|
onDecision?: (userId: string) => void
|
|
201
216
|
/** 10min 无裁决告警间隔(测试注入小值;缺省 PERM_NUDGE_MS) */
|
|
202
217
|
nudgeMs?: number
|
|
218
|
+
/** 审批卡发送窗(测试注入;缺省 QQ_PERM_SEND_GRACE_MS/500ms,0=关闭) */
|
|
219
|
+
sendGraceMs?: number
|
|
203
220
|
/** 跨重启恢复读盘入口(测试注入;缺省读 legacy 全局 pending-permissions.json) */
|
|
204
221
|
loadPending?: () => Record<string, PersistedPermission>
|
|
205
222
|
/** 多角色:落盘文件(缺省 legacy 全局 pending-permissions.json) */
|
|
@@ -226,14 +243,69 @@ export interface PermissionGate {
|
|
|
226
243
|
* 若该 requestID 在挂起槽中(无论来源 bot/external),清槽 + QQ 回执「源头已处理」,
|
|
227
244
|
* 并唤醒队列。返回 true=确有槽被清。无匹配槽返回 false(正常:QQ 已先裁决)。 */
|
|
228
245
|
clearIfResolved: (sessionID: string | undefined, requestID: string, reply: unknown) => boolean
|
|
246
|
+
/** 请求近期已被解决(清槽/裁决/TTL)——发卡全链取消判据,防在飞死卡。 */
|
|
247
|
+
wasResolvedRecently: (requestID: string) => boolean
|
|
229
248
|
}
|
|
230
249
|
|
|
231
250
|
// 审批域门面:挂起槽 + 等待/裁决 + 跨重启恢复。所有状态与文件读写收在本域。
|
|
232
251
|
export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
233
252
|
// 多角色(2026-11-17):审批态落盘文件可按角色注入;缺省 legacy 全局路径
|
|
234
253
|
const PERSIST_FILE = deps.persistFile ?? PENDING_PERM_FILE
|
|
254
|
+
const SEND_GRACE_MS = deps.sendGraceMs ?? resolvePermSendGraceMs(process.env.QQ_PERM_SEND_GRACE_MS)
|
|
235
255
|
const { client, sendReply, safeDeliver } = deps
|
|
236
256
|
const pendingPermissions = new Map<string, PendingPermission>()
|
|
257
|
+
// 发卡取消语义(2026-11-28 死卡竞态修复):请求被清槽/裁决/TTL 后短 TTL 记名——
|
|
258
|
+
// clearIfResolved 只能清槽,不能撤回已在飞的 sendApprovalPrompt;发卡全链据此放弃。
|
|
259
|
+
const RESOLVED_RECENT_TTL_MS = 5 * 60_000
|
|
260
|
+
/** 清槽时提示未投递 → 「自动关闭」回执挂起;卡若随后迟到投递成功(死卡)由发卡路径补发。 */
|
|
261
|
+
type StashedNotice = { label: string; origin?: PermOrigin; ctx: MessageContext }
|
|
262
|
+
const resolvedRecently = new Map<string, { exp: number; notice?: StashedNotice }>()
|
|
263
|
+
function markResolvedRecently(requestID: string): void {
|
|
264
|
+
const prev = resolvedRecently.get(requestID)
|
|
265
|
+
resolvedRecently.set(requestID, {
|
|
266
|
+
exp: Date.now() + RESOLVED_RECENT_TTL_MS,
|
|
267
|
+
...(prev?.notice ? { notice: prev.notice } : {}),
|
|
268
|
+
})
|
|
269
|
+
if (resolvedRecently.size > 500) {
|
|
270
|
+
const now = Date.now()
|
|
271
|
+
for (const [id, e] of resolvedRecently) if (e.exp <= now) resolvedRecently.delete(id)
|
|
272
|
+
while (resolvedRecently.size > 500) {
|
|
273
|
+
const first = resolvedRecently.keys().next().value
|
|
274
|
+
if (first === undefined) break
|
|
275
|
+
resolvedRecently.delete(first)
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function wasResolvedRecently(requestID: string): boolean {
|
|
280
|
+
const e = resolvedRecently.get(requestID)
|
|
281
|
+
if (e === undefined) return false
|
|
282
|
+
if (e.exp <= Date.now()) {
|
|
283
|
+
resolvedRecently.delete(requestID)
|
|
284
|
+
return false
|
|
285
|
+
}
|
|
286
|
+
return true
|
|
287
|
+
}
|
|
288
|
+
/** 提示(卡片/文字菜单)实际投递后置标;若清槽回执因「无卡可关」被挂起且卡已迟到投递,补发回执。 */
|
|
289
|
+
function markPromptDelivered(userId: string, requestID: string): void {
|
|
290
|
+
const cur = pendingPermissions.get(userId)
|
|
291
|
+
if (cur?.request.id === requestID) cur.promptDelivered = true
|
|
292
|
+
const e = resolvedRecently.get(requestID)
|
|
293
|
+
if (!e?.notice) return
|
|
294
|
+
const n = e.notice
|
|
295
|
+
e.notice = undefined
|
|
296
|
+
void safeDeliver(
|
|
297
|
+
n.ctx,
|
|
298
|
+
`🔄 审批 ${requestID.slice(-8)} 已由${n.origin === "bot" ? "机器人回合侧" : "桌面端"}处理(${n.label}),QQ 审批自动关闭`,
|
|
299
|
+
).catch(() => {})
|
|
300
|
+
}
|
|
301
|
+
/** 发送窗:给 replied/resolve 一个取消在飞发卡的窗口;仅 SEND_GRACE_MS>0 才等待,0 保持原同步路径。 */
|
|
302
|
+
async function waitSendGrace(): Promise<void> {
|
|
303
|
+
if (SEND_GRACE_MS <= 0) return
|
|
304
|
+
await new Promise<void>((resolve) => {
|
|
305
|
+
const timer = setTimeout(resolve, SEND_GRACE_MS)
|
|
306
|
+
timer.unref?.()
|
|
307
|
+
})
|
|
308
|
+
}
|
|
237
309
|
// DEF-qqbot-20261112-5(2026-11-12 ZERO4 实测卡风暴实证):同一回合并联发起多个
|
|
238
310
|
// ask(异 request id)时,单挂槽跨请求覆写 + 双推送路径竞态会让先到的请求被重复
|
|
239
311
|
// 推卡(A 卡×2/B 卡×1 实证)。已推卡请求 id 环:同步认领(check+mark 原子,闭掉
|
|
@@ -303,6 +375,7 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
303
375
|
adopted.alertTimer = startNudgeTimer(ctx.userId, request.id, ctx)
|
|
304
376
|
adopted.timer = setTimeout(() => {
|
|
305
377
|
if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
|
|
378
|
+
markResolvedRecently(request.id)
|
|
306
379
|
pendingPermissions.delete(ctx.userId)
|
|
307
380
|
savePendingPermMap(pendingPermissions, PERSIST_FILE)
|
|
308
381
|
deps.onDecision?.(ctx.userId) // TTL 自动拒绝也要唤醒被守卫挡回的队列
|
|
@@ -326,6 +399,7 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
326
399
|
const alertTimer = startNudgeTimer(ctx.userId, request.id, ctx)
|
|
327
400
|
const timer = setTimeout(() => {
|
|
328
401
|
if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
|
|
402
|
+
markResolvedRecently(request.id)
|
|
329
403
|
pendingPermissions.delete(ctx.userId)
|
|
330
404
|
savePendingPermMap(pendingPermissions, PERSIST_FILE)
|
|
331
405
|
deps.onDecision?.(ctx.userId) // TTL 自动拒绝也要唤醒被守卫挡回的队列
|
|
@@ -354,13 +428,35 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
354
428
|
// 的请求(并发异请求覆写场景被其他路径推过)不再重复推卡。
|
|
355
429
|
if (claimCardPush(request.id)) {
|
|
356
430
|
void (async () => {
|
|
431
|
+
const isCancelled = () =>
|
|
432
|
+
wasResolvedRecently(request.id) || pendingPermissions.get(ctx.userId)?.request.id !== request.id
|
|
433
|
+
// 发卡前复查:clearIfResolved/resolve/TTL 可能已在异步任务起跑前清槽——死卡不得再发。
|
|
434
|
+
if (isCancelled()) {
|
|
435
|
+
console.log(`[perm] 发卡前复查:槽已清,放弃发卡 request=${request.id}`)
|
|
436
|
+
return
|
|
437
|
+
}
|
|
438
|
+
if (SEND_GRACE_MS > 0) {
|
|
439
|
+
await waitSendGrace()
|
|
440
|
+
if (isCancelled()) {
|
|
441
|
+
console.log(`[perm] 发送窗内请求已解决,放弃发卡 request=${request.id}`)
|
|
442
|
+
return
|
|
443
|
+
}
|
|
444
|
+
}
|
|
357
445
|
const sentByCard = deps.sendApprovalPrompt
|
|
358
|
-
? await deps.sendApprovalPrompt(ctx, request, mainSessionId, "bot").catch(() => false)
|
|
446
|
+
? await deps.sendApprovalPrompt(ctx, request, mainSessionId, "bot", isCancelled).catch(() => false)
|
|
359
447
|
: false
|
|
448
|
+
if (sentByCard) markPromptDelivered(ctx.userId, request.id)
|
|
449
|
+
const stillPending = () => pendingPermissions.get(ctx.userId)?.request.id === request.id
|
|
450
|
+
if (!stillPending()) {
|
|
451
|
+
console.log(`[perm] 发卡途中槽被清:卡片将迟到(死卡,平台无撤回),request=${request.id}`)
|
|
452
|
+
return
|
|
453
|
+
}
|
|
360
454
|
if (!sentByCard) {
|
|
361
|
-
await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "bot"))
|
|
362
|
-
|
|
363
|
-
|
|
455
|
+
await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "bot"))
|
|
456
|
+
.then(() => markPromptDelivered(ctx.userId, request.id))
|
|
457
|
+
.catch((error) => {
|
|
458
|
+
console.error("[bridge] 发送审批请求失败:", error)
|
|
459
|
+
})
|
|
364
460
|
}
|
|
365
461
|
})()
|
|
366
462
|
}
|
|
@@ -370,6 +466,7 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
370
466
|
function resolve(userId: string, decision: PermissionDecision): void {
|
|
371
467
|
const entry = pendingPermissions.get(userId)
|
|
372
468
|
if (!entry) return
|
|
469
|
+
markResolvedRecently(entry.request.id)
|
|
373
470
|
clearTimers(entry)
|
|
374
471
|
pendingPermissions.delete(userId)
|
|
375
472
|
savePendingPermMap(pendingPermissions, PERSIST_FILE)
|
|
@@ -463,10 +560,13 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
463
560
|
const sentByCard = deps.sendApprovalPrompt
|
|
464
561
|
? await deps.sendApprovalPrompt(e.ctx, e.request, e.mainSessionId, e.origin).catch(() => false)
|
|
465
562
|
: false
|
|
563
|
+
if (sentByCard) markPromptDelivered(uid, e.request.id)
|
|
466
564
|
if (!sentByCard) {
|
|
467
|
-
await sendReply(e.ctx, formatPermissionPrompt(e.request, e.mainSessionId, e.origin))
|
|
468
|
-
|
|
469
|
-
|
|
565
|
+
await sendReply(e.ctx, formatPermissionPrompt(e.request, e.mainSessionId, e.origin))
|
|
566
|
+
.then(() => markPromptDelivered(uid, e.request.id))
|
|
567
|
+
.catch((error) => {
|
|
568
|
+
console.error("[bridge] 恢复审批推送失败:", error)
|
|
569
|
+
})
|
|
470
570
|
}
|
|
471
571
|
})()
|
|
472
572
|
}
|
|
@@ -491,6 +591,7 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
491
591
|
const directory = deps.directoryOf?.(userId)
|
|
492
592
|
const timer = setTimeout(() => {
|
|
493
593
|
if (pendingPermissions.get(userId)?.request.id !== request.id) return
|
|
594
|
+
markResolvedRecently(request.id)
|
|
494
595
|
pendingPermissions.delete(userId)
|
|
495
596
|
savePendingPermMap(pendingPermissions, PERSIST_FILE)
|
|
496
597
|
deps.onDecision?.(userId) // 外部审批 TTL 拒绝也要唤醒队列
|
|
@@ -519,26 +620,37 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
519
620
|
// 场景下本请求已被他路推过而重复推卡。
|
|
520
621
|
if (claimCardPush(request.id)) {
|
|
521
622
|
void (async () => {
|
|
522
|
-
// DEF-qqbot-20261114-P5
|
|
523
|
-
//
|
|
524
|
-
//
|
|
525
|
-
|
|
526
|
-
|
|
623
|
+
// DEF-qqbot-20261114-P5 + 2026-11-28 死卡竞态修复:发卡有 token+网络耗时,
|
|
624
|
+
// 期间桌面端可能已处理(联动清槽)。有效防线=①发卡前复查 ②发送层 isCancelled
|
|
625
|
+
// (token 后/QQ API 前放弃)③发送后槽位复查 ④文字降级前复查。
|
|
626
|
+
const isCancelled = () =>
|
|
627
|
+
wasResolvedRecently(request.id) || pendingPermissions.get(userId)?.request.id !== request.id
|
|
628
|
+
if (isCancelled()) {
|
|
629
|
+
console.log(`[perm] 发卡前复查:槽已清,放弃发卡 request=${request.id}`)
|
|
630
|
+
return
|
|
631
|
+
}
|
|
632
|
+
if (SEND_GRACE_MS > 0) {
|
|
633
|
+
await waitSendGrace()
|
|
634
|
+
if (isCancelled()) {
|
|
635
|
+
console.log(`[perm] 发送窗内请求已解决,放弃发卡 request=${request.id}`)
|
|
636
|
+
return
|
|
637
|
+
}
|
|
638
|
+
}
|
|
527
639
|
const sentByCard = deps.sendApprovalPrompt
|
|
528
|
-
? await deps.sendApprovalPrompt(ctx, request, mainSessionId, origin).catch(() => false)
|
|
640
|
+
? await deps.sendApprovalPrompt(ctx, request, mainSessionId, origin, isCancelled).catch(() => false)
|
|
529
641
|
: false
|
|
642
|
+
if (sentByCard) markPromptDelivered(userId, request.id)
|
|
530
643
|
const stillPending = () => pendingPermissions.get(userId)?.request.id === request.id
|
|
531
644
|
if (!stillPending()) {
|
|
532
645
|
console.log(`[perm] 发卡途中槽被清:卡片将迟到(死卡,平台无撤回),request=${request.id}`)
|
|
646
|
+
return
|
|
533
647
|
}
|
|
534
648
|
if (!sentByCard) {
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
console.error("[bridge] 发送审批请求失败:", error)
|
|
541
|
-
})
|
|
649
|
+
await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "external"))
|
|
650
|
+
.then(() => markPromptDelivered(userId, request.id))
|
|
651
|
+
.catch((error) => {
|
|
652
|
+
console.error("[bridge] 发送审批请求失败:", error)
|
|
653
|
+
})
|
|
542
654
|
}
|
|
543
655
|
})()
|
|
544
656
|
}
|
|
@@ -552,6 +664,7 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
552
664
|
if (entry.request.id !== requestID) continue
|
|
553
665
|
if (sessionID && entry.request.sessionID && sessionID !== entry.request.sessionID) continue
|
|
554
666
|
const e = entry
|
|
667
|
+
markResolvedRecently(requestID)
|
|
555
668
|
clearTimers(e)
|
|
556
669
|
pendingPermissions.delete(uid)
|
|
557
670
|
savePendingPermMap(pendingPermissions, PERSIST_FILE)
|
|
@@ -565,16 +678,34 @@ export function createPermissionGate(deps: PermissionGateDeps): PermissionGate {
|
|
|
565
678
|
? "拒绝"
|
|
566
679
|
: `已处理(${String(reply ?? "未知")})`
|
|
567
680
|
console.log(`[perm] 联动清槽(源头已解决):uid=${uid.slice(0, 8)}… request=${requestID} reply=${String(reply)}`)
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
681
|
+
// 2026-11-28:「自动关闭」回执只在提示实际投递后发出——无卡可关时发回执属误报(owner 实证)。
|
|
682
|
+
// 提示未投递则挂起:卡若随后迟到投递成功(死卡)由 markPromptDelivered 补发;始终未投递则静默。
|
|
683
|
+
// resumedFromDisk 保持保守旧行为(重启前可能确有旧卡)。
|
|
684
|
+
if (e.promptDelivered || e.resumedFromDisk) {
|
|
685
|
+
void safeDeliver(
|
|
686
|
+
e.ctx,
|
|
687
|
+
`🔄 审批 ${requestID.slice(-8)} 已由${e.origin === "bot" ? "机器人回合侧" : "桌面端"}处理(${label}),QQ 审批自动关闭`,
|
|
688
|
+
).catch(() => {})
|
|
689
|
+
} else {
|
|
690
|
+
const r = resolvedRecently.get(requestID)
|
|
691
|
+
if (r) r.notice = { label, origin: e.origin, ctx: e.ctx }
|
|
692
|
+
console.log(`[perm] 提示未投递(无卡可关),自动关闭回执挂起 request=${requestID}`)
|
|
693
|
+
}
|
|
572
694
|
return true
|
|
573
695
|
}
|
|
574
696
|
return false
|
|
575
697
|
}
|
|
576
698
|
|
|
577
|
-
return {
|
|
699
|
+
return {
|
|
700
|
+
hasPending,
|
|
701
|
+
getPending,
|
|
702
|
+
waitForDecision,
|
|
703
|
+
resolve,
|
|
704
|
+
restore,
|
|
705
|
+
pushExternal: pushExternalImpl,
|
|
706
|
+
clearIfResolved,
|
|
707
|
+
wasResolvedRecently,
|
|
708
|
+
}
|
|
578
709
|
}
|
|
579
710
|
|
|
580
711
|
// 解析用户的审批回复(自然语言或 /allow /always /deny 命令式)。
|
|
@@ -6,8 +6,9 @@
|
|
|
6
6
|
// 限额耗尽或窗口过期后继续"被动回复"必然被平台拒绝,白白浪费一次 API 往返
|
|
7
7
|
// 且推迟送达。本模块在被动尝试前预判:不可被动 → 直接走主动通道(调用方
|
|
8
8
|
// 负责主动配额记账),可被动 → 放行并在发送成功后记账。
|
|
9
|
-
//
|
|
10
|
-
//
|
|
9
|
+
// 实现参考 tencent-connect/openclaw-qqbot(MIT):src/outbound/reply-limiter.ts。
|
|
10
|
+
// 本文件与该实现具有相同的接口、默认参数和核心状态机,属于派生修订而非独立原创。
|
|
11
|
+
// 上游版权与许可全文见 THIRD_PARTY_NOTICES.md;本项目保留来源声明,不删除或淡化归属。
|
|
11
12
|
export interface ReplyLimiterConfig {
|
|
12
13
|
/** 每条消息最大被动回复次数(官方规则 4) */
|
|
13
14
|
limit?: number
|
package/src/core/send-media.ts
CHANGED
|
@@ -87,10 +87,10 @@ export interface SendLocalFileDeps {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
/**
|
|
90
|
-
*
|
|
91
|
-
* file:// 前缀剥离(含 Windows file:///C:/ 三斜杠形态)→ URL decode(非法编码按原样)
|
|
92
|
-
* → ~
|
|
93
|
-
*
|
|
90
|
+
* normalizeLocalPath 派生修订自 openclaw local-file-router 的 normalizePath:
|
|
91
|
+
* 保留 file:// 前缀剥离(含 Windows file:///C:/ 三斜杠形态)→ URL decode(非法编码按原样)
|
|
92
|
+
* → ~ 展开为家目录的相同处理顺序。白名单/拒绝名单判定必须先于或基于规范化结果,
|
|
93
|
+
* 否则同一文件因写法不同得到两种判定。该函数来源见 THIRD_PARTY_NOTICES.md。
|
|
94
94
|
*/
|
|
95
95
|
export function normalizeLocalPath(p: string): string {
|
|
96
96
|
let r = p.trim()
|
|
@@ -115,8 +115,8 @@ export async function sendLocalFile(
|
|
|
115
115
|
filePath: string,
|
|
116
116
|
deps: SendLocalFileDeps,
|
|
117
117
|
): Promise<string> {
|
|
118
|
-
// X 项(2026-11-22
|
|
119
|
-
//
|
|
118
|
+
// X 项(2026-11-22):上述 normalizeLocalPath 为派生修订,来源已登记;其余发送、
|
|
119
|
+
// 拒绝名单/白名单、上传流程为项目实现。规范化在拒绝名单/白名单之前(否则
|
|
120
120
|
// file:///C:/x 与 C:/x 同一文件两种判定结果)。非法编码按原样不炸。
|
|
121
121
|
const trimmed = normalizeLocalPath(filePath)
|
|
122
122
|
// DEF-qqbot-20261112-03:文件级拒绝优先于目录白名单(穿越解析落白名单根也拦)
|
package/src/core/stt.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @input: 音频字节 + OpenAI 兼容 STT 端点配置(fetch 可注入,测试用)
|
|
2
2
|
// @output: sttConfigured / sttTranscribe
|
|
3
|
-
// @pos: core - 语音外部转写回退(2026-11-23
|
|
3
|
+
// @pos: core - 语音外部转写回退(2026-11-23 学习参考 AD 项,源=hermes-agent adapter.py P0 邻接)
|
|
4
4
|
//
|
|
5
5
|
// 链路:QQ 内置 ASR(asr_refer_text,免费优先)→ 空时回退本模块(GLM-ASR/Whisper/
|
|
6
6
|
// 任意 OpenAI 兼容 /audio/transcriptions 端点)。未配置三键时本模块整体离线——
|
package/src/core/watchdog.ts
CHANGED
|
@@ -360,11 +360,12 @@ export interface SuperviseDeps {
|
|
|
360
360
|
policy?: SupervisorPolicy
|
|
361
361
|
/**
|
|
362
362
|
* 触发形态:health-check=周期巡检(默认);manual-restart=openqq restart
|
|
363
|
-
*
|
|
364
|
-
* manual-restart
|
|
365
|
-
*
|
|
363
|
+
* 人工请求;manual-stop=openqq stop 人工停止(design §3.9.1:restart/stop 都是
|
|
364
|
+
* superviseOnce 的调用方而非独立实现)。manual-restart 下健康实例也会被优雅杀后拉起;
|
|
365
|
+
* manual-stop 下健康实例优雅杀后不拉起、不计重启强度账。两者都跳过「杀前复核」
|
|
366
|
+
* (人工意图即权威,复核只防监督者误杀);认领互斥/审计分家全部照旧。
|
|
366
367
|
*/
|
|
367
|
-
request?: "health-check" | "manual-restart"
|
|
368
|
+
request?: "health-check" | "manual-restart" | "manual-stop"
|
|
368
369
|
now?: () => number
|
|
369
370
|
kill?: (pid: number, signal?: "SIGTERM" | "SIGKILL") => void
|
|
370
371
|
isAlive?: (pid: number) => boolean
|
|
@@ -374,6 +375,8 @@ export interface SuperviseDeps {
|
|
|
374
375
|
alert?: (message: string) => void
|
|
375
376
|
statePath?: string
|
|
376
377
|
claimPath?: string
|
|
378
|
+
/** manual-stop 持有标记路径(测试注入临时文件;缺省 ~/.openqq/supervisor-hold.json) */
|
|
379
|
+
holdPath?: string
|
|
377
380
|
/** 监督动作审计日志路径(测试注入临时文件,避免污染真实 watchdog.log) */
|
|
378
381
|
auditLogPath?: string
|
|
379
382
|
/**
|
|
@@ -408,6 +411,47 @@ function readJson<T>(path: string, fallback: T): T {
|
|
|
408
411
|
}
|
|
409
412
|
}
|
|
410
413
|
|
|
414
|
+
export interface SupervisorHold {
|
|
415
|
+
version: 1
|
|
416
|
+
reason: string
|
|
417
|
+
by: string
|
|
418
|
+
at: number
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function defaultHoldPath(): string {
|
|
422
|
+
return join(homedir(), ".openqq", "supervisor-hold.json")
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
export function readSupervisorHold(path = defaultHoldPath()): SupervisorHold | null {
|
|
426
|
+
try {
|
|
427
|
+
const raw = JSON.parse(readFileSync(path, "utf-8")) as Partial<SupervisorHold>
|
|
428
|
+
if (raw?.version === 1 && typeof raw.reason === "string" && typeof raw.by === "string" && typeof raw.at === "number") {
|
|
429
|
+
return raw as SupervisorHold
|
|
430
|
+
}
|
|
431
|
+
} catch {
|
|
432
|
+
/* 缺失/损坏视为无 hold */
|
|
433
|
+
}
|
|
434
|
+
return null
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export function writeSupervisorHold(path: string, reason: string, by: string): void {
|
|
438
|
+
try {
|
|
439
|
+
writeFileSync(path, JSON.stringify({ version: 1, reason, by, at: Date.now() } satisfies SupervisorHold))
|
|
440
|
+
} catch {
|
|
441
|
+
/* hold 落盘失败不阻断停止动作本身;下次巡检仍可能拉起,日志已留痕 */
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
export function clearSupervisorHold(path: string): boolean {
|
|
446
|
+
try {
|
|
447
|
+
if (!existsSync(path)) return false
|
|
448
|
+
unlinkSync(path)
|
|
449
|
+
return true
|
|
450
|
+
} catch {
|
|
451
|
+
return false
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
411
455
|
/**
|
|
412
456
|
* 单次监督:认领锁 → 判健康 → 决策 → 执行(优雅杀/拉起/放弃上报)→ 记强度账。
|
|
413
457
|
* 插件引导器与计划任务共用本函数,互斥靠 claim 文件,杜绝双开竞争。
|
|
@@ -454,8 +498,36 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
|
|
|
454
498
|
try {
|
|
455
499
|
const health = readBotHealth(deps.paths, now)
|
|
456
500
|
const state = readJson<SupervisorState>(statePath, { restartLog: [] })
|
|
501
|
+
const holdPath = deps.holdPath ?? defaultHoldPath()
|
|
502
|
+
const hold = readSupervisorHold(holdPath)
|
|
503
|
+
|
|
504
|
+
// manual-stop 持有标记:stop 是耐久停止,不是“停到下次巡检前”。健康巡检见 hold 且
|
|
505
|
+
// bot 未运行即让贤;bot 已在运行说明 hold 已陈旧(人工/外部已拉起),自动失效恢复监督。
|
|
506
|
+
if (hold && (!deps.request || deps.request === "health-check")) {
|
|
507
|
+
if (health.lockPid === null || health.pidAlive === false) {
|
|
508
|
+
log(`[supervisor] manual-stop hold 生效(${hold.reason}),跳过拉起`)
|
|
509
|
+
return { action: "yield", detail: `manual-stop hold 生效:${hold.reason}`, killedPid: null, spawnedPid: null }
|
|
510
|
+
}
|
|
511
|
+
if (clearSupervisorHold(holdPath)) {
|
|
512
|
+
log(`[supervisor] manual-stop hold 失效:bot 已在运行,恢复常规监督`)
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
// 人工重启是 hold 的显式解除入口:先清 hold 再走重启,避免“stop 后永远拉不起”。
|
|
516
|
+
if (deps.request === "manual-restart" && hold) {
|
|
517
|
+
if (clearSupervisorHold(holdPath)) log(`[supervisor] manual-stop hold 已解除(openqq restart)`)
|
|
518
|
+
}
|
|
519
|
+
|
|
457
520
|
let action = decideSupervise(health, state, now, policy)
|
|
458
521
|
|
|
522
|
+
// 人工请求停止(design §3.9.1 生命周期入口):停止是用户显式意图,必须可执行——
|
|
523
|
+
// 不被重启强度/冷却拦截(give-up 场景恰恰需要能停下来);bot 未运行/已死则只清锁不拉起。
|
|
524
|
+
if (deps.request === "manual-stop") {
|
|
525
|
+
action =
|
|
526
|
+
health.lockPid !== null && health.pidAlive !== false
|
|
527
|
+
? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求停止(openqq stop)" }
|
|
528
|
+
: { kind: "spawn", reason: "人工请求停止(bot 未运行,仅清锁)" }
|
|
529
|
+
}
|
|
530
|
+
|
|
459
531
|
// 人工请求重启(design §3.9.1 入口 3):健康实例也要优雅杀后拉起;
|
|
460
532
|
// bot 未运行/已死则只拉起。强度与冷却约束在 decideSupervise 内已经生效
|
|
461
533
|
//(needsRestart 为 false 时同样先查 give-up/cooldown,再走到这里覆盖动作)。
|
|
@@ -518,7 +590,7 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
|
|
|
518
590
|
// 若有心跳落盘必须被看见;随后重读一次,转新鲜即改判 ok、放弃本轮,全程审计留痕。
|
|
519
591
|
// 心跳「缺失」不豁免(语义同 decide:缺失视为未恢复,维持原判)。——
|
|
520
592
|
// 例外:manual-restart(人工意图即权威,不存在"误杀")。——
|
|
521
|
-
if (deps.request !== "manual-restart") {
|
|
593
|
+
if (deps.request !== "manual-restart" && deps.request !== "manual-stop") {
|
|
522
594
|
await sleep(300)
|
|
523
595
|
const recheck = readBotHealth(deps.paths, Date.now())
|
|
524
596
|
const recheckFresh =
|
|
@@ -582,6 +654,37 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
|
|
|
582
654
|
} catch {
|
|
583
655
|
/* 清锁失败不阻断拉起 */
|
|
584
656
|
}
|
|
657
|
+
|
|
658
|
+
// 人工停止:与重启共用认领互斥/优雅杀/清锁/审计,但不拉起、不计重启强度账。
|
|
659
|
+
// bot 独立存活是故障隔离语义,不是脱离用户控制;stop 是显式生命周期终点。
|
|
660
|
+
if (deps.request === "manual-stop") {
|
|
661
|
+
writeSupervisorHold(holdPath, action.reason, "openqq stop")
|
|
662
|
+
const detail = killedPid
|
|
663
|
+
? `${action.reason};已优雅停 pid=${killedPid};锁已清;hold 已立(巡检不拉起)`
|
|
664
|
+
: `${action.reason};锁已清;hold 已立(巡检不拉起)`
|
|
665
|
+
if (killedPid !== null) {
|
|
666
|
+
appendKillLog({
|
|
667
|
+
kind: "decision",
|
|
668
|
+
reason: action.reason,
|
|
669
|
+
health: {
|
|
670
|
+
lockPid: health.lockPid,
|
|
671
|
+
pidAlive: health.pidAlive,
|
|
672
|
+
heartbeatAgeMs: health.heartbeatAgeMs,
|
|
673
|
+
lockAgeMs: health.lockAgeMs,
|
|
674
|
+
},
|
|
675
|
+
killedPid,
|
|
676
|
+
killEscalation: "TERM",
|
|
677
|
+
spawnedPid: null,
|
|
678
|
+
restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
|
|
679
|
+
livenessVerdict: "stopped",
|
|
680
|
+
at: Date.now(),
|
|
681
|
+
})
|
|
682
|
+
}
|
|
683
|
+
audit(`主动停:${detail}`)
|
|
684
|
+
log(`[supervisor] 主动停:${detail}`)
|
|
685
|
+
return { action: "stopped", detail, killedPid, spawnedPid: null }
|
|
686
|
+
}
|
|
687
|
+
|
|
585
688
|
const spawnedPid = deps.spawn()
|
|
586
689
|
state.restartLog.push(Date.now())
|
|
587
690
|
state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2)
|
package/src/index.ts
CHANGED
|
@@ -102,7 +102,7 @@ async function main(): Promise<void> {
|
|
|
102
102
|
allowedUsers: r.allowedUsers,
|
|
103
103
|
})
|
|
104
104
|
|
|
105
|
-
// M 项(2026-10-30
|
|
105
|
+
// M 项(2026-10-30,参考竞品 proper-lockfile 方案零依赖手写):单实例锁防多开——
|
|
106
106
|
// 双实例同 bot 会被 QQ 网关互踢。后到实例待命轮询,宿主退出/暴毙(30s 僵尸判定)
|
|
107
107
|
// 后自动接管。QQ_INSTANCE_LOCK=false 关闭;=try 则抢不到即退出(插件引导器拉起
|
|
108
108
|
// 场景:多 location 并发拉起时防待命实例堆积)。
|
package/src/opencode/mirror.ts
CHANGED
|
@@ -10,6 +10,43 @@ import { redactSecrets } from "./history.js"
|
|
|
10
10
|
import { labelBlock } from "../core/markdown.js"
|
|
11
11
|
|
|
12
12
|
const USER_CLIP = 160
|
|
13
|
+
export const DIGEST_TITLE_MAX_WIDTH = 20 // 10 个中文,或 20 个 ASCII 的等效显示宽度
|
|
14
|
+
|
|
15
|
+
function isWideCodePoint(cp: number): boolean {
|
|
16
|
+
return cp >= 0x1100 && (
|
|
17
|
+
cp <= 0x115f || cp === 0x2329 || cp === 0x232a ||
|
|
18
|
+
(cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) ||
|
|
19
|
+
(cp >= 0xac00 && cp <= 0xd7a3) ||
|
|
20
|
+
(cp >= 0xf900 && cp <= 0xfaff) ||
|
|
21
|
+
(cp >= 0xfe10 && cp <= 0xfe19) ||
|
|
22
|
+
(cp >= 0xfe30 && cp <= 0xfe6f) ||
|
|
23
|
+
(cp >= 0xff00 && cp <= 0xff60) ||
|
|
24
|
+
(cp >= 0xffe0 && cp <= 0xffe6) ||
|
|
25
|
+
(cp >= 0x1f000 && cp <= 0x1faff) ||
|
|
26
|
+
(cp >= 0x20000 && cp <= 0x3fffd)
|
|
27
|
+
)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 会话标题按终端等效显示宽度截断:中文/全角/emoji 2 列,ASCII 1 列。 */
|
|
31
|
+
export function clipDigestTitle(value: string | undefined, maxWidth = DIGEST_TITLE_MAX_WIDTH): string {
|
|
32
|
+
const title = (value ?? "").replace(/\s+/g, " ").trim() || "未命名会话"
|
|
33
|
+
let width = 0
|
|
34
|
+
let out = ""
|
|
35
|
+
for (const char of title) {
|
|
36
|
+
const cp = char.codePointAt(0) ?? 0
|
|
37
|
+
const charWidth = /\p{Mark}/u.test(char) || cp === 0x200d || (cp >= 0xfe00 && cp <= 0xfe0f)
|
|
38
|
+
? 0
|
|
39
|
+
: isWideCodePoint(cp) ? 2 : 1
|
|
40
|
+
if (width + charWidth > maxWidth) return `${out}...`
|
|
41
|
+
out += char
|
|
42
|
+
width += charWidth
|
|
43
|
+
}
|
|
44
|
+
return out
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function digestSessionLabel(sessionId: string): string {
|
|
48
|
+
return sessionId.length > 10 ? `${sessionId.slice(0, 10)}…` : sessionId
|
|
49
|
+
}
|
|
13
50
|
|
|
14
51
|
// E2(2026-10-29,用户要求"摘要回全文"):答案截断上限改为运行时可配——
|
|
15
52
|
// 默认 0=不截断回全文(投递层 splitMessage 自动分条送达);设
|
|
@@ -50,8 +87,17 @@ export function digestTurnKey(messages: SessionMessage[]): string | null {
|
|
|
50
87
|
return null
|
|
51
88
|
}
|
|
52
89
|
|
|
90
|
+
export interface DigestIdentity {
|
|
91
|
+
sessionId: string
|
|
92
|
+
title?: string
|
|
93
|
+
}
|
|
94
|
+
|
|
53
95
|
// 构建最近一轮问答的摘要卡;返回 null = 无可镜像正文。
|
|
54
|
-
export function buildDigest(
|
|
96
|
+
export function buildDigest(
|
|
97
|
+
messages: SessionMessage[],
|
|
98
|
+
goalObjective?: string,
|
|
99
|
+
identity?: DigestIdentity,
|
|
100
|
+
): string | null {
|
|
55
101
|
const ordered = [...messages].reverse()
|
|
56
102
|
|
|
57
103
|
// A 方案第三桶(owner 2026-11-23):回合边界消息 type=synthetic = 引擎自主注入
|
|
@@ -90,7 +136,13 @@ export function buildDigest(messages: SessionMessage[], goalObjective?: string):
|
|
|
90
136
|
}
|
|
91
137
|
if (!answer) return null
|
|
92
138
|
|
|
93
|
-
const
|
|
139
|
+
const kind = goalDriven ? "🎯 目标续跑摘要" : "📋 桌面问答摘要"
|
|
140
|
+
const lines = [
|
|
141
|
+
identity
|
|
142
|
+
? `${kind} · ${clipDigestTitle(identity.title)} · ${digestSessionLabel(identity.sessionId)}`
|
|
143
|
+
: kind,
|
|
144
|
+
]
|
|
145
|
+
if (identity) lines.push("↩️ 引用回复仅在该会话仍为当前绑定时受理")
|
|
94
146
|
if (userText) lines.push(`🧑 ${clip(userText, USER_CLIP)}`)
|
|
95
147
|
const clipLimit = answerClipLimit()
|
|
96
148
|
if (clipLimit > 0) {
|