@linjz/opencode-qqbot 0.0.0-stage → 0.3.1
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/LICENSE +21 -0
- package/README.md +134 -3
- package/bin/openqq.js +2 -0
- package/package.json +42 -4
- package/src/_FOLDER.md +19 -0
- package/src/bridge.ts +731 -0
- package/src/commands.ts +514 -0
- package/src/config.ts +121 -0
- package/src/core/card-approval.ts +146 -0
- package/src/core/context-buffer.ts +52 -0
- package/src/core/delivery.ts +263 -0
- package/src/core/discovery.ts +151 -0
- package/src/core/form-bridge.ts +304 -0
- package/src/core/linkwatch.ts +195 -0
- package/src/core/mirror.ts +173 -0
- package/src/core/permission.ts +301 -0
- package/src/core/reply-limiter.ts +106 -0
- package/src/core/send-media.ts +90 -0
- package/src/core/util.ts +8 -0
- package/src/index.ts +134 -0
- package/src/opencode/_FOLDER.md +11 -0
- package/src/opencode/client.ts +386 -0
- package/src/opencode/eventstream.ts +138 -0
- package/src/opencode/history.ts +143 -0
- package/src/opencode/mirror.ts +65 -0
- package/src/opencode/sessions.ts +158 -0
- package/src/qq/_FOLDER.md +13 -0
- package/src/qq/api.ts +519 -0
- package/src/qq/gateway.ts +486 -0
- package/src/qq/media.ts +204 -0
- package/src/qq/sender.ts +300 -0
- package/src/qq/types.ts +146 -0
- package/tsconfig.json +24 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// @input: ../qq/api (getAccessToken, sendC2CMessage, sendGroupMessage, InlineKeyboard),
|
|
2
|
+
// ../qq/types (MessageContext, InteractionEvent),
|
|
3
|
+
// ./permission (formatPermissionPrompt, PendingPermission)
|
|
4
|
+
// @output: encodeButtonData, decodeButtonData, buildApprovalKeyboard, sendApprovalCard,
|
|
5
|
+
// handleApprovalInteraction
|
|
6
|
+
// @pos: core - 卡片按钮审批(A 项 2026-10-29)
|
|
7
|
+
//
|
|
8
|
+
// 设计吸收自 P0 官方源:dsh-qqbot src/features/{button-utils,approval-channel}.ts
|
|
9
|
+
// (button_data 明文 JSON + t 判别字段)与 @tencent-connect/qqbot-nodejs
|
|
10
|
+
// protocol/types.ts(KeyboardButton/InlineKeyboard 形状)。
|
|
11
|
+
// 与文字菜单并行不互拆:卡片优先,发送失败自动降级文字;文字通道原样保留。
|
|
12
|
+
// 安全基线(fail-closed):忽略按钮=不决策(权限保持挂起至 TTL);
|
|
13
|
+
// button_data 内嵌 request.id,槽位已被新请求替换时旧按钮点击直接拒识。
|
|
14
|
+
import { getAccessToken, sendC2CMessage, sendGroupMessage, type InlineKeyboard, type KeyboardButton } from "../qq/api.js"
|
|
15
|
+
import type { InteractionEvent, MessageContext } from "../qq/types.js"
|
|
16
|
+
import type { PermissionDecision, PermissionRequest } from "../opencode/client.js"
|
|
17
|
+
import { formatPermissionPrompt, type PendingPermission } from "./permission.js"
|
|
18
|
+
|
|
19
|
+
/** QQ 按钮 label 长度限制(dsh P0 实证) */
|
|
20
|
+
export const BUTTON_LABEL_MAX = 10
|
|
21
|
+
|
|
22
|
+
/** button_data 统一编码:明文 JSON + t 判别字段(dsh button-utils P0 格式),
|
|
23
|
+
* r=request.id 防伪(槽位替换后旧按钮失效) */
|
|
24
|
+
export interface ApprovalButtonData {
|
|
25
|
+
t: "approval"
|
|
26
|
+
r: string
|
|
27
|
+
d: "once" | "always" | "reject" | "ignore"
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function encodeButtonData(data: ApprovalButtonData): string {
|
|
31
|
+
return JSON.stringify(data)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function decodeButtonData(raw: string | undefined): ApprovalButtonData | undefined {
|
|
35
|
+
if (!raw) return undefined
|
|
36
|
+
try {
|
|
37
|
+
const parsed = JSON.parse(raw) as Partial<ApprovalButtonData>
|
|
38
|
+
if (
|
|
39
|
+
parsed !== null &&
|
|
40
|
+
typeof parsed === "object" &&
|
|
41
|
+
parsed.t === "approval" &&
|
|
42
|
+
typeof parsed.r === "string" &&
|
|
43
|
+
(parsed.d === "once" || parsed.d === "always" || parsed.d === "reject" || parsed.d === "ignore")
|
|
44
|
+
) {
|
|
45
|
+
return parsed as ApprovalButtonData
|
|
46
|
+
}
|
|
47
|
+
} catch {
|
|
48
|
+
// fall through
|
|
49
|
+
}
|
|
50
|
+
return undefined
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function clipLabel(text: string): string {
|
|
54
|
+
const s = text.trim()
|
|
55
|
+
return s.length > BUTTON_LABEL_MAX ? s.slice(0, BUTTON_LABEL_MAX - 1) + "…" : s
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function makeButton(label: string, style: number, data: ApprovalButtonData, ownerOpenid: string): KeyboardButton {
|
|
59
|
+
// visited_label = 点击后的原生回显(QQ 客户端把已点按钮渲染为已访问态、其余置灰——
|
|
60
|
+
// 这就是"dsh 点一个其余变灰"的平台原生机制,2026-10-30 用户要求抄的效果)
|
|
61
|
+
const visited = data.d === "once" || data.d === "always" ? `✓ ${label}` : data.d === "reject" ? `✗ ${label}` : label
|
|
62
|
+
return {
|
|
63
|
+
id: `approval-${data.d}-${data.r}`.slice(0, 64),
|
|
64
|
+
render_data: { label: clipLabel(label), visited_label: clipLabel(visited), style },
|
|
65
|
+
// permission.type=2 + specify_user_ids:仅审批发起人可点(官方 P0 字段,
|
|
66
|
+
// 防止群里其他人代点裁决)
|
|
67
|
+
action: { type: 1, permission: { type: 2, specify_user_ids: [ownerOpenid] }, data: encodeButtonData(data) },
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 审批卡片键盘:允许一次 / 总是允许 / 拒绝 / 忽略(2×2 布局) */
|
|
72
|
+
export function buildApprovalKeyboard(request: PermissionRequest, ownerOpenid: string): InlineKeyboard {
|
|
73
|
+
const mk = (d: ApprovalButtonData["d"], label: string, style: number): KeyboardButton =>
|
|
74
|
+
makeButton(label, style, { t: "approval", r: request.id, d }, ownerOpenid)
|
|
75
|
+
return {
|
|
76
|
+
content: {
|
|
77
|
+
rows: [
|
|
78
|
+
{ buttons: [mk("once", "允许一次", 1), mk("always", "总是允许", 1)] },
|
|
79
|
+
{ buttons: [mk("reject", "拒绝", 0), mk("ignore", "忽略", 0)] },
|
|
80
|
+
],
|
|
81
|
+
},
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface CardApprovalDeps {
|
|
86
|
+
appId: string
|
|
87
|
+
clientSecret: string
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** 发送审批卡片;成功=true。失败由调用方降级文字菜单(本函数不外抛)。 */
|
|
91
|
+
export async function sendApprovalCard(
|
|
92
|
+
deps: CardApprovalDeps,
|
|
93
|
+
ctx: MessageContext,
|
|
94
|
+
request: PermissionRequest,
|
|
95
|
+
mainSessionId: string,
|
|
96
|
+
): Promise<boolean> {
|
|
97
|
+
try {
|
|
98
|
+
const token = await getAccessToken(deps.appId, deps.clientSecret)
|
|
99
|
+
const keyboard = buildApprovalKeyboard(request, ctx.userId)
|
|
100
|
+
// 正文复用现有格式化(用户看到的字段与文字菜单完全一致)
|
|
101
|
+
const text = formatPermissionPrompt(request, mainSessionId)
|
|
102
|
+
if (ctx.type === "group" && ctx.groupId) {
|
|
103
|
+
await sendGroupMessage(token, ctx.groupId, text, ctx.msgId, undefined, true, keyboard)
|
|
104
|
+
} else {
|
|
105
|
+
await sendC2CMessage(token, ctx.userId, text, ctx.msgId, undefined, true, keyboard)
|
|
106
|
+
}
|
|
107
|
+
console.log(`[card-approval] 审批卡片已发送 user=${ctx.userId.slice(0, 8)}… request=${request.id}`)
|
|
108
|
+
return true
|
|
109
|
+
} catch (error) {
|
|
110
|
+
console.error("[card-approval] 审批卡片发送失败,将降级文字菜单:", error instanceof Error ? error.message : error)
|
|
111
|
+
return false
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface ApprovalGateLike {
|
|
116
|
+
getPending: (userId: string) => PendingPermission | undefined
|
|
117
|
+
resolve: (userId: string, decision: PermissionDecision) => void
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 互动回调 → 审批裁决。返回 true=已消费(含 ignore 吞掉);false=非本域事件。
|
|
121
|
+
* 竞态:文字回复与按钮先到先赢(resolve 后槽位即清空,后到者自然落空)。
|
|
122
|
+
* 身份:C2C 用 user_openid;群场景点击者走 group_member_openid(与挂起槽
|
|
123
|
+
* 对群用户的 member_openid 索引一致,自我评审 2026-10-29 修复)。 */
|
|
124
|
+
export function handleApprovalInteraction(event: InteractionEvent, gate: ApprovalGateLike): boolean {
|
|
125
|
+
const userId = event.user_openid ?? event.group_member_openid
|
|
126
|
+
if (!userId) return false
|
|
127
|
+
const button = decodeButtonData(event.data?.resolved?.button_data)
|
|
128
|
+
if (!button) return false
|
|
129
|
+
|
|
130
|
+
const pending = gate.getPending(userId)
|
|
131
|
+
if (!pending || pending.request.id !== button.r) {
|
|
132
|
+
// 槽位已空或已被新请求替换:旧按钮点击,拒识(fail-closed,不误裁决新请求)
|
|
133
|
+
console.log(`[card-approval] 拒识过期按钮点击 user=${userId.slice(0, 8)}… request=${button.r}`)
|
|
134
|
+
return true
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (button.d === "ignore") {
|
|
138
|
+
// 忽略=不决策:权限保持挂起,用户仍可文字回复或等 TTL 自动拒绝
|
|
139
|
+
console.log(`[card-approval] 用户忽略审批请求 user=${userId.slice(0, 8)}… request=${button.r}`)
|
|
140
|
+
return true
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
console.log(`[card-approval] 按钮裁决 user=${userId.slice(0, 8)}… request=${button.r} decision=${button.d}`)
|
|
144
|
+
gate.resolve(userId, button.d)
|
|
145
|
+
return true
|
|
146
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// @input: (模块级单例缓存)
|
|
2
|
+
// @output: recordMessage, resolveQuote, scopeKeyOf, resetContextBuffer(测试用)
|
|
3
|
+
// @pos: core - 消息上下文索引缓存(引用消息解析)
|
|
4
|
+
//
|
|
5
|
+
// 设计吸收自 P0:qqbot-nodejs middleware/quote-ref.ts(MemoryRefIndexStore +
|
|
6
|
+
// msgIdx 索引 + 解析)。QQ C2C/群消息的引用经由 message_reference.message_id
|
|
7
|
+
// 透传;QQ 不提供 C2C 历史消息拉取,故引用解析只能靠本缓存——我方发出的回复
|
|
8
|
+
// 也记录(消息 id 取服务端回执 MessageResponse.id),保证"引用 AI 答案"可解析。
|
|
9
|
+
// 单进程 bot 用进程内 LRU(每域 200 条)足够;跨重启引用解析为空属可接受降级。
|
|
10
|
+
interface RefEntry {
|
|
11
|
+
text: string
|
|
12
|
+
at: number
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const MAX_ENTRIES_PER_SCOPE = 200
|
|
16
|
+
const scopeBuffers = new Map<string, Map<string, RefEntry>>()
|
|
17
|
+
|
|
18
|
+
/** 域键:C2C 按用户,群聊按群(引用多在群内发生) */
|
|
19
|
+
export function scopeKeyOf(ctx: { type: string; userId: string; groupId?: string }): string {
|
|
20
|
+
return ctx.type === "group" && ctx.groupId ? `group:${ctx.groupId}` : `c2c:${ctx.userId}`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function bufferOf(scope: string): Map<string, RefEntry> {
|
|
24
|
+
let b = scopeBuffers.get(scope)
|
|
25
|
+
if (!b) {
|
|
26
|
+
b = new Map()
|
|
27
|
+
scopeBuffers.set(scope, b)
|
|
28
|
+
}
|
|
29
|
+
return b
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 记录一条消息(入站用户消息 + 我方出站回复) */
|
|
33
|
+
export function recordMessage(scope: string, msgId: string, text: string): void {
|
|
34
|
+
if (!msgId) return
|
|
35
|
+
const b = bufferOf(scope)
|
|
36
|
+
if (b.size >= MAX_ENTRIES_PER_SCOPE && !b.has(msgId)) {
|
|
37
|
+
const first = b.keys().next().value
|
|
38
|
+
if (first !== undefined) b.delete(first)
|
|
39
|
+
}
|
|
40
|
+
b.set(msgId, { text, at: Date.now() })
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 按引用 id 解析被引消息文本;不存在返回 null */
|
|
44
|
+
export function resolveQuote(scope: string, referencedMsgId: string): string | null {
|
|
45
|
+
const entry = scopeBuffers.get(scope)?.get(referencedMsgId)
|
|
46
|
+
return entry?.text ?? null
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 测试/运维用:清空全部缓存 */
|
|
50
|
+
export function resetContextBuffer(): void {
|
|
51
|
+
scopeBuffers.clear()
|
|
52
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// @input: ../config, ../qq/types, ../qq/api, ../qq/sender, fs/path/os
|
|
2
|
+
// @output: createDelivery
|
|
3
|
+
// @pos: 根层/core - 投递域(O7c 2026-10-15 自 bridge.ts 拆出:统一投递
|
|
4
|
+
// 被动→主动降级、日配额记账与落盘、观察推送节流队列、主动/被动通道发送)
|
|
5
|
+
import { existsSync, readFileSync, writeFileSync } from "fs"
|
|
6
|
+
import { join } from "path"
|
|
7
|
+
import { homedir } from "os"
|
|
8
|
+
import type { Config } from "../config.js"
|
|
9
|
+
import type { MessageContext } from "../qq/types.js"
|
|
10
|
+
import { getAccessToken, sendC2CMessage, sendGroupMessage, getNextMsgSeq } from "../qq/api.js"
|
|
11
|
+
import { replyToQQ } from "../qq/sender.js"
|
|
12
|
+
import { ReplyLimiter } from "./reply-limiter.js"
|
|
13
|
+
import { recordMessage, scopeKeyOf } from "./context-buffer.js"
|
|
14
|
+
|
|
15
|
+
// 用户级推送队列:节流合并(主动消息配额记账已移至 activeQuota 共享)
|
|
16
|
+
interface PushQueue {
|
|
17
|
+
lastSent: number
|
|
18
|
+
timer: ReturnType<typeof setTimeout> | null
|
|
19
|
+
lines: string[]
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// O5(2026-10-15,P2-4b):主动配额落盘——跨重启不归零,防日配额轻微超发。
|
|
23
|
+
const QUOTA_FILE = join(homedir(), ".openqq", "quota.json")
|
|
24
|
+
|
|
25
|
+
function loadQuotaMap(): Record<string, { day: string; count: number; warned: boolean }> {
|
|
26
|
+
try {
|
|
27
|
+
if (existsSync(QUOTA_FILE)) {
|
|
28
|
+
const raw = readFileSync(QUOTA_FILE, "utf-8")
|
|
29
|
+
const obj = JSON.parse(raw)
|
|
30
|
+
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
31
|
+
const out: Record<string, { day: string; count: number; warned: boolean }> = {}
|
|
32
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
33
|
+
const e = v as { day?: unknown; count?: unknown; warned?: unknown }
|
|
34
|
+
if (typeof e?.day === "string" && typeof e.count === "number") {
|
|
35
|
+
out[k] = { day: e.day, count: e.count, warned: Boolean(e.warned) }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return out
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
} catch {
|
|
42
|
+
// 损坏即空
|
|
43
|
+
}
|
|
44
|
+
return {}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function saveQuotaMap(m: ReadonlyMap<string, { day: string; count: number; warned: boolean }>): void {
|
|
48
|
+
try {
|
|
49
|
+
writeFileSync(QUOTA_FILE, JSON.stringify(Object.fromEntries(m)))
|
|
50
|
+
} catch (error) {
|
|
51
|
+
console.warn("[bridge] 配额落盘失败:", error instanceof Error ? error.message : error)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// B-msgid 纯函数(导出供测试,2026-10-29):挑选可"骑"的被动 msg_id——
|
|
56
|
+
// 同一聊天类型、时间戳在窗口内才有效;任何不对齐都返回 undefined(回落真主动)。
|
|
57
|
+
export function selectRideMsgId(
|
|
58
|
+
last: MessageContext | undefined,
|
|
59
|
+
ctx: MessageContext,
|
|
60
|
+
now: number,
|
|
61
|
+
windowMs: number,
|
|
62
|
+
): string | undefined {
|
|
63
|
+
if (!last?.msgId) return undefined
|
|
64
|
+
if (last.type !== ctx.type) return undefined
|
|
65
|
+
const ts = Number(last.timestamp ?? 0)
|
|
66
|
+
if (!Number.isFinite(ts) || ts <= 0) return undefined
|
|
67
|
+
if (now - ts > windowMs) return undefined
|
|
68
|
+
return last.msgId
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface Delivery {
|
|
72
|
+
enqueuePush: (userId: string, line: string) => void
|
|
73
|
+
deliver: (ctx: MessageContext, text: string) => Promise<void>
|
|
74
|
+
safeDeliver: (ctx: MessageContext, text: string) => Promise<void>
|
|
75
|
+
sendReply: (ctx: MessageContext, text: string) => Promise<void>
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 投递域门面。lastCtx 为跨域共享状态(bridge 拥有写权),本域只读——
|
|
79
|
+
// 用于推送/批量行的被动窗口内降级判断与主动通道选择。
|
|
80
|
+
export function createDelivery(
|
|
81
|
+
config: Config,
|
|
82
|
+
lastCtx: ReadonlyMap<string, MessageContext>,
|
|
83
|
+
): Delivery {
|
|
84
|
+
const PUSH_MIN_GAP_MS = 2000 // 用户级节流:最快 2 秒一批
|
|
85
|
+
const PUSH_MAX_LINES = 6 // 队列上限:洪峰丢最旧,防积压
|
|
86
|
+
// 债务D4(2026-10-13 官方文档查证):主动消息频控 = 单关系 1000 条/天 + 20/qpm,
|
|
87
|
+
// Bot 维度认证 10/qps(超限报 40034100)。原自设 15/天过度保守 → 默认 100 留
|
|
88
|
+
// 余量,可用 env QQ_ACTIVE_DAILY_LIMIT 覆盖。
|
|
89
|
+
const ACTIVE_DAILY_LIMIT = Number(process.env.QQ_ACTIVE_DAILY_LIMIT ?? 100)
|
|
90
|
+
|
|
91
|
+
// B-msgid(2026-10-29,吸收 dsh transport/msgid-cache):主动降级前尝试让发送
|
|
92
|
+
// "骑"该用户最近的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额)。
|
|
93
|
+
// 窗口口径保守取 5 分钟(社区亦有 60 分钟说法;骑失败无副作用自动回落真主动,
|
|
94
|
+
// 故从保守值起步,可用 QQ_PASSIVE_RIDE_WINDOW_MS 调整)。
|
|
95
|
+
const RIDE_WINDOW_MS = (() => {
|
|
96
|
+
const n = Number(process.env.QQ_PASSIVE_RIDE_WINDOW_MS ?? "300000")
|
|
97
|
+
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 300_000
|
|
98
|
+
})()
|
|
99
|
+
|
|
100
|
+
// J-轻(2026-10-30,用户拍板固化):伪流式错峰——多片回复片间间隔(默认 300ms),
|
|
101
|
+
// 配合 B3 typing 指示,长答案逐段到达体感近打字机;0=关闭恢复一次性全发。
|
|
102
|
+
const STREAM_STAGGER_MS = (() => {
|
|
103
|
+
const n = Number(process.env.QQ_STREAM_STAGGER_MS ?? "300")
|
|
104
|
+
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 300
|
|
105
|
+
})()
|
|
106
|
+
|
|
107
|
+
const pushQueues = new Map<string, PushQueue>()
|
|
108
|
+
const activeQuota = new Map<string, { day: string; count: number; warned: boolean }>()
|
|
109
|
+
// B1(2026-10-29,吸收自 openclaw-qqbot reply-limiter):被动回复限额预判——
|
|
110
|
+
// 单 msgId 4 次/1h 窗口,耗尽/过期直接转主动,省一次注定被拒的 API 往返。
|
|
111
|
+
// 记账点在 sendReply 成功路径(统一出口,bridge 直调与 deliver 共用)。
|
|
112
|
+
const passiveLimiter = new ReplyLimiter()
|
|
113
|
+
// O5:恢复落盘配额(非当日条目由 deliver 按 day 字段自然重置)
|
|
114
|
+
for (const [uid, q] of Object.entries(loadQuotaMap())) activeQuota.set(uid, q)
|
|
115
|
+
|
|
116
|
+
function enqueuePush(userId: string, line: string): void {
|
|
117
|
+
let q = pushQueues.get(userId)
|
|
118
|
+
if (!q) {
|
|
119
|
+
q = { lastSent: 0, timer: null, lines: [] }
|
|
120
|
+
pushQueues.set(userId, q)
|
|
121
|
+
}
|
|
122
|
+
if (q.lines.length >= PUSH_MAX_LINES) q.lines.shift()
|
|
123
|
+
q.lines.push(line)
|
|
124
|
+
if (q.timer) return
|
|
125
|
+
const wait = Math.max(0, PUSH_MIN_GAP_MS - (Date.now() - q.lastSent))
|
|
126
|
+
q.timer = setTimeout(() => {
|
|
127
|
+
q!.timer = null
|
|
128
|
+
void flushPush(userId)
|
|
129
|
+
}, wait)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function flushPush(userId: string): Promise<void> {
|
|
133
|
+
const q = pushQueues.get(userId)
|
|
134
|
+
const ctx = lastCtx.get(userId)
|
|
135
|
+
if (!q || q.lines.length === 0) return
|
|
136
|
+
if (!ctx) {
|
|
137
|
+
q.lines.length = 0
|
|
138
|
+
return
|
|
139
|
+
}
|
|
140
|
+
const text = q.lines.splice(0, q.lines.length).map((l) => `· ${l}`).join("\n")
|
|
141
|
+
q.lastSent = Date.now()
|
|
142
|
+
try {
|
|
143
|
+
await deliver(ctx, text)
|
|
144
|
+
} catch (error) {
|
|
145
|
+
console.error("[bridge] 观察推送失败(被动+主动均失败,丢弃本批):", error)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 统一投递:被动回复优先(ctx.msg_id,5 分钟窗口内、无配额消耗);
|
|
150
|
+
// 窗口过期/失败降级主动消息(计日配额,超限告警一次)。
|
|
151
|
+
// 观察推送与最终回复共用——超长回合(>被动窗口)的答案靠它送达
|
|
152
|
+
//(2026-10-13 实测教训:回合 >5 分钟时旧路径答案永久丢失)。
|
|
153
|
+
async function deliver(ctx: MessageContext, text: string): Promise<void> {
|
|
154
|
+
// B1:被动尝试前预判额度,耗尽/过期直接走主动(避免注定被拒的被动请求)
|
|
155
|
+
const passive = ctx.msgId ? passiveLimiter.checkLimit(ctx.msgId) : null
|
|
156
|
+
if (passive?.shouldFallbackToProactive) {
|
|
157
|
+
console.log(
|
|
158
|
+
`[bridge] 被动回复${passive.fallbackReason === "expired" ? "窗口已过期" : "次数已耗尽"},直接走主动通道: msgId=${ctx.msgId}`,
|
|
159
|
+
)
|
|
160
|
+
} else {
|
|
161
|
+
try {
|
|
162
|
+
await sendReply(ctx, text)
|
|
163
|
+
return
|
|
164
|
+
} catch (error) {
|
|
165
|
+
console.warn(
|
|
166
|
+
"[bridge] 被动回复失败(可能超 5 分钟窗口),降级主动消息:",
|
|
167
|
+
error instanceof Error ? error.message : error,
|
|
168
|
+
)
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// B-msgid(吸收 dsh msgid-cache,2026-10-29):主动降级前尝试"骑"该用户最近
|
|
173
|
+
// 的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额、记 B1 账本);
|
|
174
|
+
// 骑失败无副作用,回落下方真主动流程。
|
|
175
|
+
const rideMsgId = selectRideMsgId(lastCtx.get(ctx.userId), ctx, Date.now(), RIDE_WINDOW_MS)
|
|
176
|
+
if (rideMsgId) {
|
|
177
|
+
try {
|
|
178
|
+
const rideIds = await sendActive(ctx, text, rideMsgId)
|
|
179
|
+
passiveLimiter.record(rideMsgId)
|
|
180
|
+
for (const id of rideIds) recordMessage(scopeKeyOf(ctx), id, text)
|
|
181
|
+
console.log(`[bridge] 主动降级已骑被动窗口 msgId=${rideMsgId},省一次主动配额`)
|
|
182
|
+
return
|
|
183
|
+
} catch {
|
|
184
|
+
console.log("[bridge] 骑被动窗口失败(窗口可能已过),回落真主动消息")
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const today = new Date().toISOString().slice(0, 10)
|
|
189
|
+
let q = activeQuota.get(ctx.userId)
|
|
190
|
+
if (!q || q.day !== today) {
|
|
191
|
+
q = { day: today, count: 0, warned: false }
|
|
192
|
+
activeQuota.set(ctx.userId, q)
|
|
193
|
+
}
|
|
194
|
+
if (q.count >= ACTIVE_DAILY_LIMIT) {
|
|
195
|
+
if (!q.warned) {
|
|
196
|
+
q.warned = true
|
|
197
|
+
saveQuotaMap(activeQuota) // O5:告警态也落盘
|
|
198
|
+
console.warn(`[bridge] 用户 ${ctx.userId} 今日主动推送配额用尽,窗口外消息无法送达`)
|
|
199
|
+
try {
|
|
200
|
+
await sendActive(ctx, "⚠️ 今日主动推送配额已用尽(QQ 限制),窗口外消息明日恢复送达")
|
|
201
|
+
} catch {
|
|
202
|
+
// 告警也发不出去就静默
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
throw new Error("主动消息配额已用尽,本条无法送达")
|
|
206
|
+
}
|
|
207
|
+
const activeIds = await sendActive(ctx, text)
|
|
208
|
+
for (const id of activeIds) recordMessage(scopeKeyOf(ctx), id, text)
|
|
209
|
+
q.count++
|
|
210
|
+
saveQuotaMap(activeQuota) // O5:计数落盘,跨重启不归零
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function safeDeliver(c: MessageContext, text: string): Promise<void> {
|
|
214
|
+
try {
|
|
215
|
+
await deliver(c, text)
|
|
216
|
+
} catch (error) {
|
|
217
|
+
console.error("[bridge] 消息无法送达(被动+主动均失败):", error)
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// 主动消息(不带 msg_id):markdown 优先,失败回退纯文本。
|
|
222
|
+
// passiveMsgId(B-msgid 2026-10-29):"骑"被动窗口时传入,平台接受则按被动计。
|
|
223
|
+
// 返回服务端回执消息 id 列表(引用解析缓存登记用)。
|
|
224
|
+
async function sendActive(ctx: MessageContext, text: string, passiveMsgId?: string): Promise<string[]> {
|
|
225
|
+
const token = await getAccessToken(config.qq.appId, config.qq.clientSecret)
|
|
226
|
+
const seq = getNextMsgSeq(passiveMsgId ?? "")
|
|
227
|
+
const isGroup = ctx.type === "group" && ctx.groupId
|
|
228
|
+
try {
|
|
229
|
+
if (isGroup) {
|
|
230
|
+
const r = await sendGroupMessage(token, ctx.groupId!, text, passiveMsgId, seq, true)
|
|
231
|
+
return r?.id ? [r.id] : []
|
|
232
|
+
}
|
|
233
|
+
const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, true)
|
|
234
|
+
return r?.id ? [r.id] : []
|
|
235
|
+
} catch (error) {
|
|
236
|
+
console.error("[bridge] 主动 markdown 发送失败,回退纯文本:", error)
|
|
237
|
+
}
|
|
238
|
+
if (isGroup) {
|
|
239
|
+
const r = await sendGroupMessage(token, ctx.groupId!, text, passiveMsgId, seq, false)
|
|
240
|
+
return r?.id ? [r.id] : []
|
|
241
|
+
}
|
|
242
|
+
const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, false)
|
|
243
|
+
return r?.id ? [r.id] : []
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function sendReply(ctx: MessageContext, text: string): Promise<void> {
|
|
247
|
+
const accessToken = await getAccessToken(config.qq.appId, config.qq.clientSecret)
|
|
248
|
+
// J-轻:伪流式错峰(多片时隔 300ms 逐段到达);replyToQQ 返回片数与服务端消息 id
|
|
249
|
+
const result = await replyToQQ(accessToken, ctx, text, config.maxReplyLength, {
|
|
250
|
+
staggerMs: STREAM_STAGGER_MS,
|
|
251
|
+
})
|
|
252
|
+
// B1:被动回复成功才记额度(失败不计,避免虚耗);按片记账——平台限额按"条"计,
|
|
253
|
+
// 多片回复此前少计 N-1(J-轻顺手修正);bridge 直调与 deliver 共用此出口
|
|
254
|
+
if (ctx.msgId) {
|
|
255
|
+
for (let i = 0; i < result.chunks; i++) passiveLimiter.record(ctx.msgId)
|
|
256
|
+
}
|
|
257
|
+
// 缺口 1:我方出站回复登记进上下文缓存(引用解析可命中 AI 答案)
|
|
258
|
+
const scope = scopeKeyOf(ctx)
|
|
259
|
+
for (const id of result.ids) recordMessage(scope, id, text)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return { enqueuePush, deliver, safeDeliver, sendReply }
|
|
263
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// HC1(2026-10-26):opencode 服务端口漂移自动发现。
|
|
2
|
+
// 背景:桌面端 2.1.3 后台服务 = opencode-cli.exe serve --service,端口动态分配
|
|
3
|
+
//(实证 49374→28894;服务重建/系统重启后可能再变,且无持久化发现文件)。
|
|
4
|
+
// bot 配置的 OPENCODE_BASE_URL 失联(ECONNREFUSED)时,扫描本机 TCP 监听口
|
|
5
|
+
// 并逐口探测 /api/info 签名:
|
|
6
|
+
// {"version":"2.1.3","pid":44152,"urls":["http://127.0.0.1:28894"],"paths":{...}}
|
|
7
|
+
// 签名要求 version 字符串 + urls 数组 + paths 对象三层同构,随机端口误报概率≈0。
|
|
8
|
+
// 仅匹配 `${port}/api/info`:bot 的 V2 端点契约即 base=.../api(见 client.ts),
|
|
9
|
+
// 无 /api 前缀的形态与本契约不符,不采用。
|
|
10
|
+
// @input: 127.0.0.1 监听口(netstat -ano -p tcp)、/api/info 端点
|
|
11
|
+
// @output: discoverOpencode, probeOpencodeEndpoint, parseListenPorts, isOpencodeInfo, persistDiscovery
|
|
12
|
+
// @pos: core - 端口发现(HC1,Windows only)
|
|
13
|
+
import { exec } from "node:child_process"
|
|
14
|
+
import { promisify } from "node:util"
|
|
15
|
+
import { mkdirSync, writeFileSync } from "fs"
|
|
16
|
+
import { join } from "path"
|
|
17
|
+
import { homedir } from "os"
|
|
18
|
+
|
|
19
|
+
const execAsync = promisify(exec)
|
|
20
|
+
|
|
21
|
+
export interface OpencodeDiscovery {
|
|
22
|
+
baseUrl: string
|
|
23
|
+
port: number
|
|
24
|
+
version: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type InfoPayload = { version?: unknown; urls?: unknown; paths?: unknown }
|
|
28
|
+
|
|
29
|
+
// /api/info 签名校验:version(string) + urls(非空数组) + paths(对象) 三层同构。
|
|
30
|
+
export function isOpencodeInfo(body: unknown): boolean {
|
|
31
|
+
if (body === null || typeof body !== "object") return false
|
|
32
|
+
const b = body as InfoPayload
|
|
33
|
+
return (
|
|
34
|
+
typeof b.version === "string" &&
|
|
35
|
+
b.version.length > 0 &&
|
|
36
|
+
Array.isArray(b.urls) &&
|
|
37
|
+
b.urls.length > 0 &&
|
|
38
|
+
b.paths !== null &&
|
|
39
|
+
typeof b.paths === "object"
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// netstat/ss 输出 → 本机监听口列表(去重,保持首次出现序)。
|
|
44
|
+
// 跨平台兼容三形态(QQ 官方插件纯 TS 零 OS 分支为参照——我们也要不挑系统):
|
|
45
|
+
// Windows: TCP 127.0.0.1:28894 0.0.0.0:0 LISTENING 44152
|
|
46
|
+
// Linux ss: LISTEN 0 128 127.0.0.1:28894 0.0.0.0:*
|
|
47
|
+
// macOS: tcp4 0 0 127.0.0.1.28894 *.* LISTEN(注意 macOS 是点分隔)
|
|
48
|
+
// 规则:LISTEN(ING) 行内,取含 : 或 . 分隔的地址列,末段数字即端口;
|
|
49
|
+
// 裸 IP 末段可能误当端口(如 127.0.0.1 → 1),无害——探测时签名不符即跳过。
|
|
50
|
+
export function parseListenPorts(output: string): number[] {
|
|
51
|
+
const ports = new Set<number>()
|
|
52
|
+
for (const raw of output.split(/\r?\n/)) {
|
|
53
|
+
const line = raw.trim()
|
|
54
|
+
if (!/\bLISTEN(?:ING)?\b/i.test(line)) continue
|
|
55
|
+
for (const col of line.split(/\s+/)) {
|
|
56
|
+
const m = /^[\w.[\]:%*]*[:.](\d+)$/.exec(col)
|
|
57
|
+
if (!m) continue
|
|
58
|
+
const port = Number(m[1])
|
|
59
|
+
if (Number.isInteger(port) && port > 0 && port < 65536) ports.add(port)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return [...ports]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// 跨平台监听口枚举:Windows=netstat -ano -p tcp;Linux=ss -tln(兜底 netstat -tln);
|
|
66
|
+
// macOS=netstat -an -p tcp(兜底 ss)。命令失败→换备选→全灭则记日志返回空。
|
|
67
|
+
async function listListenPorts(): Promise<number[]> {
|
|
68
|
+
const platform = process.platform
|
|
69
|
+
const candidates: string[] =
|
|
70
|
+
platform === "win32"
|
|
71
|
+
? ["netstat -ano -p tcp"]
|
|
72
|
+
: platform === "darwin"
|
|
73
|
+
? ["netstat -an -p tcp", "ss -tln"]
|
|
74
|
+
: ["ss -tln", "netstat -tln"]
|
|
75
|
+
for (const cmd of candidates) {
|
|
76
|
+
try {
|
|
77
|
+
const { stdout } = await execAsync(cmd, { maxBuffer: 10 * 1024 * 1024, timeout: 10_000 })
|
|
78
|
+
const ports = parseListenPorts(stdout)
|
|
79
|
+
if (ports.length > 0) return ports
|
|
80
|
+
} catch (error) {
|
|
81
|
+
console.log(`[discovery] ${cmd.split(" ")[0]} 不可用: ${error instanceof Error ? error.message : error}`)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
console.log("[discovery] 监听口枚举工具全部不可用,跳过端口扫描")
|
|
85
|
+
return []
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// 探测单个 /api/info URL;命中签名返回版本号,否则 null
|
|
89
|
+
//(连接拒/超时/404/非 JSON/签名不符同归 null,永不抛出)。
|
|
90
|
+
export async function probeOpencodeEndpoint(
|
|
91
|
+
url: string,
|
|
92
|
+
opts?: { password?: string; timeoutMs?: number },
|
|
93
|
+
): Promise<string | null> {
|
|
94
|
+
const ac = new AbortController()
|
|
95
|
+
const timer = setTimeout(() => ac.abort(), opts?.timeoutMs ?? 900)
|
|
96
|
+
try {
|
|
97
|
+
const headers: Record<string, string> = {}
|
|
98
|
+
if (opts?.password) {
|
|
99
|
+
headers.Authorization = `Basic ${Buffer.from(`opencode:${opts.password}`).toString("base64")}`
|
|
100
|
+
}
|
|
101
|
+
const res = await fetch(url, { headers, signal: ac.signal, redirect: "manual" })
|
|
102
|
+
if (!res.ok) return null
|
|
103
|
+
const body: unknown = JSON.parse(await res.text())
|
|
104
|
+
if (!isOpencodeInfo(body)) return null
|
|
105
|
+
return (body as InfoPayload).version as string
|
|
106
|
+
} catch {
|
|
107
|
+
return null
|
|
108
|
+
} finally {
|
|
109
|
+
clearTimeout(timer)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// 端口发现主流程:默认 netstat 自动列口;测试可注入 ports 跳过扫描。
|
|
114
|
+
// 建议调用方在外层包 try/catch——本函数不向上抛(内部兜底日志)。
|
|
115
|
+
export async function discoverOpencode(opts?: {
|
|
116
|
+
password?: string
|
|
117
|
+
timeoutMs?: number
|
|
118
|
+
ports?: number[]
|
|
119
|
+
}): Promise<OpencodeDiscovery | null> {
|
|
120
|
+
const ports = opts?.ports ?? (await listListenPorts())
|
|
121
|
+
if (ports.length === 0) return null
|
|
122
|
+
const started = Date.now()
|
|
123
|
+
let probed = 0
|
|
124
|
+
for (const port of ports) {
|
|
125
|
+
probed++
|
|
126
|
+
const version = await probeOpencodeEndpoint(`http://127.0.0.1:${port}/api/info`, opts)
|
|
127
|
+
if (version !== null) {
|
|
128
|
+
const hit: OpencodeDiscovery = { baseUrl: `http://127.0.0.1:${port}/api`, port, version }
|
|
129
|
+
console.log(
|
|
130
|
+
`[discovery] 命中 opencode 服务:${hit.baseUrl}(v${hit.version},第 ${probed}/${ports.length} 口,${Date.now() - started}ms)`,
|
|
131
|
+
)
|
|
132
|
+
return hit
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
console.log(`[discovery] 扫描 ${ports.length} 个监听口(${Date.now() - started}ms),无签名命中`)
|
|
136
|
+
return null
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// 发现结果落盘 ~/.openqq/last-discovered.json,供看门狗/排障查看。不写 .env。
|
|
140
|
+
export function persistDiscovery(d: OpencodeDiscovery): void {
|
|
141
|
+
try {
|
|
142
|
+
const dir = join(homedir(), ".openqq")
|
|
143
|
+
mkdirSync(dir, { recursive: true })
|
|
144
|
+
writeFileSync(
|
|
145
|
+
join(dir, "last-discovered.json"),
|
|
146
|
+
JSON.stringify({ ...d, at: new Date().toISOString() }, null, 2),
|
|
147
|
+
)
|
|
148
|
+
} catch (error) {
|
|
149
|
+
console.log(`[discovery] 发现结果落盘失败: ${error instanceof Error ? error.message : error}`)
|
|
150
|
+
}
|
|
151
|
+
}
|