@linjz/opencode-qqbot 0.3.16 → 0.3.18
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 +316 -266
- package/README.zh-CN.md +326 -0
- package/dist/notify-cli.js +64 -12
- package/dist/opencode-qqbot-plugin.js +591 -92
- package/dist/openqq-bot.js +1172 -303
- package/dist/openqq-cli.js +253 -64
- package/dist/openqq-watchdog.js +373 -110
- package/package.json +4 -3
- package/src/bridge.ts +448 -32
- package/src/cli/notify.ts +4 -1
- package/src/cli/watchdog-main.ts +22 -7
- package/src/commands.ts +74 -58
- package/src/config.ts +39 -5
- package/src/core/bot-config.ts +66 -0
- package/src/core/bot-control.ts +21 -3
- package/src/core/bot-launcher.ts +4 -2
- package/src/core/cron-reminders.ts +84 -0
- package/src/core/delivery.ts +24 -1
- package/src/core/discovery.ts +207 -169
- package/src/core/error-rescue.ts +1 -1
- package/src/core/file-log.ts +16 -7
- package/src/core/inflight-journal.ts +1 -0
- package/src/core/instance-lock.ts +32 -1
- package/src/core/log-rotate.ts +91 -0
- package/src/core/mirror.ts +13 -4
- package/src/core/notices.ts +62 -0
- package/src/core/outbound-sanitize.ts +29 -0
- package/src/core/permission.ts +16 -0
- package/src/core/qq-instructions.ts +122 -0
- package/src/core/queue-view.ts +1 -0
- package/src/core/send-media.ts +29 -2
- package/src/core/send-requests.ts +227 -0
- package/src/core/start-error.ts +26 -0
- package/src/core/stt.ts +55 -0
- package/src/core/supervisor-election.ts +53 -0
- package/src/core/turn-correction.ts +68 -0
- package/src/core/watchdog.ts +171 -14
- package/src/index.ts +262 -250
- package/src/opencode/client.ts +32 -1
- package/src/opencode/mirror.ts +17 -4
- package/src/opencode/sessions.ts +20 -1
- package/src/plugin-entry.ts +67 -2
- package/src/qq/gateway.ts +35 -0
- package/src/qq/media.ts +21 -0
- package/src/qq/sender.ts +50 -1
package/src/opencode/mirror.ts
CHANGED
|
@@ -51,19 +51,32 @@ export function digestTurnKey(messages: SessionMessage[]): string | null {
|
|
|
51
51
|
}
|
|
52
52
|
|
|
53
53
|
// 构建最近一轮问答的摘要卡;返回 null = 无可镜像正文。
|
|
54
|
-
export function buildDigest(messages: SessionMessage[]): string | null {
|
|
54
|
+
export function buildDigest(messages: SessionMessage[], goalObjective?: string): string | null {
|
|
55
55
|
const ordered = [...messages].reverse()
|
|
56
56
|
|
|
57
|
+
// A 方案第三桶(owner 2026-11-23):回合边界消息 type=synthetic = 引擎自主注入
|
|
58
|
+
// (goal 续跑/自动化)——既非 QQ 派发也非桌面输入,实证 shape(11-23 goal 会话
|
|
59
|
+
// 消息流):continuation 为 synthetic 型 user 消息。此类回合标「🎯 目标续跑摘要」。
|
|
60
|
+
// kickoff 轮(引擎不打标):边界 user 文本==goal 设定原文时同标(bot 侧标记近似)。
|
|
57
61
|
let lastUserIdx = -1
|
|
62
|
+
let goalDriven = false
|
|
58
63
|
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
59
|
-
|
|
64
|
+
const t = (ordered[i] as { type?: string }).type
|
|
65
|
+
if (t === "user" || t === "synthetic") {
|
|
60
66
|
lastUserIdx = i
|
|
67
|
+
goalDriven = t === "synthetic"
|
|
61
68
|
break
|
|
62
69
|
}
|
|
63
70
|
}
|
|
64
71
|
if (lastUserIdx < 0) return null
|
|
65
72
|
|
|
66
|
-
const
|
|
73
|
+
const boundaryMsg = ordered[lastUserIdx] as { text?: string; content?: Array<{ type?: string; text?: string }> }
|
|
74
|
+
const userText = goalDriven
|
|
75
|
+
? ""
|
|
76
|
+
: ((boundaryMsg.text ?? (boundaryMsg.content ?? []).filter((p) => p.type === "text").map((p) => p.text ?? "").join("")) ?? "").trim()
|
|
77
|
+
if (!goalDriven && goalObjective && userText && userText === goalObjective.trim()) {
|
|
78
|
+
goalDriven = true
|
|
79
|
+
}
|
|
67
80
|
|
|
68
81
|
let answer = ""
|
|
69
82
|
for (let i = ordered.length - 1; i > lastUserIdx; i--) {
|
|
@@ -77,7 +90,7 @@ export function buildDigest(messages: SessionMessage[]): string | null {
|
|
|
77
90
|
}
|
|
78
91
|
if (!answer) return null
|
|
79
92
|
|
|
80
|
-
const lines = ["📋 桌面问答摘要"]
|
|
93
|
+
const lines = [goalDriven ? "🎯 目标续跑摘要" : "📋 桌面问答摘要"]
|
|
81
94
|
if (userText) lines.push(`🧑 ${clip(userText, USER_CLIP)}`)
|
|
82
95
|
const clipLimit = answerClipLimit()
|
|
83
96
|
if (clipLimit > 0) {
|
package/src/opencode/sessions.ts
CHANGED
|
@@ -40,8 +40,14 @@ export class SessionManager {
|
|
|
40
40
|
// 手工编辑或 PowerShell Out-File 常带 BOM,JSON.parse 会炸——先剥掉
|
|
41
41
|
const raw = readFileSync(this.storeFile, "utf8").replace(/^\uFEFF/, "")
|
|
42
42
|
const parsed = JSON.parse(raw) as Record<string, UserSession>
|
|
43
|
+
let dropped = 0
|
|
43
44
|
for (const [userId, session] of Object.entries(parsed)) {
|
|
44
|
-
|
|
45
|
+
// DEF-qqbot-20261123-1 R3:加载即校验 sessionId 形态,手工改坏/测试夹具在加载层拦截
|
|
46
|
+
if (session?.sessionId && /^ses_/.test(session.sessionId)) this.sessions.set(userId, session)
|
|
47
|
+
else dropped++
|
|
48
|
+
}
|
|
49
|
+
if (dropped > 0) {
|
|
50
|
+
console.warn(`[sessions] 加载时丢弃 ${dropped} 条非法映射(sessionId 形态不合法,不做整图回写保留)`)
|
|
45
51
|
}
|
|
46
52
|
if (this.sessions.size > 0) {
|
|
47
53
|
console.log(`[sessions] 已从磁盘恢复 ${this.sessions.size} 个用户会话映射`)
|
|
@@ -217,6 +223,19 @@ export class SessionManager {
|
|
|
217
223
|
return [...this.sessions.entries()].map(([userId, s]) => ({ userId, sessionId: s.sessionId, directory: s.directory }))
|
|
218
224
|
}
|
|
219
225
|
|
|
226
|
+
/**
|
|
227
|
+
* 驱逐失效映射(DEF-qqbot-20261123-1 R2):轮询侧 400/404 累计 3 次判死后调用——
|
|
228
|
+
* 幽灵/失效绑定不驱逐则永久驻留并被 12s 轮询放大为无效请求风暴。返回是否真删了条目。
|
|
229
|
+
*/
|
|
230
|
+
evict(userId: string): boolean {
|
|
231
|
+
const had = this.sessions.delete(userId)
|
|
232
|
+
if (had) {
|
|
233
|
+
this.saveSessions()
|
|
234
|
+
console.log(`[sessions] 驱逐失效映射 userId=${userId.slice(0, 8)}…(400/404 三连判死)`)
|
|
235
|
+
}
|
|
236
|
+
return had
|
|
237
|
+
}
|
|
238
|
+
|
|
220
239
|
// v2: 模型/agent 是 session 级(/prompt body 会被剥离),必须调 session 端点。
|
|
221
240
|
// 先服务端成功再落本地,避免 /model 显示成功但实际没生效。
|
|
222
241
|
async setModel(userId: string, providerId: string, modelId: string): Promise<void> {
|
package/src/plugin-entry.ts
CHANGED
|
@@ -12,10 +12,13 @@ import { join } from "path"
|
|
|
12
12
|
import { homedir } from "os"
|
|
13
13
|
import { appendFileSync, existsSync, renameSync, statSync } from "fs"
|
|
14
14
|
import { fileURLToPath } from "url"
|
|
15
|
-
import { botWatchdogPaths, superviseOnce } from "./core/watchdog.js"
|
|
15
|
+
import { botWatchdogPaths, superviseOnce, appendWatchdogLog } from "./core/watchdog.js"
|
|
16
16
|
import { startBot } from "./core/bot-control.js"
|
|
17
17
|
import { runNotifyCli } from "./cli/notify.js"
|
|
18
18
|
import { readDotEnvField } from "./core/bot-launcher.js"
|
|
19
|
+
import { electSupervisor } from "./core/supervisor-election.js"
|
|
20
|
+
import { executeQQSendFile } from "./core/send-requests.js"
|
|
21
|
+
import { syncQQInstructions } from "./core/qq-instructions.js"
|
|
19
22
|
|
|
20
23
|
const ENV_FILE = join(homedir(), ".openqq", ".env")
|
|
21
24
|
const CHECK_INTERVAL_MS = (() => {
|
|
@@ -54,7 +57,19 @@ export default Plugin.define({
|
|
|
54
57
|
}
|
|
55
58
|
const ensure = (): void => {
|
|
56
59
|
try {
|
|
57
|
-
|
|
60
|
+
// 2026-11-20 应修尽修批:legacy 字段缺省时回退 QQ_BOTS 首角色(纯多角色部署)
|
|
61
|
+
const botsRaw = readDotEnvField(ENV_FILE, "QQ_BOTS")
|
|
62
|
+
let botsFirst: string | null = null
|
|
63
|
+
if (botsRaw) {
|
|
64
|
+
try {
|
|
65
|
+
const arr = JSON.parse(botsRaw) as Array<{ appId?: unknown }>
|
|
66
|
+
const first = Array.isArray(arr) ? arr[0]?.appId : undefined
|
|
67
|
+
if (typeof first === "string" && first) botsFirst = first
|
|
68
|
+
} catch {
|
|
69
|
+
/* 坏 JSON 视为无 */
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const appId = readDotEnvField(ENV_FILE, "QQ_APP_ID") ?? botsFirst
|
|
58
73
|
if (!appId) {
|
|
59
74
|
warnOnce(
|
|
60
75
|
"cred",
|
|
@@ -62,6 +77,15 @@ export default Plugin.define({
|
|
|
62
77
|
)
|
|
63
78
|
return
|
|
64
79
|
}
|
|
80
|
+
// QQ 系统级指令同步(2026-11-24 owner 批准):entry 优先/hook 降级,状态文件驱动
|
|
81
|
+
// bridge 停用 prompt 正文注入——与 supervisor 租约无关,任何存活实例都可幂等同步。
|
|
82
|
+
void syncQQInstructions(_ctx as never).catch((error) => {
|
|
83
|
+
console.warn("[opencode-qqbot] QQ 系统指令同步失败(下周期重试):", error instanceof Error ? error.message : error)
|
|
84
|
+
})
|
|
85
|
+
// 双触发器归一(2026-11-20 owner 批):service(计划任务看门狗)与 plugin
|
|
86
|
+
// (本引导器巡检)租约选主——service 持租约时整轮让贤,连 superviseOnce
|
|
87
|
+
// 都不进(零干扰);service 停排/死亡后租约过期自动接管,双向自愈。
|
|
88
|
+
if (!electSupervisor("plugin")) return
|
|
65
89
|
// 2026-11-09 重构:巡检升级为 superviseOnce(与计划任务同一监督矩阵 + 认领互斥):
|
|
66
90
|
// 优雅杀/冷却/重启强度超限 give-up 并告警,杜绝裸「杀旧拉新」循环。
|
|
67
91
|
void superviseOnce({
|
|
@@ -80,6 +104,8 @@ export default Plugin.define({
|
|
|
80
104
|
if (result.action === "ok" || result.action === "restart") lastBlocker = null
|
|
81
105
|
})
|
|
82
106
|
.catch((error) => {
|
|
107
|
+
// 2026-11-20 修:静默消除——巡检失败只进引擎 console 曾造成 6 分钟无人拉活空窗无人知
|
|
108
|
+
appendWatchdogLog(`[plugin] 巡检失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
83
109
|
console.error("[opencode-qqbot] 巡检失败:", error instanceof Error ? error.message : error)
|
|
84
110
|
})
|
|
85
111
|
} catch (error) {
|
|
@@ -90,6 +116,45 @@ export default Plugin.define({
|
|
|
90
116
|
ensure()
|
|
91
117
|
const timer = setInterval(ensure, CHECK_INTERVAL_MS)
|
|
92
118
|
|
|
119
|
+
// qq_send_file 工具注册(2026-11-23 owner 批准):AI 出站发文件从「QQ_SEND_FILE 魔法标记」
|
|
120
|
+
// 升级为一等工具——模型在工具清单读到 schema 与精确错误,不再猜标记/猜路径。
|
|
121
|
+
// 传输=文件队列(core/send-requests),bot 进程消费并回执;权威白名单校验在 bot 侧。
|
|
122
|
+
// 特性探测:旧引擎无 ctx.tool.transform 时静默降级(标记通道仍可用),不阻断宿主。
|
|
123
|
+
const toolApi = (_ctx as unknown as {
|
|
124
|
+
tool?: {
|
|
125
|
+
transform?: (cb: (editor: {
|
|
126
|
+
namespace?: (ns: { name: string; description: string }) => void
|
|
127
|
+
add: (def: {
|
|
128
|
+
name: string
|
|
129
|
+
description: string
|
|
130
|
+
input: Record<string, unknown>
|
|
131
|
+
options?: Record<string, unknown>
|
|
132
|
+
execute: (input: { path: string; caption?: string }, context: { sessionID: string; signal?: AbortSignal }) => Promise<{ content: string }>
|
|
133
|
+
}) => void
|
|
134
|
+
}) => void) => Promise<unknown>
|
|
135
|
+
}
|
|
136
|
+
}).tool
|
|
137
|
+
if (toolApi?.transform) {
|
|
138
|
+
void toolApi.transform((editor) => {
|
|
139
|
+
editor.namespace?.({ name: "qq", description: "QQ 消息通道工具(发送到当前会话绑定的 QQ 用户)" })
|
|
140
|
+
editor.add({
|
|
141
|
+
name: "send_file",
|
|
142
|
+
description:
|
|
143
|
+
"把本机文件/图片发送到当前会话绑定的 QQ 用户。path=本机绝对路径(须在发送白名单内,默认 QQ 图片缓存目录与 bot 工作目录,QQ_SEND_EXTRA_ROOTS 可扩)。失败返回精确原因(含白名单根目录/拒识类型),修正后可重试;相同文件重复调用自动去重。",
|
|
144
|
+
input: {
|
|
145
|
+
type: "object",
|
|
146
|
+
properties: { path: { type: "string" }, caption: { type: "string" } },
|
|
147
|
+
required: ["path"],
|
|
148
|
+
additionalProperties: false,
|
|
149
|
+
},
|
|
150
|
+
options: { namespace: "qq", codemode: true },
|
|
151
|
+
execute: async (input, context) => ({ content: await executeQQSendFile(input, context) }),
|
|
152
|
+
})
|
|
153
|
+
}).catch((error) => {
|
|
154
|
+
console.warn("[opencode-qqbot] qq_send_file 注册失败(降级为 QQ_SEND_FILE 标记通道):", error)
|
|
155
|
+
})
|
|
156
|
+
}
|
|
157
|
+
|
|
93
158
|
// 事件探针(可选,默认关):QQ_EVENT_PROBE=true 时订阅全量事件流落盘
|
|
94
159
|
let probeAbort: AbortController | null = null
|
|
95
160
|
if (readDotEnvField(ENV_FILE, "QQ_EVENT_PROBE") === "true") {
|
package/src/qq/gateway.ts
CHANGED
|
@@ -46,6 +46,8 @@ interface GatewayState {
|
|
|
46
46
|
stopped: boolean
|
|
47
47
|
connecting: boolean
|
|
48
48
|
reconnectAttempt: number
|
|
49
|
+
/** AB:快断连时刻戳窗(风暴守卫计数) */
|
|
50
|
+
quickCloses: number[]
|
|
49
51
|
reconnectTimer: ReturnType<typeof setTimeout> | null
|
|
50
52
|
heartbeatTimer: ReturnType<typeof setInterval> | null
|
|
51
53
|
accessToken: string | null
|
|
@@ -68,6 +70,7 @@ function createInitialState(stateFile: string): GatewayState {
|
|
|
68
70
|
stopped: false,
|
|
69
71
|
connecting: false,
|
|
70
72
|
reconnectAttempt: 0,
|
|
73
|
+
quickCloses: [],
|
|
71
74
|
reconnectTimer: null,
|
|
72
75
|
heartbeatTimer: null,
|
|
73
76
|
accessToken: null,
|
|
@@ -141,6 +144,26 @@ function scheduleReconnect(state: GatewayState, connect: () => Promise<void>, cu
|
|
|
141
144
|
}, delayMs)
|
|
142
145
|
}
|
|
143
146
|
|
|
147
|
+
// —— AB:快断连风暴守卫(2026-11-23 学习吸收,源=hermes-agent adapter.py P0 邻接)——
|
|
148
|
+
// 背景:指数退避(1s→30s)只放缓单个重连,挡不住「坏凭据/网络抖动」的无限循环——
|
|
149
|
+
// bot 会在 1~30s 档永远空转且日志无声。守卫口径:窗口内快断连(建连后秒挂)累计
|
|
150
|
+
// 达上限 → 升级 5min 静默冷却 + 高声错误日志(排障信号),冷却后再犯重新累计。
|
|
151
|
+
|
|
152
|
+
/** 快断连判定与升级(纯函数供测试):closes=各次断连时刻戳(epoch ms)。
|
|
153
|
+
* 返回 true=本次应升级长冷却(调用方负责清窗)。窗口默认 60s、上限默认 5 次。 */
|
|
154
|
+
export function shouldEscalateReconnect(
|
|
155
|
+
closes: number[],
|
|
156
|
+
now: number,
|
|
157
|
+
windowMs: number = 60_000,
|
|
158
|
+
maxQuick: number = 5,
|
|
159
|
+
): boolean {
|
|
160
|
+
while (closes.length > 0 && now - closes[0] > windowMs) closes.shift()
|
|
161
|
+
return closes.length >= maxQuick
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 升级冷却时长(常量;5min 足以让平台侧限流/凭据修复/网络恢复生效) */
|
|
165
|
+
const STORM_COOLDOWN_MS = 5 * 60_000
|
|
166
|
+
|
|
144
167
|
function startHeartbeat(state: GatewayState, intervalMs: number): void {
|
|
145
168
|
if (state.heartbeatTimer) {
|
|
146
169
|
clearInterval(state.heartbeatTimer)
|
|
@@ -581,6 +604,18 @@ export async function startGateway(options: GatewayOptions): Promise<GatewayCont
|
|
|
581
604
|
return
|
|
582
605
|
}
|
|
583
606
|
|
|
607
|
+
// AB:快断连风暴守卫——窗口内快断连累计达上限 → 升级 5min 冷却 + 高声日志。
|
|
608
|
+
// 4008(平台限流)已有专属 60s 官方长退避,不计入风暴窗(避免双重惩罚误伤)。
|
|
609
|
+
if (code !== RATE_LIMITED_CLOSE_CODE) {
|
|
610
|
+
state.quickCloses.push(Date.now())
|
|
611
|
+
if (shouldEscalateReconnect(state.quickCloses, Date.now())) {
|
|
612
|
+
state.quickCloses.length = 0
|
|
613
|
+
console.error(`[qq-gateway] 快断连风暴(60s 内 ${5} 次以上)→ 冷却 ${STORM_COOLDOWN_MS / 60000} 分钟后重试;请排查凭据/intent/网络`)
|
|
614
|
+
scheduleReconnect(state, connect, STORM_COOLDOWN_MS)
|
|
615
|
+
return
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
584
619
|
scheduleReconnect(state, connect)
|
|
585
620
|
})
|
|
586
621
|
|
package/src/qq/media.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync, readFileSy
|
|
|
13
13
|
import { join } from "node:path"
|
|
14
14
|
import { tmpdir } from "node:os"
|
|
15
15
|
import type { MessageAttachment } from "./types.js"
|
|
16
|
+
import { sttConfigured, sttTranscribe } from "../core/stt.js"
|
|
16
17
|
|
|
17
18
|
export interface PromptFile {
|
|
18
19
|
uri: string
|
|
@@ -92,6 +93,26 @@ export async function downloadQQAttachment(
|
|
|
92
93
|
if (isVoice && att.asr_refer_text?.trim()) {
|
|
93
94
|
return { voice: att.asr_refer_text.trim() }
|
|
94
95
|
}
|
|
96
|
+
// AD(2026-11-23 学习吸收):QQ 内置 ASR 无转写 → 外部 STT 回退(hermes 双级链同款)。
|
|
97
|
+
// 需 QQ_STT_BASE_URL+QQ_STT_API_KEY 齐配(QQ_STT_MODEL 默认 whisper-1);未配置保持
|
|
98
|
+
// 既有「不支持」路径零变化。音频仍走 QQ 域白名单+token 重试,10MB 上限同图片口径。
|
|
99
|
+
if (isVoice && sttConfigured()) {
|
|
100
|
+
try {
|
|
101
|
+
if (!isAllowedDownloadHost(att.url)) return { failed: "下载域不在白名单" }
|
|
102
|
+
const name = att.filename || `voice-${Date.now()}.amr`
|
|
103
|
+
let res = await fetchWithTimeout(att.url, 15000)
|
|
104
|
+
if ((res.status === 401 || res.status === 403) && getAuth) {
|
|
105
|
+
res = await fetchWithTimeout(att.url, 15000, await getAuth())
|
|
106
|
+
}
|
|
107
|
+
if (!res.ok) return { failed: "语音下载失败" }
|
|
108
|
+
const buf = new Uint8Array(await res.arrayBuffer())
|
|
109
|
+
if (buf.byteLength > MAX_IMAGE_BYTES) return { failed: "语音超过 10MB 上限" }
|
|
110
|
+
const text = await sttTranscribe(buf, name, sttConfigured() as never)
|
|
111
|
+
return { voice: text }
|
|
112
|
+
} catch {
|
|
113
|
+
return { failed: "语音转写失败(外部 STT 未响应或识别为空)" }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
95
116
|
const ext = extForImageMime(att.content_type || "")
|
|
96
117
|
if (!ext) return { unsupported: att.content_type || att.filename || "未知类型" }
|
|
97
118
|
if (!isAllowedDownloadHost(att.url)) return { failed: "下载域不在白名单" }
|
package/src/qq/sender.ts
CHANGED
|
@@ -8,11 +8,47 @@
|
|
|
8
8
|
import { sendC2CMessage, sendGroupMessage, getNextMsgSeq, type MessageResponse } from "./api.js"
|
|
9
9
|
import type { MessageContext } from "./types.js"
|
|
10
10
|
import { normalizeOutboundMarkdown, matchFence, type FenceToken } from "../core/markdown.js"
|
|
11
|
+
import { stripInteractionTags } from "../core/notices.js"
|
|
12
|
+
import { stripScaffolding } from "../core/outbound-sanitize.js"
|
|
13
|
+
|
|
14
|
+
// QQ 按 CommonMark 语义渲染:`\`+ASCII标点 被当作转义、反斜杠被吃掉
|
|
15
|
+
//(2026-11-20 /status 实证:C:\Users\linjz\.openqq 被渲染成 linjz.openqq——
|
|
16
|
+
// 路径里 `\U`、`\l` 等「反斜杠+字母」不是标点不受影响,唯独 `\.` 中招)。
|
|
17
|
+
// 围栏代码块与行内代码内 QQ 按字面渲染、不做转义——故仅对围栏外、行内代码外的
|
|
18
|
+
// 反斜杠双写(`\.` → `\\.` → QQ 渲染还原 `\.`)。
|
|
19
|
+
// ASCII 标点类即 CommonMark 转义目标:!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
|
|
20
|
+
const PUNCT_BACKSLASH = /\\(?=[!-/:-@[-`{-~])/g
|
|
21
|
+
const INLINE_CODE_SPLIT = /(`[^`]*`)/g
|
|
22
|
+
|
|
23
|
+
/** 单行内:行内代码段(单反引号对)原样保留,其余段做反斜杠双写。 */
|
|
24
|
+
function escapeLineBackslashes(line: string): string {
|
|
25
|
+
return line
|
|
26
|
+
.split(INLINE_CODE_SPLIT)
|
|
27
|
+
.map((seg, i) => (i % 2 === 1 ? seg : seg.replace(PUNCT_BACKSLASH, "\\\\")))
|
|
28
|
+
.join("")
|
|
29
|
+
}
|
|
11
30
|
|
|
12
31
|
// Markdown 主路径: QQ 原生渲染标准 markdown(含表格/代码),故基本透传,仅做首尾清理
|
|
13
32
|
// 与围栏归一(补未闭合 + 去空围栏对)——两者都会在 QQ 里变成空代码卡(2026-11-10 实证)。
|
|
14
33
|
export function formatForQQMarkdown(text: string): string {
|
|
15
|
-
|
|
34
|
+
// Z 项(2026-11-23):先消毒脚手架块(thinking/system-reminder 等),再走归一——
|
|
35
|
+
// 顺序不可换:围栏保护在归一步,消毒须在围栏占位之前执行才刮不到代码块内。
|
|
36
|
+
const sanitized = stripScaffolding(text)
|
|
37
|
+
const normalized = normalizeOutboundMarkdown(sanitized.trim())
|
|
38
|
+
// 围栏状态跟踪(normalizeOutboundMarkdown 已保证围栏配对,可安全切换):
|
|
39
|
+
// 围栏行与其内部内容逐字保留,不做反斜杠双写。
|
|
40
|
+
let inFence = false
|
|
41
|
+
return normalized
|
|
42
|
+
.split("\n")
|
|
43
|
+
.map((line) => {
|
|
44
|
+
const f = matchFence(line)
|
|
45
|
+
if (f) {
|
|
46
|
+
inFence = !inFence
|
|
47
|
+
return line
|
|
48
|
+
}
|
|
49
|
+
return inFence ? line : escapeLineBackslashes(line)
|
|
50
|
+
})
|
|
51
|
+
.join("\n")
|
|
16
52
|
}
|
|
17
53
|
|
|
18
54
|
// 纯文本兜底: 去除所有 markdown 标记(当 markdown 发送失败时使用)
|
|
@@ -46,6 +82,19 @@ export function formatForQQ(text: string): string {
|
|
|
46
82
|
processed = processed.replace(`\x00CB${i}\x00`, codeBlocks[i])
|
|
47
83
|
}
|
|
48
84
|
|
|
85
|
+
// 交互标签兜底剥离(2026-11-22 学习吸收轮):<qqbot-cmd-input> 等仅 markdown 消息生效,
|
|
86
|
+
// 纯文本通道必须把标签降级为可读文本,否则尖括号原样糊给用户(AstrBot#8755 同款坑)。
|
|
87
|
+
// 围栏内是代码字面量,不动。
|
|
88
|
+
let inStripFence = false
|
|
89
|
+
processed = processed.split("\n").map((line) => {
|
|
90
|
+
const f = matchFence(line)
|
|
91
|
+
if (f) {
|
|
92
|
+
inStripFence = !inStripFence
|
|
93
|
+
return line
|
|
94
|
+
}
|
|
95
|
+
return inStripFence ? line : stripInteractionTags(line)
|
|
96
|
+
}).join("\n")
|
|
97
|
+
|
|
49
98
|
return processed.trim()
|
|
50
99
|
}
|
|
51
100
|
|