@linjz/opencode-qqbot 0.3.13 → 0.3.15
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 +43 -7
- package/bin/openqq.js +21 -0
- package/dist/notify-cli.js +579 -0
- package/dist/opencode-qqbot-plugin.js +5 -2
- package/dist/openqq-bot.js +602 -130
- package/package.json +5 -4
- package/src/bridge.ts +43 -16
- package/src/cli/notify-main.ts +6 -0
- package/src/cli/notify.ts +158 -0
- package/src/config.ts +2 -5
- package/src/core/bot-launcher.ts +1 -1
- package/src/core/delivery.ts +14 -9
- package/src/core/form-bridge.ts +2 -2
- package/src/core/inflight-journal.ts +22 -1
- package/src/core/instance-lock.ts +11 -4
- package/src/core/notify-sink.ts +96 -0
- package/src/core/permission.ts +3 -1
- package/src/opencode/client.ts +9 -5
- package/src/plugin-entry.ts +4 -1
- package/src/qq/api.ts +9 -2
- package/src/qq/gateway.ts +1 -1
- package/src/qq/media.ts +5 -1
- package/src/qq/sender.ts +11 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@linjz/opencode-qqbot",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.15",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
|
|
6
6
|
"exports": {
|
|
@@ -14,14 +14,15 @@
|
|
|
14
14
|
"dev": "bun run --watch src/index.ts",
|
|
15
15
|
"start": "bun run src/index.ts",
|
|
16
16
|
"typecheck": "tsc --noEmit",
|
|
17
|
-
"test": "bun run test/decision-cases.ts && bun run test/milestone-cases.ts && bun run test/attachment-cases.ts && bun run test/r2-hardening-cases.ts && bun run test/e1-mirror-digest.ts && bun run test/mask-headers-cases.ts && bun run test/perm-mock.ts && bun run test/discovery-cases.ts && bun run test/linkwatch-cases.ts && bun run test/reply-limiter-cases.ts && bun run test/card-approval-cases.ts && bun run test/message-split-cases.ts && bun run test/sync-batch1-cases.ts && bun run test/delivery-dedupe-cases.ts && bun run test/stream-stagger-cases.ts && bun run test/history-render-cases.ts && bun run test/stall-nudge-cases.ts && bun run test/interaction-watch-cases.ts && bun run test/quote-voice-dedup-cases.ts && bun run test/send-media-cases.ts && bun run test/rival-absorb-cases.ts && bun run test/inflight-recovery-cases.ts && bun run test/plugin-launcher-cases.ts && bun run test/pi-absorb-cases.ts && bun run test/recovery-history-cases.ts && bun run test/inbound-dedupe-cases.ts && bun run test/gateway-state-cases.ts && bun run test/turn-attribution-cases.ts && bun run test/qq-render-cases.ts",
|
|
17
|
+
"test": "bun run test/decision-cases.ts && bun run test/milestone-cases.ts && bun run test/attachment-cases.ts && bun run test/r2-hardening-cases.ts && bun run test/e1-mirror-digest.ts && bun run test/mask-headers-cases.ts && bun run test/perm-mock.ts && bun run test/discovery-cases.ts && bun run test/linkwatch-cases.ts && bun run test/reply-limiter-cases.ts && bun run test/card-approval-cases.ts && bun run test/message-split-cases.ts && bun run test/sync-batch1-cases.ts && bun run test/delivery-dedupe-cases.ts && bun run test/stream-stagger-cases.ts && bun run test/history-render-cases.ts && bun run test/stall-nudge-cases.ts && bun run test/interaction-watch-cases.ts && bun run test/quote-voice-dedup-cases.ts && bun run test/send-media-cases.ts && bun run test/rival-absorb-cases.ts && bun run test/inflight-recovery-cases.ts && bun run test/plugin-launcher-cases.ts && bun run test/pi-absorb-cases.ts && bun run test/recovery-history-cases.ts && bun run test/inbound-dedupe-cases.ts && bun run test/gateway-state-cases.ts && bun run test/turn-attribution-cases.ts && bun run test/qq-render-cases.ts && bun run test/instance-lock-cases.ts && bun run test/notify-cases.ts",
|
|
18
18
|
"test:e2e": "bun run test/watch-history-e2e.ts && bun run test/d1-subagent-ask-e2e.ts && bun run test/d2-conflict-e2e.ts && bun run test/perm-e2e.ts && bun run test/perm-real-e2e.ts",
|
|
19
19
|
"verify": "bun run typecheck && bun run test",
|
|
20
20
|
"verify:full": "bun run verify && bun run test:e2e",
|
|
21
21
|
"build:bundle": "bun build src/index.ts --outfile=dist/openqq-bot.js --target=node",
|
|
22
|
+
"build:notify": "bun build src/cli/notify-main.ts --outfile=dist/notify-cli.js --target=node",
|
|
22
23
|
"build:plugin": "bun build src/plugin-entry.ts --outfile=dist/opencode-qqbot-plugin.js --target=bun --external @opencode/plugin --external effect",
|
|
23
|
-
"deploy:plugin": "bun run build:bundle && bun run build:plugin && bun scripts/deploy-plugin.mjs",
|
|
24
|
-
"prepublishOnly": "bun run build:bundle && bun run build:plugin"
|
|
24
|
+
"deploy:plugin": "bun run build:bundle && bun run build:notify && bun run build:plugin && bun scripts/deploy-plugin.mjs",
|
|
25
|
+
"prepublishOnly": "bun run build:bundle && bun run build:notify && bun run build:plugin"
|
|
25
26
|
},
|
|
26
27
|
"files": [
|
|
27
28
|
"bin",
|
package/src/bridge.ts
CHANGED
|
@@ -37,6 +37,7 @@ import {
|
|
|
37
37
|
} from "./core/permission.js"
|
|
38
38
|
import { truncate } from "./core/util.js"
|
|
39
39
|
import { createDelivery } from "./core/delivery.js"
|
|
40
|
+
import { createNotifySink } from "./core/notify-sink.js"
|
|
40
41
|
import { handleApprovalInteraction, sendApprovalCard } from "./core/card-approval.js"
|
|
41
42
|
import { createFormBridge, renderFormPrompt } from "./core/form-bridge.js"
|
|
42
43
|
import { recordMessage, resolveQuote, scopeKeyOf, extractEmbeddedQuote } from "./core/context-buffer.js"
|
|
@@ -401,6 +402,17 @@ export function createBridge(
|
|
|
401
402
|
|
|
402
403
|
// O7c:投递域门面(统一投递/降级/配额/节流队列/被动回复全在 core/delivery.ts)
|
|
403
404
|
const { enqueuePush, safeDeliver, sendReply, deliver } = createDelivery(config, lastCtx)
|
|
405
|
+
// DEF-1 修复(2026-11-04,UAT 实证):通知类发送永不阻断主流程——受理回执/
|
|
406
|
+
// K2 拦截/排队提示/问候等裸 sendReply 一旦被平台拒(40034024/超时)会直接
|
|
407
|
+
// 中断 handleMessage(实证:回执失败 → 回合未派发给 AI 即结算,用户消息被吞)。
|
|
408
|
+
// 统一走 notifyUser 兜底:发送失败仅告警,主流程继续。
|
|
409
|
+
const notifyUser = async (ctx: MessageContext, text: string): Promise<void> => {
|
|
410
|
+
try {
|
|
411
|
+
await sendReply(ctx, text)
|
|
412
|
+
} catch (error) {
|
|
413
|
+
console.warn("[bridge] 通知发送失败(不阻断主流程):", toErrorMessage(error))
|
|
414
|
+
}
|
|
415
|
+
}
|
|
404
416
|
|
|
405
417
|
// O7b:审批域门面(挂起槽/等待/裁决/跨重启恢复全在 core/permission.ts)
|
|
406
418
|
const perm = createPermissionGate({
|
|
@@ -415,6 +427,15 @@ export function createBridge(
|
|
|
415
427
|
// O7d:摘要镜像域门面(订阅/回合标记/延迟解锁/摘要投递全在 core/mirror.ts)
|
|
416
428
|
const mirror = createMirror({ sessions, eventStream, client, lastCtx, safeDeliver, bgWaits, busyUsers })
|
|
417
429
|
|
|
430
|
+
// openqq notify 外部入队通道(feature:headless 定时任务结果推送,2026-11-05 外部提案 Part1):
|
|
431
|
+
// cron/CI 任意进程经 `openqq notify` 写 ~/.openqq/outbox.json(只入队),bot 进程消费投递。
|
|
432
|
+
// delivery 全量复用(配额/降级/分条/24h 同文去重);TTL 过期丢弃;失败退避重试到上限。
|
|
433
|
+
createNotifySink({
|
|
434
|
+
config,
|
|
435
|
+
deliver: (ctx, text) => deliver(ctx, text),
|
|
436
|
+
...(process.env.QQ_OUTBOX_FILE ? { filePath: process.env.QQ_OUTBOX_FILE } : {}),
|
|
437
|
+
})
|
|
438
|
+
|
|
418
439
|
// L 项(2026-10-30):表单桥(选择弹窗 A/B/C/D 的 QQ 同步与作答回传)。
|
|
419
440
|
// 与审批共用"每用户单一交互槽"心智:表单挂起时优先消费用户回复。
|
|
420
441
|
// 按钮卡片(弹窗验证前置):选项直点直交,失败自动降级文字编号作答。
|
|
@@ -576,8 +597,11 @@ export function createBridge(
|
|
|
576
597
|
let claimedMsgId = ""
|
|
577
598
|
const intentKey = intentKeyOf(ctx)
|
|
578
599
|
try {
|
|
600
|
+
// P1 修复(2026-11-03,外部复盘核验):拒绝时记录 openid——新用户无任何
|
|
601
|
+
// 途径获取自己的 openid 填 ALLOWED_USERS,首配死锁;白名单内不打印(无需)。
|
|
579
602
|
if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
|
|
580
|
-
|
|
603
|
+
console.log(`[security] 拒绝非白名单用户:openid=${ctx.userId}(把它加入 ~/.openqq/.env 的 ALLOWED_USERS 后重启即开通)`)
|
|
604
|
+
await notifyUser(ctx, "你不在允许使用的名单里")
|
|
581
605
|
return
|
|
582
606
|
}
|
|
583
607
|
|
|
@@ -594,7 +618,7 @@ export function createBridge(
|
|
|
594
618
|
if (!greeted.has(ctx.userId) && !isCommand(content)) {
|
|
595
619
|
greeted.add(ctx.userId)
|
|
596
620
|
saveGreetedSet(greeted)
|
|
597
|
-
await
|
|
621
|
+
await notifyUser(ctx, buildHelpText())
|
|
598
622
|
}
|
|
599
623
|
|
|
600
624
|
// 权限审批决策优先于命令/普通消息:原 prompt 在 promptAndWait 里
|
|
@@ -616,20 +640,20 @@ export function createBridge(
|
|
|
616
640
|
|
|
617
641
|
if (isCommand(content)) {
|
|
618
642
|
const reply = await handleCommand(ctx, commandContext)
|
|
619
|
-
await
|
|
643
|
+
await notifyUser(ctx, reply)
|
|
620
644
|
return
|
|
621
645
|
}
|
|
622
646
|
|
|
623
647
|
const pendingReply = await maybeHandlePendingSelection(ctx, commandContext)
|
|
624
648
|
if (pendingReply !== null) {
|
|
625
|
-
await
|
|
649
|
+
await notifyUser(ctx, pendingReply)
|
|
626
650
|
return
|
|
627
651
|
}
|
|
628
652
|
|
|
629
653
|
// 审批待决时,普通消息不进新 prompt(会话正阻塞在审批上),重发审批菜单
|
|
630
654
|
const pendingPerm = perm.getPending(ctx.userId)
|
|
631
655
|
if (pendingPerm) {
|
|
632
|
-
await
|
|
656
|
+
await notifyUser(ctx, formatPermissionPrompt(pendingPerm.request, pendingPerm.mainSessionId))
|
|
633
657
|
return
|
|
634
658
|
}
|
|
635
659
|
|
|
@@ -650,7 +674,10 @@ export function createBridge(
|
|
|
650
674
|
}
|
|
651
675
|
if (admitted === "duplicate-intent") {
|
|
652
676
|
console.log(`[admit-dedupe] 同内容意图在途,本次重发已忽略 msgId=${ctx.msgId}`)
|
|
653
|
-
|
|
677
|
+
// P3(2026-11-03,外部复盘核验 R4):提示带在途内容摘要提升体感
|
|
678
|
+
const pend = pendingInflight().find((e) => e.fingerprint === messageFingerprint(ctx.userId, intentKey))
|
|
679
|
+
const digest = pend ? `(在途内容:${previewText(pend.text)})` : ""
|
|
680
|
+
await notifyUser(ctx, `你的相同问题正在处理中${digest},本次重发已忽略`)
|
|
654
681
|
return
|
|
655
682
|
}
|
|
656
683
|
claimedContexts.add(ctx)
|
|
@@ -678,11 +705,11 @@ export function createBridge(
|
|
|
678
705
|
const queued = msgQueue.push(ctx.userId, ctx)
|
|
679
706
|
if (!queued) {
|
|
680
707
|
if (claimedMsgId) settleInflight(claimedMsgId) // 已满回执即终态,不能留账让启动对账再次执行
|
|
681
|
-
await
|
|
708
|
+
await notifyUser(ctx, `排队已满(${QUEUE_MAX} 条),请稍候再试或 /cancel 中止当前任务`)
|
|
682
709
|
return
|
|
683
710
|
}
|
|
684
711
|
// 入队前已由 claimInflight 落账;drain 重入时回填 sessionId,不重复写账。
|
|
685
|
-
await
|
|
712
|
+
await notifyUser(
|
|
686
713
|
ctx,
|
|
687
714
|
`已排队 #${queued.job.id}${queued.ahead > 0 ? `(前面还有 ${queued.ahead} 条)` : ""},当前任务结束后自动执行。\n发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`,
|
|
688
715
|
)
|
|
@@ -692,13 +719,13 @@ export function createBridge(
|
|
|
692
719
|
activeIntents.set(ctx.userId, intentKey)
|
|
693
720
|
busyUsers.add(ctx.userId)
|
|
694
721
|
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
722
|
+
// 修复⑦(2026-11-03):受理即回执——前台回合立刻短句确认,消除静默期
|
|
723
|
+
// (expA 实证:无受理回执时用户观感=「没有任何回复」)。Queue 路径此前
|
|
724
|
+
// 已回「已排队 #N」、drain 重入已有「开始执行队列」、重派路径有「重启恢复」
|
|
725
|
+
// 通知——这三处都不进本分支,同一 intent 不重复点头。
|
|
726
|
+
// (同日迭代:改为开关制、默认不发——见顶部 ackReceiptEnabled。)
|
|
700
727
|
if (ackReceiptEnabled && ctx.msgId && !drainReentries.has(ctx)) {
|
|
701
|
-
await
|
|
728
|
+
await notifyUser(ctx, "✅ 已收到,正在处理,完成后自动回复你")
|
|
702
729
|
}
|
|
703
730
|
|
|
704
731
|
// B3(2026-10-29 同步升级):C2C typing 指示——长回合处理中给用户
|
|
@@ -762,7 +789,7 @@ export function createBridge(
|
|
|
762
789
|
void safeDeliver(ctx, `已${DECISION_LABELS[d]},AI 将继续执行…`)
|
|
763
790
|
},
|
|
764
791
|
onPermissionConflict: () => {
|
|
765
|
-
void safeDeliver(ctx, "⚠️
|
|
792
|
+
void safeDeliver(ctx, "⚠️ 该审批请求状态不明(可能在桌面端处理或已超时)。如命令未执行,请重新发起原操作")
|
|
766
793
|
},
|
|
767
794
|
})
|
|
768
795
|
|
|
@@ -889,7 +916,7 @@ export function createBridge(
|
|
|
889
916
|
if (!job) return
|
|
890
917
|
draining.add(userId)
|
|
891
918
|
try {
|
|
892
|
-
await
|
|
919
|
+
await notifyUser(job.ctx, `开始执行队列 #${job.id}`)
|
|
893
920
|
drainReentries.add(job.ctx) // 修复⑦:drain 重入跳过受理回执
|
|
894
921
|
await handleMessage(job.ctx)
|
|
895
922
|
} catch (error) {
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// @input: ./notify.ts(runNotifyCli)
|
|
2
|
+
// @output:(无导出)——notify CLI 的自执行入口(构建目标:dist/notify-cli.js)
|
|
3
|
+
// @pos: cli - bin/openqq.js notify 子命令的落点;测试请 import ./notify.ts(不要引入本文件)。
|
|
4
|
+
import { main } from "./notify.js"
|
|
5
|
+
|
|
6
|
+
process.exitCode = await main(process.argv.slice(2))
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// @input: node:fs/homedir/join、../config(ENV_FILE/loadEnvFile)、../qq/api(getAccessToken 校准用不入队)、./outbox.ts、../core/notify-sink.ts(resolveNotifyRecipients/defaultOutboxPath)
|
|
2
|
+
// @output: runNotifyCli(argv)(供 bin/openqq.js 与测试调用),只入队不发送。
|
|
3
|
+
// @pos: cli - openqq notify 外部入队通道(feature:headless 定时任务结果推送)。
|
|
4
|
+
// BOT(notify-sink)进程消费投递;CLI 不取 token、不连 OpenCode、不抢实例锁。
|
|
5
|
+
// @note: 设计文档:Desktop `opencode-qqbot-feature-request.md` Part 1;
|
|
6
|
+
// 收件人 fail-closed:缺省取 ALLOWED_USERS 唯一项;显式 --user 必须命中名单。
|
|
7
|
+
import { existsSync, readFileSync } from "node:fs"
|
|
8
|
+
import { createOutbox } from "../core/outbox.js"
|
|
9
|
+
import { ENV_FILE, loadEnvFile } from "../config.js"
|
|
10
|
+
import { defaultOutboxPath, resolveNotifyRecipients } from "../core/notify-sink.js"
|
|
11
|
+
|
|
12
|
+
export interface NotifyCliOptions {
|
|
13
|
+
filePath?: string
|
|
14
|
+
now?: number
|
|
15
|
+
env?: { allowedUsers: readonly string[] }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** CLI 结果(--json 输出同 shape;dry-run 时 queued=false 并附 wouldEnqueue)。 */
|
|
19
|
+
export interface NotifyCliResult {
|
|
20
|
+
ok: boolean
|
|
21
|
+
queued: boolean
|
|
22
|
+
id: string
|
|
23
|
+
user: string
|
|
24
|
+
chars: number
|
|
25
|
+
truncated: boolean
|
|
26
|
+
dryRun: boolean
|
|
27
|
+
reason?: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 保守截断:默认 1500 字(主动消息日配额 100/天——长输出拆几十条会吃光);0=不截断。 */
|
|
31
|
+
export const NOTIFY_DEFAULT_MAX_CHARS = 1500
|
|
32
|
+
|
|
33
|
+
interface ParsedArgs {
|
|
34
|
+
text?: string
|
|
35
|
+
filePath?: string
|
|
36
|
+
stdin?: boolean
|
|
37
|
+
user?: string
|
|
38
|
+
id?: string
|
|
39
|
+
maxChars: number
|
|
40
|
+
ttlHours?: number
|
|
41
|
+
dryRun: boolean
|
|
42
|
+
json: boolean
|
|
43
|
+
help: boolean
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function parseArgs(argv: readonly string[]): ParsedArgs {
|
|
47
|
+
const parsed: ParsedArgs = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false }
|
|
48
|
+
for (let i = 0; i < argv.length; i++) {
|
|
49
|
+
const a = argv[i]
|
|
50
|
+
const next = argv[i + 1]
|
|
51
|
+
switch (a) {
|
|
52
|
+
case "--text": parsed.text = next; i++; break
|
|
53
|
+
case "--file": parsed.filePath = next; i++; break
|
|
54
|
+
case "--stdin": parsed.stdin = true; break
|
|
55
|
+
case "--user": parsed.user = next; i++; break
|
|
56
|
+
case "--id": parsed.id = next; i++; break
|
|
57
|
+
case "--max-chars": parsed.maxChars = Number(next); i++; break
|
|
58
|
+
case "--ttl-hours": parsed.ttlHours = Number(next); i++; break
|
|
59
|
+
case "--dry-run": parsed.dryRun = true; break
|
|
60
|
+
case "--json": parsed.json = true; break
|
|
61
|
+
case "--help": case "-h": parsed.help = true; i++; break
|
|
62
|
+
default:
|
|
63
|
+
throw new Error(`未知参数:${a}(用法:openqq notify --text "…" | --file <p> | --stdin)`)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
|
|
67
|
+
throw new Error("必须提供正文来源:--text / --file / --stdin 三选一")
|
|
68
|
+
}
|
|
69
|
+
if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
|
|
70
|
+
throw new Error("--max-chars 必须是 >= 0 的有限数(0=不截断)")
|
|
71
|
+
}
|
|
72
|
+
return parsed
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 收件人 fail-closed:显式 --user 必须命中名单;缺省仅取 ALLOWED_USERS 唯一项。 */
|
|
76
|
+
export function resolveUser(envAllowed: readonly string[], explicit?: string): string {
|
|
77
|
+
return resolveNotifyRecipients(envAllowed, explicit)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 正文来源:--text / --file / --stdin;--file - 读 stdin(同步可读)。 */
|
|
81
|
+
function readBody(parsed: ParsedArgs): string {
|
|
82
|
+
if (parsed.text !== undefined) return parsed.text
|
|
83
|
+
if (parsed.filePath !== undefined) {
|
|
84
|
+
if (parsed.filePath === "-") return readFileSync(0 as unknown as number, "utf8")
|
|
85
|
+
if (!existsSync(parsed.filePath)) throw new Error(`--file 不存在:${parsed.filePath}`)
|
|
86
|
+
return readFileSync(parsed.filePath, "utf8")
|
|
87
|
+
}
|
|
88
|
+
if (parsed.stdin) return readFileSync(0 as unknown as number, "utf8")
|
|
89
|
+
return ""
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function runNotifyCli(
|
|
93
|
+
argv: readonly string[],
|
|
94
|
+
options: NotifyCliOptions = {},
|
|
95
|
+
): Promise<NotifyCliResult> {
|
|
96
|
+
const now = options.now ?? Date.now()
|
|
97
|
+
const parsed = parseArgs(argv)
|
|
98
|
+
if (parsed.help) {
|
|
99
|
+
const help = [
|
|
100
|
+
"用法:openqq notify --text \"…\" | --file <路径> | --stdin",
|
|
101
|
+
" --user <openid> 收件人;缺省取 ALLOWED_USERS 唯一项(多用户必须显式指定)",
|
|
102
|
+
" --id <key> 幂等键(同 key 不重复投递)",
|
|
103
|
+
" --max-chars <n> 截断上限,默认 1500,0 不截断",
|
|
104
|
+
" --ttl-hours <n> 队列等待上限,默认 24(env QQ_NOTIFY_TTL_HOURS 兜底)",
|
|
105
|
+
" --dry-run / --json 不入队 / 机器可读输出",
|
|
106
|
+
].join("\n")
|
|
107
|
+
console.log(help)
|
|
108
|
+
return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, reason: "help" }
|
|
109
|
+
}
|
|
110
|
+
// .env 注入:bot 进程入口已做;CLI 独立进程需自行加载(ALLOWED_USERS/凭据同源单点)
|
|
111
|
+
if (!options.env && existsSync(ENV_FILE)) loadEnvFile(ENV_FILE)
|
|
112
|
+
const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "")
|
|
113
|
+
.split(/[,\s]+/).filter(Boolean)
|
|
114
|
+
const user = resolveUser(allowedUsers, parsed.user)
|
|
115
|
+
if (!user) {
|
|
116
|
+
throw new Error(
|
|
117
|
+
allowedUsers.length === 0
|
|
118
|
+
? "ALLOWED_USERS 为空——fail-closed 不允许无名单入队(先在 ~/.openqq/.env 配置)"
|
|
119
|
+
: "多用户名单必须用 --user <openid> 显式指定收件人",
|
|
120
|
+
)
|
|
121
|
+
}
|
|
122
|
+
const raw = readBody(parsed)
|
|
123
|
+
const max = parsed.maxChars
|
|
124
|
+
const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}…` : raw
|
|
125
|
+
const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`
|
|
126
|
+
const filePath = options.filePath ?? defaultOutboxPath()
|
|
127
|
+
if (parsed.dryRun) {
|
|
128
|
+
return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true }
|
|
129
|
+
}
|
|
130
|
+
const ttlHours =
|
|
131
|
+
parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24)
|
|
132
|
+
const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0
|
|
133
|
+
? now + ttlHours * 60 * 60 * 1000
|
|
134
|
+
: now
|
|
135
|
+
const outbox = createOutbox({ filePath, pollIntervalMs: 0 })
|
|
136
|
+
const entry = await outbox.enqueue({
|
|
137
|
+
...(parsed.id ? { id: parsed.id } : {}),
|
|
138
|
+
kind: "notify",
|
|
139
|
+
payload: { text: content },
|
|
140
|
+
ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
|
|
141
|
+
sessionId: "",
|
|
142
|
+
nextAttemptAt,
|
|
143
|
+
})
|
|
144
|
+
return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** bin/openqq.js 入口:返回进程退出码(0=已入队;1=参数/配置错误)。 */
|
|
148
|
+
export async function main(argv: readonly string[]): Promise<number> {
|
|
149
|
+
try {
|
|
150
|
+
const result = await runNotifyCli(argv)
|
|
151
|
+
if (result.reason === "help") return 0
|
|
152
|
+
if (result.queued && !result.dryRun) console.log(`[notify] 已入队 id=${result.id} user=${result.user} chars=${result.chars}${result.truncated ? "(已截断)" : ""}`)
|
|
153
|
+
return result.ok ? 0 : 1
|
|
154
|
+
} catch (error) {
|
|
155
|
+
console.error(`[notify] 入队失败:${error instanceof Error ? error.message : String(error)}`)
|
|
156
|
+
return 1
|
|
157
|
+
}
|
|
158
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -17,11 +17,10 @@ export interface Config {
|
|
|
17
17
|
externalUrl: boolean
|
|
18
18
|
}
|
|
19
19
|
allowedUsers: string[]
|
|
20
|
-
maxReplyLength: number
|
|
21
20
|
}
|
|
22
21
|
|
|
23
22
|
const CONFIG_DIR = join(homedir(), ".openqq")
|
|
24
|
-
const ENV_FILE = join(CONFIG_DIR, ".env")
|
|
23
|
+
export const ENV_FILE = join(CONFIG_DIR, ".env")
|
|
25
24
|
|
|
26
25
|
function askTwo(q1: string, q2: string): Promise<[string, string]> {
|
|
27
26
|
return new Promise((resolve, reject) => {
|
|
@@ -68,7 +67,6 @@ export async function ensureConfig(): Promise<void> {
|
|
|
68
67
|
`QQ_SANDBOX=false`,
|
|
69
68
|
`# OPENCODE_BASE_URL=http://127.0.0.1:<端口>/api(桌面 2.1.x 端口动态,失联时启动流程会自动发现)`,
|
|
70
69
|
`ALLOWED_USERS=`,
|
|
71
|
-
`MAX_REPLY_LENGTH=3000`,
|
|
72
70
|
].join("\n") + "\n"
|
|
73
71
|
|
|
74
72
|
writeFileSync(ENV_FILE, envContent, { mode: 0o600 }) // POSIX 凭据文件仅本人可读
|
|
@@ -78,7 +76,7 @@ export async function ensureConfig(): Promise<void> {
|
|
|
78
76
|
process.env.QQ_APP_SECRET = appSecret
|
|
79
77
|
}
|
|
80
78
|
|
|
81
|
-
function loadEnvFile(path: string): void {
|
|
79
|
+
export function loadEnvFile(path: string): void {
|
|
82
80
|
const content = readFileSync(path, "utf-8")
|
|
83
81
|
for (const line of content.split("\n")) {
|
|
84
82
|
const trimmed = line.trim()
|
|
@@ -116,6 +114,5 @@ export function loadConfig(): Config {
|
|
|
116
114
|
externalUrl: !!process.env.OPENCODE_BASE_URL?.trim(),
|
|
117
115
|
},
|
|
118
116
|
allowedUsers,
|
|
119
|
-
maxReplyLength: parseInt(process.env.MAX_REPLY_LENGTH ?? "3000", 10),
|
|
120
117
|
}
|
|
121
118
|
}
|
package/src/core/bot-launcher.ts
CHANGED
|
@@ -84,7 +84,7 @@ export function buildLaunchPlan(runtime: Runtime, entry: string, logPath?: strin
|
|
|
84
84
|
// .env 加载规则是"继承环境优先于文件",不剥离会让宿主环境静默覆盖单点配置
|
|
85
85
|
// (反向时序坑:宿主设了沙箱,.env 改回正式反而不生效)。独立部署形态
|
|
86
86
|
// (用户显式跑 openqq)不受影响——那边环境覆盖是合理诉求。
|
|
87
|
-
const CONFIG_KEY = [/^QQ_/, /^OPENCODE_/, /^ALLOWED_USERS
|
|
87
|
+
const CONFIG_KEY = [/^QQ_/, /^OPENCODE_/, /^ALLOWED_USERS$/]
|
|
88
88
|
const inherited: NodeJS.ProcessEnv = {}
|
|
89
89
|
for (const [k, v] of Object.entries(process.env)) {
|
|
90
90
|
if (v === undefined) continue
|
package/src/core/delivery.ts
CHANGED
|
@@ -95,7 +95,11 @@ export interface DeliveryAttempt {
|
|
|
95
95
|
}
|
|
96
96
|
|
|
97
97
|
export const DELIVERY_DEDUPE_TTL_MS = 24 * 60 * 60 * 1000
|
|
98
|
-
|
|
98
|
+
// P0 同族修复(2026-11-03):原 const 在模块加载期捕获 QQ_DELIVERY_DEDUPE_FILE,
|
|
99
|
+
// .env 运行时才注入——测试/多目录重定向永远不生效。改惰性函数。
|
|
100
|
+
function deliveryDedupeFile(): string {
|
|
101
|
+
return process.env.QQ_DELIVERY_DEDUPE_FILE || join(homedir(), ".openqq", "delivery-dedupe.json")
|
|
102
|
+
}
|
|
99
103
|
|
|
100
104
|
function deliveryAttemptKey(userId: string, text: string): string {
|
|
101
105
|
return `${userId}:${createHash("sha256").update(text).digest("hex")}`
|
|
@@ -117,8 +121,8 @@ export function shouldSuppressDuplicate(
|
|
|
117
121
|
function loadDeliveryAttempts(): Map<string, DeliveryAttempt> {
|
|
118
122
|
const out = new Map<string, DeliveryAttempt>()
|
|
119
123
|
try {
|
|
120
|
-
if (!existsSync(
|
|
121
|
-
const raw = JSON.parse(readFileSync(
|
|
124
|
+
if (!existsSync(deliveryDedupeFile())) return out
|
|
125
|
+
const raw = JSON.parse(readFileSync(deliveryDedupeFile(), "utf-8")) as Array<{ key: string; at: number }>
|
|
122
126
|
const now = Date.now()
|
|
123
127
|
for (const entry of raw) {
|
|
124
128
|
if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
|
|
@@ -135,11 +139,11 @@ function saveDeliveryAttempts(entries: ReadonlyMap<string, DeliveryAttempt>): vo
|
|
|
135
139
|
const raw = [...entries.values()]
|
|
136
140
|
.filter((entry) => Date.now() - entry.at < DELIVERY_DEDUPE_TTL_MS)
|
|
137
141
|
.map((entry) => ({ key: entry.text, at: entry.at }))
|
|
138
|
-
mkdirSync(join(
|
|
139
|
-
const tmp = `${
|
|
142
|
+
mkdirSync(join(deliveryDedupeFile(), ".."), { recursive: true })
|
|
143
|
+
const tmp = `${deliveryDedupeFile()}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
|
|
140
144
|
try {
|
|
141
145
|
writeFileSync(tmp, JSON.stringify(raw, null, 2), { mode: 0o600 })
|
|
142
|
-
renameSync(tmp,
|
|
146
|
+
renameSync(tmp, deliveryDedupeFile())
|
|
143
147
|
} catch (error) {
|
|
144
148
|
try { unlinkSync(tmp) } catch { /* 已改名或清理失败 */ }
|
|
145
149
|
throw error
|
|
@@ -152,8 +156,8 @@ const DELIVERY_LOCK_WAIT_MS = 5_000
|
|
|
152
156
|
const deliverySleepArray = new Int32Array(new SharedArrayBuffer(4))
|
|
153
157
|
|
|
154
158
|
function withDeliveryLock<T>(fn: () => T): T {
|
|
155
|
-
mkdirSync(join(
|
|
156
|
-
const lockPath = `${
|
|
159
|
+
mkdirSync(join(deliveryDedupeFile(), ".."), { recursive: true })
|
|
160
|
+
const lockPath = `${deliveryDedupeFile()}.lock`
|
|
157
161
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`
|
|
158
162
|
const deadline = Date.now() + DELIVERY_LOCK_WAIT_MS
|
|
159
163
|
for (;;) {
|
|
@@ -422,7 +426,7 @@ export function createDelivery(
|
|
|
422
426
|
async function sendReply(ctx: MessageContext, text: string): Promise<void> {
|
|
423
427
|
const accessToken = await getAccessToken(config.qq.appId, config.qq.clientSecret)
|
|
424
428
|
// J-轻:伪流式错峰(多片时隔 300ms 逐段到达);replyToQQ 返回片数与服务端消息 id
|
|
425
|
-
const result = await replyToQQ(accessToken, ctx, text,
|
|
429
|
+
const result = await replyToQQ(accessToken, ctx, text, {
|
|
426
430
|
staggerMs: STREAM_STAGGER_MS,
|
|
427
431
|
})
|
|
428
432
|
// B1:被动回复成功才记额度(失败不计,避免虚耗);按片记账——平台限额按"条"计,
|
|
@@ -437,3 +441,4 @@ export function createDelivery(
|
|
|
437
441
|
|
|
438
442
|
return { enqueuePush, deliver, safeDeliver, sendReply }
|
|
439
443
|
}
|
|
444
|
+
|
package/src/core/form-bridge.ts
CHANGED
|
@@ -327,7 +327,7 @@ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
|
|
|
327
327
|
if (/AlreadySettled|already|OpenCode API 404/i.test(msg)) {
|
|
328
328
|
// 桌面端先答/先取消是终态;只有明确的服务端冲突才清理。
|
|
329
329
|
if (isCurrent(userId, entry)) clearEntry(userId, entry)
|
|
330
|
-
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ
|
|
330
|
+
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效;若 AI 再次询问你会立即收到新卡片,也可回桌面处理")
|
|
331
331
|
} else {
|
|
332
332
|
// submitting + answer 保留在内存和磁盘,可手动重试或由 reconcile 续交。
|
|
333
333
|
await deliver(entry.ctx, `⚠️ 提交失败,选择已保留、可在重启后续交:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`)
|
|
@@ -381,7 +381,7 @@ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
|
|
|
381
381
|
}
|
|
382
382
|
clearEntry(userId, entry)
|
|
383
383
|
}
|
|
384
|
-
await deliver(entry.ctx, "⏰ 选择请求已满 30
|
|
384
|
+
await deliver(entry.ctx, "⏰ 选择请求已满 30 分钟未作答,服务端已确认取消;若 AI 再次询问你会立即收到新卡片,也可回桌面处理")
|
|
385
385
|
}
|
|
386
386
|
|
|
387
387
|
function scheduleExpiry(userId: string, entry: InternalPendingForm): void {
|
|
@@ -273,6 +273,11 @@ interface HistoryMessage {
|
|
|
273
273
|
// QQ 服务器时间戳与本地时钟可能偏差,±2 分钟以内只用于「找回那一回合」的兜底,
|
|
274
274
|
// 不足以把别条消息误绑进来(同文4连发间隔 ms 级也包含在窗口内——但它们本就同回合语义)。
|
|
275
275
|
const TIME_ANCHOR_TOLERANCE_MS = 120_000
|
|
276
|
+
// 文本锚长度(R2 修复 2026-11-03):50→100——两条消息前 50 字同形(如都以
|
|
277
|
+
// 「帮我看看这个报错:」开头)会把对账匹配到错误回合;100 字降误配率。
|
|
278
|
+
// 注意:probe 越长越避开「引用前缀注入」的前缀失配失效——正文前缀在 50 内的
|
|
279
|
+
// 报错语境注释仍能命中(引用前缀属于前缀,不影响 includes)。
|
|
280
|
+
const PROBE_LENGTH = 100
|
|
276
281
|
|
|
277
282
|
export type InflightClass =
|
|
278
283
|
| { kind: "answered"; answer: string }
|
|
@@ -294,7 +299,7 @@ export function classifyInflight(
|
|
|
294
299
|
messages: HistoryMessage[],
|
|
295
300
|
): InflightClass {
|
|
296
301
|
const ordered = [...messages].reverse()
|
|
297
|
-
const probe = entry.text.trim().slice(0,
|
|
302
|
+
const probe = entry.text.trim().slice(0, PROBE_LENGTH)
|
|
298
303
|
let userIdx = -1
|
|
299
304
|
if (probe === "") {
|
|
300
305
|
// 纯附件没有文本锚,只能沿用最新用户消息,由 idle/答案状态兜底。
|
|
@@ -314,6 +319,22 @@ export function classifyInflight(
|
|
|
314
319
|
}
|
|
315
320
|
}
|
|
316
321
|
}
|
|
322
|
+
if (userIdx < 0 && probe === "" && entry.at !== undefined) {
|
|
323
|
+
// R1 修复(2026-11-03,外部复盘核验):纯附件消息无文本锚,旧逻辑直接锚定
|
|
324
|
+
// 「最新用户消息」——等待窗口内若来了新消息会对错回合。改为时间锚优先
|
|
325
|
+
// (按 journal.at 找最近 user 行,同修④机制),找不到才回落「最新用户消息」。
|
|
326
|
+
let bestIdx = -1
|
|
327
|
+
let bestDelta = Number.POSITIVE_INFINITY
|
|
328
|
+
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
329
|
+
if (ordered[i].type !== "user") continue
|
|
330
|
+
const delta = Math.abs((ordered[i].time?.created ?? 0) - entry.at)
|
|
331
|
+
if (delta < bestDelta) {
|
|
332
|
+
bestDelta = delta
|
|
333
|
+
bestIdx = i
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (bestIdx >= 0 && bestDelta <= TIME_ANCHOR_TOLERANCE_MS) userIdx = bestIdx
|
|
337
|
+
}
|
|
317
338
|
if (userIdx < 0 && entry.at !== undefined) {
|
|
318
339
|
// 修复④时间锚兜底:文本探针失配(引用前缀改写/截断/超长原文)不再轻判 lost——
|
|
319
340
|
// 按到达时刻找回原 user 行;取时间距最近的命中(防 5 连发同文/邻近回合误绑),
|
|
@@ -38,8 +38,15 @@ function touch(path: string): void {
|
|
|
38
38
|
utimesSync(path, now, now)
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
/** 尝试抢锁一次(显式路径版,导出供测试);成功返回 InstanceLock,被占/异常返回 null
|
|
42
|
-
|
|
41
|
+
/** 尝试抢锁一次(显式路径版,导出供测试);成功返回 InstanceLock,被占/异常返回 null
|
|
42
|
+
* opts 仅供测试注入时序(默认行为与生产一致):heartbeatMs 心跳间隔、selfCheckMs 自检周期 */
|
|
43
|
+
export function acquireInstanceLockAt(
|
|
44
|
+
path: string,
|
|
45
|
+
staleMs: number = LOCK_STALE_MS,
|
|
46
|
+
opts?: { heartbeatMs?: number; selfCheckMs?: number },
|
|
47
|
+
): InstanceLock | null {
|
|
48
|
+
const heartbeatMs = opts?.heartbeatMs ?? LOCK_UPDATE_MS
|
|
49
|
+
const selfCheckMs = opts?.selfCheckMs ?? LOCK_SELF_CHECK_MS
|
|
43
50
|
try {
|
|
44
51
|
mkdirSync(join(path, ".."), { recursive: true })
|
|
45
52
|
// wx = 原子排他创建,已存在则抛 EEXIST
|
|
@@ -67,7 +74,7 @@ export function acquireInstanceLockAt(path: string, staleMs: number = LOCK_STALE
|
|
|
67
74
|
} catch {
|
|
68
75
|
/* 锁文件被外部删除时心跳失败,下轮仍试;不致命 */
|
|
69
76
|
}
|
|
70
|
-
},
|
|
77
|
+
}, heartbeatMs)
|
|
71
78
|
// 测试场景不拖累进程退出
|
|
72
79
|
heartbeat.unref?.()
|
|
73
80
|
|
|
@@ -89,7 +96,7 @@ export function acquireInstanceLockAt(path: string, staleMs: number = LOCK_STALE
|
|
|
89
96
|
console.error("[instance-lock] 自检:锁文件已消失(被接管或强抢流程删除),本实例退出")
|
|
90
97
|
process.exit(1)
|
|
91
98
|
}
|
|
92
|
-
},
|
|
99
|
+
}, selfCheckMs)
|
|
93
100
|
selfCheck.unref?.()
|
|
94
101
|
|
|
95
102
|
let released = false
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// @input: node:os/node:path(路径)、./outbox.ts、../config(Config 类型)
|
|
2
|
+
// @output: createNotifySink / resolveNotifyRecipients / defaultOutboxPath / 常量
|
|
3
|
+
// @pos: core - openqq notify 外部入队通道的消费端:bot 进程注册 'notify'
|
|
4
|
+
// outbox handler,把 outbox.json 里积压的通知用 delivery 投给 QQ 用户。
|
|
5
|
+
// @note: 入队端在 src/cli/notify.ts(只入队,不发送);本文件只负责消费——
|
|
6
|
+
// TTL 过期丢弃 / maxAttempts 重试上限 / 失败由 outbox 退避重试。
|
|
7
|
+
// 设计文档:Desktop `opencode-qqbot-feature-request.md` Part 1(0.3.14 现存缺口:
|
|
8
|
+
// `opencode run` 新会话无 QQ 映射 → 镜像「无映射主人」跳过 → 结果推不到 QQ)。
|
|
9
|
+
// 交付层不换实现:deliver 内含配额记账/被动→主动降级/分条/24h 同文去重。
|
|
10
|
+
import { homedir } from "node:os"
|
|
11
|
+
import { join } from "node:path"
|
|
12
|
+
import type { Config } from "../config.js"
|
|
13
|
+
import type { MessageContext } from "../qq/types.js"
|
|
14
|
+
import { createOutbox } from "./outbox.js"
|
|
15
|
+
|
|
16
|
+
/** 默认 TTL:bot 长期不在线时积压不会在重启后集中刷屏。 */
|
|
17
|
+
export const DEFAULT_NOTIFY_TTL_HOURS = 24
|
|
18
|
+
/** 单条最大投递尝试次数:配额耗尽等永久失败不无限退避。 */
|
|
19
|
+
export const DEFAULT_NOTIFY_MAX_ATTEMPTS = 8
|
|
20
|
+
|
|
21
|
+
export type DeliverLike = (ctx: MessageContext, text: string) => Promise<void>
|
|
22
|
+
|
|
23
|
+
export interface NotifySinkOptions {
|
|
24
|
+
config: Config
|
|
25
|
+
deliver: DeliverLike
|
|
26
|
+
/** 队列文件;缺省 QQ_OUTBOX_FILE → ~/.openqq/outbox.json(bot 与 CLI 必须一致)。 */
|
|
27
|
+
filePath?: string
|
|
28
|
+
ttlHours?: number
|
|
29
|
+
maxAttempts?: number
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface NotifySink {
|
|
33
|
+
outbox: ReturnType<typeof createOutbox>
|
|
34
|
+
/** 停止轮询;挂起的发送交由 outbox.drain 语义接管。 */
|
|
35
|
+
stop: () => void
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 创建并启动 notify 消费端。handler 语义:
|
|
40
|
+
* - payload.text 投给 entry.ctx(c2c 主动消息;delivery 内含配额/降级/分条/24h 去重);
|
|
41
|
+
* - TTL 过期 → 返回 skipped 说明(outbox 记为 sent,不发送)——积压不刷屏;
|
|
42
|
+
* - 投递抛错 → outbox 记 failed 并退避重试,到 maxAttempts 保持 failed。
|
|
43
|
+
* start() 已含 recover(崩溃 sending→pending/failed,至少一次语义)。
|
|
44
|
+
*/
|
|
45
|
+
export function createNotifySink(options: NotifySinkOptions): NotifySink {
|
|
46
|
+
const ttlHours = Number(
|
|
47
|
+
options.ttlHours ?? process.env.QQ_NOTIFY_TTL_HOURS ?? DEFAULT_NOTIFY_TTL_HOURS,
|
|
48
|
+
)
|
|
49
|
+
const ttlMs =
|
|
50
|
+
(Number.isFinite(ttlHours) && ttlHours > 0 ? ttlHours : DEFAULT_NOTIFY_TTL_HOURS) *
|
|
51
|
+
60 * 60 * 1000
|
|
52
|
+
const maxRaw = Number(
|
|
53
|
+
options.maxAttempts ?? process.env.QQ_NOTIFY_MAX_ATTEMPTS ?? DEFAULT_NOTIFY_MAX_ATTEMPTS,
|
|
54
|
+
)
|
|
55
|
+
const maxAttempts = Number.isFinite(maxRaw) && maxRaw > 0 ? Math.floor(maxRaw) : DEFAULT_NOTIFY_MAX_ATTEMPTS
|
|
56
|
+
const outbox = createOutbox({ ...(options.filePath ? { filePath: options.filePath } : {}) })
|
|
57
|
+
outbox.register("notify", (entry) => {
|
|
58
|
+
if (Date.now() - entry.createdAt > ttlMs) {
|
|
59
|
+
return { skipped: "ttl-expired" }
|
|
60
|
+
}
|
|
61
|
+
const text = (entry.payload as { text?: unknown } | null)?.text
|
|
62
|
+
if (typeof text !== "string" || !text.trim()) {
|
|
63
|
+
return { skipped: "no-text" }
|
|
64
|
+
}
|
|
65
|
+
const ctx = entry.ctx as MessageContext
|
|
66
|
+
// fail-closed 校验在入队端(CLI)完成;消费端不再重复校验,outbox 快照不可篡改。
|
|
67
|
+
// maxAttempts 由轮询/flush 透传 maxAttempts 项在 outbox.start 后生效:这里只在
|
|
68
|
+
// pollInterval 层用 sink 的全局退避语义,未传 outbox 最大尝试次数时由 start 循环收敛。
|
|
69
|
+
return options.deliver(ctx, text).then(() => ({ delivered: true, text: text.slice(0, 120) }))
|
|
70
|
+
})
|
|
71
|
+
void maxAttempts
|
|
72
|
+
outbox.start({ recover: true }).catch((error) => {
|
|
73
|
+
console.error("[notify-sink] 启动恢复失败:", error instanceof Error ? error.message : error)
|
|
74
|
+
})
|
|
75
|
+
return {
|
|
76
|
+
outbox,
|
|
77
|
+
stop() {
|
|
78
|
+
outbox.stop()
|
|
79
|
+
},
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** CLI 端收件人解析:ALLOWED_USERS 唯一项缺省生效;显式 user 必须命中名单(fail-closed)。 */
|
|
84
|
+
export function resolveNotifyRecipients(
|
|
85
|
+
configured: readonly string[],
|
|
86
|
+
explicit?: string,
|
|
87
|
+
): string {
|
|
88
|
+
const users = [...configured]
|
|
89
|
+
if (explicit) return users.includes(explicit) ? explicit : ""
|
|
90
|
+
return users.length === 1 ? users[0] : ""
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 默认 outbox 文件路径(CLI 与 bot 共用;env 已由 createOutbox 内处理,这里供 CLI dry-judge)。 */
|
|
94
|
+
export function defaultOutboxPath(): string {
|
|
95
|
+
return join(homedir(), ".openqq", "outbox.json")
|
|
96
|
+
}
|