@cmach_socket/opencode-qq-bot 0.3.4 → 0.5.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/NOTICE +63 -0
- package/README.md +170 -20
- package/package.json +20 -2
- package/src/bot-lock.ts +17 -26
- package/src/config.ts +218 -3
- package/src/emoji/command.ts +189 -0
- package/src/emoji/faces.ts +136 -0
- package/src/emoji/favorite-index.ts +150 -0
- package/src/emoji/favorites.ts +161 -0
- package/src/emoji/label.ts +318 -0
- package/src/home.ts +45 -0
- package/src/index.ts +156 -32
- package/src/instance.ts +30 -17
- package/src/keepalive.ts +222 -0
- package/src/logger.ts +273 -17
- package/src/media-path.ts +186 -0
- package/src/model-view.ts +130 -0
- package/src/naplink/client.ts +10 -19
- package/src/naplink/history.ts +258 -0
- package/src/naplink/media.ts +34 -103
- package/src/naplink/render.ts +96 -32
- package/src/outbound.ts +146 -0
- package/src/rate-limit.ts +161 -0
- package/src/safe-fetch.ts +143 -0
- package/src/sensitive.ts +309 -0
- package/src/session/manager.ts +232 -18
- package/src/session/prompt.ts +4 -1
- package/src/tools/ask-guard.ts +3 -2
- package/src/tools/qq.ts +218 -36
- package/src/tools/send-guard.ts +72 -0
package/src/tools/qq.ts
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode/plugin"
|
|
2
2
|
import { type ChatTarget, isTargetEnabled, targetLabel } from "../chat"
|
|
3
3
|
import type { QQBotConfig } from "../config"
|
|
4
|
+
import {
|
|
5
|
+
CUSTOM_FACE_SUB_TYPE,
|
|
6
|
+
type FavoriteStore,
|
|
7
|
+
formatFavoriteIds,
|
|
8
|
+
formatFavoriteList,
|
|
9
|
+
} from "../emoji/favorites"
|
|
10
|
+
import type { FavoriteIndex } from "../emoji/favorite-index"
|
|
4
11
|
import type { Logger } from "../logger"
|
|
12
|
+
import type { OutboundMedia } from "../media-path"
|
|
5
13
|
import type { QQClient } from "../naplink/client"
|
|
14
|
+
import { splitGraphemes, splitMessage, toPlainText } from "../outbound"
|
|
15
|
+
import type { RateLimitVerdict, SendRateLimiter } from "../rate-limit"
|
|
16
|
+
import { modelSendScope, pluginSendScope } from "../rate-limit"
|
|
17
|
+
import type { SensitiveChecker } from "../sensitive"
|
|
6
18
|
import type { SessionManager } from "../session/manager"
|
|
7
19
|
|
|
8
20
|
/** 工具命名空间,最终工具名为 qq_send_message 等。 */
|
|
@@ -14,6 +26,16 @@ export interface ToolDeps {
|
|
|
14
26
|
logger: Logger
|
|
15
27
|
manager: SessionManager
|
|
16
28
|
client: QQClient
|
|
29
|
+
/** 收藏表情读写,供 qq_send_sticker 使用。 */
|
|
30
|
+
favorites: FavoriteStore
|
|
31
|
+
/** 收藏表情编号索引,供 qq_send_sticker 与 qq_favorite_list 使用。 */
|
|
32
|
+
favoriteIndex: FavoriteIndex
|
|
33
|
+
/** 出站限流器,所有发送类工具共用一个实例。 */
|
|
34
|
+
limiter: SendRateLimiter
|
|
35
|
+
/** 出站敏感信息检查,命中时整条消息不发送。 */
|
|
36
|
+
sensitive: SensitiveChecker
|
|
37
|
+
/** 出站媒体的路径与地址把关。 */
|
|
38
|
+
outbound: OutboundMedia
|
|
17
39
|
}
|
|
18
40
|
|
|
19
41
|
interface SendMessageInput {
|
|
@@ -41,15 +63,21 @@ interface UserInput {
|
|
|
41
63
|
user_id?: number | string
|
|
42
64
|
}
|
|
43
65
|
|
|
66
|
+
interface StickerInput {
|
|
67
|
+
id?: number
|
|
68
|
+
}
|
|
69
|
+
|
|
44
70
|
interface MessageIdInput {
|
|
45
71
|
message_id?: number | string
|
|
46
72
|
}
|
|
47
73
|
|
|
48
74
|
/** QQ 单条消息的保守长度上限,超过时按段发送。 */
|
|
49
|
-
export
|
|
75
|
+
export { MAX_MESSAGE_CHARS } from "../outbound"
|
|
50
76
|
|
|
51
|
-
function text(value: string) {
|
|
52
|
-
|
|
77
|
+
function text(value: string, metadata?: Record<string, unknown>) {
|
|
78
|
+
// 工具返回 error 文本时状态仍是 completed;把失败标记带给发送守卫。
|
|
79
|
+
const marks = { ...(value.startsWith("error:") ? { failed: true } : {}), ...metadata }
|
|
80
|
+
return { content: value, ...(Object.keys(marks).length > 0 ? { metadata: marks } : {}) }
|
|
53
81
|
}
|
|
54
82
|
|
|
55
83
|
function delay(ms: number): Promise<void> {
|
|
@@ -64,28 +92,39 @@ function messageIdOf(response: unknown): string | undefined {
|
|
|
64
92
|
return value === undefined || value === null ? undefined : String(value)
|
|
65
93
|
}
|
|
66
94
|
|
|
67
|
-
/**
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
95
|
+
/** 插件自己发的消息同样按操作 id 分组:一次发送拆出的多段共用一个 id。 */
|
|
96
|
+
let plainSeq = 0
|
|
97
|
+
const nextPlainOperation = (): string => `plain-${++plainSeq}`
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 向一个目标发送纯文本消息,超长时按段落拆分。
|
|
101
|
+
*
|
|
102
|
+
* 命令、后台任务这类没有会话轮次的场景用它回消息,
|
|
103
|
+
* 内容由插件自己生成,不做 markdown 剥离;
|
|
104
|
+
* 发送前只做节奏控制,不会被硬上限拦下。
|
|
105
|
+
*/
|
|
106
|
+
export async function sendPlainMessage(
|
|
107
|
+
client: QQClient,
|
|
108
|
+
target: ChatTarget,
|
|
109
|
+
content: string,
|
|
110
|
+
options: { delayMs?: number; limiter: SendRateLimiter },
|
|
111
|
+
): Promise<number> {
|
|
112
|
+
const chunks = splitMessage(content)
|
|
113
|
+
const operation = nextPlainOperation()
|
|
114
|
+
let sent = 0
|
|
115
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
116
|
+
await options.limiter.pace(pluginSendScope(target), operation)
|
|
117
|
+
if (target.kind === "group") {
|
|
118
|
+
await client.api.sendGroupMessage(target.id, chunk)
|
|
119
|
+
} else {
|
|
120
|
+
await client.api.sendPrivateMessage(target.id, chunk)
|
|
77
121
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
const part = Array.from(rest).slice(0, max).join("")
|
|
82
|
-
chunks.push(part)
|
|
83
|
-
rest = Array.from(rest).slice(max).join("")
|
|
122
|
+
sent += 1
|
|
123
|
+
if (index < chunks.length - 1 && (options.delayMs ?? 0) > 0) {
|
|
124
|
+
await delay(options.delayMs ?? 0)
|
|
84
125
|
}
|
|
85
|
-
current = rest
|
|
86
126
|
}
|
|
87
|
-
|
|
88
|
-
return chunks.length > 0 ? chunks : [content]
|
|
127
|
+
return sent
|
|
89
128
|
}
|
|
90
129
|
|
|
91
130
|
/**
|
|
@@ -95,7 +134,18 @@ export function splitMessage(content: string, max = MAX_MESSAGE_CHARS): string[]
|
|
|
95
134
|
* 只暴露消息收发与只读查询,不提供封禁/踢人等破坏性操作。
|
|
96
135
|
*/
|
|
97
136
|
export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promise<void> }> {
|
|
98
|
-
const {
|
|
137
|
+
const {
|
|
138
|
+
ctx,
|
|
139
|
+
config,
|
|
140
|
+
logger,
|
|
141
|
+
manager,
|
|
142
|
+
client,
|
|
143
|
+
favorites,
|
|
144
|
+
favoriteIndex,
|
|
145
|
+
limiter,
|
|
146
|
+
sensitive,
|
|
147
|
+
outbound,
|
|
148
|
+
} = deps
|
|
99
149
|
|
|
100
150
|
const requireTarget = (sessionID: string): ChatTarget | undefined => {
|
|
101
151
|
const target = manager.targetForSession(sessionID)
|
|
@@ -111,6 +161,47 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
111
161
|
return target
|
|
112
162
|
}
|
|
113
163
|
|
|
164
|
+
// 同一次工具调用拆出的多段共用一个操作 id:段与段之间不再额外等间隔。
|
|
165
|
+
let operationSeq = 0
|
|
166
|
+
const nextOperation = (): string => `send-${++operationSeq}`
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* 申请一次出站发送许可。
|
|
170
|
+
*
|
|
171
|
+
* 超出每分钟 / 每小时上限时拒绝这次发送,并把原因回给模型,
|
|
172
|
+
* 让它立刻停下,而不是把群刷爆。
|
|
173
|
+
*/
|
|
174
|
+
const permit = async (target: ChatTarget, operation: string): Promise<RateLimitVerdict> => {
|
|
175
|
+
const verdict = await limiter.acquire(modelSendScope(target), operation)
|
|
176
|
+
if (!verdict.allowed) logger.warn(`${targetLabel(target)} 出站限流:${verdict.reason}`)
|
|
177
|
+
return verdict
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 限流拒绝时的工具返回值:本轮算已回复,避免模型被反复提醒补发。 */
|
|
181
|
+
const refuse = (sessionID: string, verdict: RateLimitVerdict, sent = 0, total = 0) => {
|
|
182
|
+
manager.markMessageSent(sessionID)
|
|
183
|
+
const progress = total > 0 ? `(已发送 ${sent}/${total} 段)` : ""
|
|
184
|
+
// 限流拒绝是“请停止发送”,不要因为它允许模型立刻重试。
|
|
185
|
+
return text(`error: ${verdict.reason}${progress}`, { retryable: false })
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 出站前的敏感信息检查。
|
|
190
|
+
*
|
|
191
|
+
* 命中时抛错而不是返回 error 文本:发送守卫会因此解除“已发送”标记,
|
|
192
|
+
* 本轮也不会算作已回复,模型可以删掉凭证后立刻重发。
|
|
193
|
+
*/
|
|
194
|
+
const guardOutbound = (target: ChatTarget, content: string): void => {
|
|
195
|
+
const verdict = sensitive.check(content)
|
|
196
|
+
if (verdict.allowed) return
|
|
197
|
+
const detectors = verdict.hits.map((hit) => hit.detector).join("、")
|
|
198
|
+
logger.warn(`${targetLabel(target)} 出站消息包含敏感信息,已拦截:${detectors}`)
|
|
199
|
+
throw new Error(verdict.reason)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** base64:// 载荷是二进制数据,按文本扫描既没意义也慢。 */
|
|
203
|
+
const isInlineData = (value: string): boolean => value.startsWith("base64://")
|
|
204
|
+
|
|
114
205
|
const sendText = (target: ChatTarget, chunk: string) =>
|
|
115
206
|
target.kind === "group"
|
|
116
207
|
? client.api.sendGroupMessage(target.id, chunk)
|
|
@@ -170,14 +261,28 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
170
261
|
return text("skipped")
|
|
171
262
|
}
|
|
172
263
|
|
|
173
|
-
|
|
174
|
-
|
|
264
|
+
// 模型偶尔不听话写 markdown,剥成纯文本再发出去。
|
|
265
|
+
const plain = toPlainText(content).trim()
|
|
266
|
+
if (!plain) {
|
|
267
|
+
logger.info(`${label} 回复内容剥离后为空`)
|
|
268
|
+
manager.markMessageSent(context.sessionID)
|
|
269
|
+
return text("skipped")
|
|
270
|
+
}
|
|
271
|
+
guardOutbound(target, plain)
|
|
272
|
+
|
|
273
|
+
// 长度按字素簇算,和拆段的口径一致:一个 emoji 只算一个。
|
|
274
|
+
const length = splitGraphemes(plain).length
|
|
275
|
+
if (length > config.warnLength && input.unlimit_length !== true) {
|
|
276
|
+
logger.warn(`send_message 内容长度 ${length} 超过 ${config.warnLength}`)
|
|
175
277
|
}
|
|
176
278
|
|
|
177
|
-
const chunks = splitMessage(
|
|
279
|
+
const chunks = splitMessage(plain)
|
|
280
|
+
const operation = nextOperation()
|
|
178
281
|
let sent = 0
|
|
179
282
|
try {
|
|
180
283
|
for (const [index, chunk] of chunks.entries()) {
|
|
284
|
+
const verdict = await permit(target, operation)
|
|
285
|
+
if (!verdict.allowed) return refuse(context.sessionID, verdict, sent, chunks.length)
|
|
181
286
|
const response = await sendText(target, chunk)
|
|
182
287
|
const messageId = messageIdOf(response)
|
|
183
288
|
if (messageId) manager.rememberOutgoing(target, messageId)
|
|
@@ -189,10 +294,11 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
189
294
|
} catch (error) {
|
|
190
295
|
if (sent > 0) manager.markMessageSent(context.sessionID)
|
|
191
296
|
logger.error(`${label} 发送消息失败,已发送 ${sent}/${chunks.length} 段`, error)
|
|
192
|
-
|
|
297
|
+
// 已经发出部分段落时不要允许整条重试,否则会重复发送。
|
|
298
|
+
return text(`error: 消息只发送了 ${sent}/${chunks.length} 段`, { retryable: sent === 0 })
|
|
193
299
|
}
|
|
194
300
|
manager.markMessageSent(context.sessionID)
|
|
195
|
-
logger.info(`${label} 已发送 ${
|
|
301
|
+
logger.info(`${label} 已发送 ${length} 字`)
|
|
196
302
|
return text("你已成功发送消息,可以选择结束对话")
|
|
197
303
|
},
|
|
198
304
|
})
|
|
@@ -200,7 +306,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
200
306
|
editor.add({
|
|
201
307
|
name: "send_image",
|
|
202
308
|
description:
|
|
203
|
-
"向当前 QQ 群聊或私聊发送一张图片。file 可以是本地路径或 http(s) 图片地址;base64 传 base64://
|
|
309
|
+
"向当前 QQ 群聊或私聊发送一张图片。file 可以是本地路径或 http(s) 图片地址;base64 传 base64:// 形式的数据。本地路径只能取自机器人工作目录、媒体目录和配置放开的目录;http(s) 地址只允许公网地址。",
|
|
204
310
|
input: {
|
|
205
311
|
type: "object",
|
|
206
312
|
properties: {
|
|
@@ -216,7 +322,13 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
216
322
|
if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
|
|
217
323
|
const file = input.file ?? (input.base64 ? `base64://${input.base64}` : undefined)
|
|
218
324
|
if (!file) return text("error: 缺少 file 或 base64")
|
|
219
|
-
|
|
325
|
+
if (!isInlineData(file)) guardOutbound(target, file)
|
|
326
|
+
// 路径白名单在这里就判定:不过就不占发送额度。内联数据不涉及路径与网络。
|
|
327
|
+
const plan = isInlineData(file) ? undefined : await outbound.check(file)
|
|
328
|
+
const verdict = await permit(target, nextOperation())
|
|
329
|
+
if (!verdict.allowed) return refuse(context.sessionID, verdict)
|
|
330
|
+
const media = plan ? outbound.materialize(plan) : file
|
|
331
|
+
const response = await sendSegments(target, [{ type: "image", data: { file: media } }])
|
|
220
332
|
const messageId = messageIdOf(response)
|
|
221
333
|
if (messageId) manager.rememberOutgoing(target, messageId)
|
|
222
334
|
manager.markMessageSent(context.sessionID)
|
|
@@ -224,9 +336,68 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
224
336
|
},
|
|
225
337
|
})
|
|
226
338
|
|
|
339
|
+
editor.add({
|
|
340
|
+
name: "favorite_list",
|
|
341
|
+
description: "列出收藏表情(表情包)的编号与标签,编号用于 qq_send_sticker 发送。",
|
|
342
|
+
input: {
|
|
343
|
+
type: "object",
|
|
344
|
+
properties: {},
|
|
345
|
+
additionalProperties: false,
|
|
346
|
+
},
|
|
347
|
+
options: { namespace: TOOL_NAMESPACE },
|
|
348
|
+
execute: async () => {
|
|
349
|
+
const faces = await favorites.list()
|
|
350
|
+
const rows = await favoriteIndex.sync(faces)
|
|
351
|
+
return text(formatFavoriteList(rows))
|
|
352
|
+
},
|
|
353
|
+
})
|
|
354
|
+
|
|
355
|
+
editor.add({
|
|
356
|
+
name: "send_sticker",
|
|
357
|
+
description:
|
|
358
|
+
"发送一张收藏表情(表情包)。id 是收藏表情编号,先用 qq_favorite_list 查看编号与标签的对应关系。",
|
|
359
|
+
input: {
|
|
360
|
+
type: "object",
|
|
361
|
+
properties: {
|
|
362
|
+
id: { type: "number", description: "收藏表情编号" },
|
|
363
|
+
},
|
|
364
|
+
required: ["id"],
|
|
365
|
+
additionalProperties: false,
|
|
366
|
+
},
|
|
367
|
+
options: { namespace: TOOL_NAMESPACE },
|
|
368
|
+
execute: async (raw, context) => {
|
|
369
|
+
const input = (raw ?? {}) as StickerInput
|
|
370
|
+
const target = requireTarget(context.sessionID)
|
|
371
|
+
if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
|
|
372
|
+
const id = input.id
|
|
373
|
+
if (typeof id !== "number" || !Number.isInteger(id)) {
|
|
374
|
+
return text("error: 缺少 id(收藏表情编号)")
|
|
375
|
+
}
|
|
376
|
+
const faces = await favorites.list()
|
|
377
|
+
const rows = await favoriteIndex.sync(faces)
|
|
378
|
+
const row = rows.find((item) => item.id === id)
|
|
379
|
+
if (!row) {
|
|
380
|
+
return text(`error: 没有找到编号 ${id} 的收藏表情,可用编号:${formatFavoriteIds(rows)}`)
|
|
381
|
+
}
|
|
382
|
+
const url = typeof row.face.url === "string" ? row.face.url : undefined
|
|
383
|
+
if (!url) return text(`error: 编号 ${id} 的收藏表情缺少可用地址`)
|
|
384
|
+
guardOutbound(target, url)
|
|
385
|
+
const verdict = await permit(target, nextOperation())
|
|
386
|
+
if (!verdict.allowed) return refuse(context.sessionID, verdict)
|
|
387
|
+
const response = await sendSegments(target, [
|
|
388
|
+
{ type: "image", data: { file: url, sub_type: CUSTOM_FACE_SUB_TYPE } },
|
|
389
|
+
])
|
|
390
|
+
const messageId = messageIdOf(response)
|
|
391
|
+
if (messageId) manager.rememberOutgoing(target, messageId)
|
|
392
|
+
manager.markMessageSent(context.sessionID)
|
|
393
|
+
return text(`你已成功发送收藏表情 ${id}「${row.tag || "未标注"}」,可以选择结束对话`)
|
|
394
|
+
},
|
|
395
|
+
})
|
|
396
|
+
|
|
227
397
|
editor.add({
|
|
228
398
|
name: "send_record",
|
|
229
|
-
description:
|
|
399
|
+
description:
|
|
400
|
+
"向当前 QQ 群聊或私聊发送一条语音。file 可以是本地路径或 http(s) 音频地址。本地路径只能取自机器人工作目录、媒体目录和配置放开的目录;http(s) 地址只允许公网地址。",
|
|
230
401
|
input: {
|
|
231
402
|
type: "object",
|
|
232
403
|
properties: {
|
|
@@ -240,9 +411,12 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
240
411
|
const target = requireTarget(context.sessionID)
|
|
241
412
|
if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
|
|
242
413
|
if (!input.file) return text("error: 缺少 file")
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
414
|
+
if (!isInlineData(input.file)) guardOutbound(target, input.file)
|
|
415
|
+
const plan = isInlineData(input.file) ? undefined : await outbound.check(input.file)
|
|
416
|
+
const verdict = await permit(target, nextOperation())
|
|
417
|
+
if (!verdict.allowed) return refuse(context.sessionID, verdict)
|
|
418
|
+
const media = plan ? outbound.materialize(plan) : input.file
|
|
419
|
+
const response = await sendSegments(target, [{ type: "record", data: { file: media } }])
|
|
246
420
|
const messageId = messageIdOf(response)
|
|
247
421
|
if (messageId) manager.rememberOutgoing(target, messageId)
|
|
248
422
|
manager.markMessageSent(context.sessionID)
|
|
@@ -290,13 +464,19 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
290
464
|
if (!Number.isInteger(userId) || userId < 0) {
|
|
291
465
|
return text(`error: 非法 user_id:${String(node.user_id)}`)
|
|
292
466
|
}
|
|
467
|
+
const body = toPlainText(node.content ?? "").trim()
|
|
468
|
+
const nickname = node.nickname?.trim() || "未知用户"
|
|
469
|
+
// 昵称同样发给对方,不能成为凭证外发的盲区。
|
|
470
|
+
guardOutbound(target, `${nickname}\n${body}`)
|
|
293
471
|
nodes.push({
|
|
294
472
|
user_id: userId,
|
|
295
|
-
nickname
|
|
296
|
-
content: [{ type: "text", data: { text:
|
|
473
|
+
nickname,
|
|
474
|
+
content: [{ type: "text", data: { text: body } }],
|
|
297
475
|
})
|
|
298
476
|
}
|
|
299
477
|
if (nodes.length === 0) return text("error: nodes 为空")
|
|
478
|
+
const verdict = await permit(target, nextOperation())
|
|
479
|
+
if (!verdict.allowed) return refuse(context.sessionID, verdict)
|
|
300
480
|
const response = await sendForward(target, nodes)
|
|
301
481
|
const messageId = messageIdOf(response)
|
|
302
482
|
if (messageId) manager.rememberOutgoing(target, messageId)
|
|
@@ -322,6 +502,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
322
502
|
const target = requireTarget(context.sessionID)
|
|
323
503
|
if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
|
|
324
504
|
if (!input.user_id) return text("error: 缺少 user_id")
|
|
505
|
+
const verdict = await permit(target, nextOperation())
|
|
506
|
+
if (!verdict.allowed) return refuse(context.sessionID, verdict)
|
|
325
507
|
await sendPoke(target, input.user_id)
|
|
326
508
|
manager.markMessageSent(context.sessionID)
|
|
327
509
|
return text("你已成功戳一下用户,可以选择结束对话")
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import type { Logger } from "../logger"
|
|
3
|
+
import type { SessionManager, Turn } from "../session/manager"
|
|
4
|
+
|
|
5
|
+
/** 连续调用发送工具时回给模型的说明。 */
|
|
6
|
+
export const DUPLICATE_SEND_REFUSAL =
|
|
7
|
+
"禁止连续调用发送工具:上一步已经发送过消息,再发可能重复。请先调用其它工具(例如查看消息或整理内容),或直接结束本轮。"
|
|
8
|
+
|
|
9
|
+
/** 匹配 qq_send_message 等发送工具;钩子里可能带或不带命名空间。 */
|
|
10
|
+
const SEND_TOOL = /^(?:qq_)?send[_-]/
|
|
11
|
+
|
|
12
|
+
interface LastCall {
|
|
13
|
+
/** 所属轮次;轮次变化时重新计数,避免上一轮的最后一次发送影响下一轮。 */
|
|
14
|
+
turn: Turn | undefined
|
|
15
|
+
send: boolean
|
|
16
|
+
/** 被放行的发送调用 id,用于在发送失败时撤销标记。 */
|
|
17
|
+
callID?: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface SendGuardDeps {
|
|
21
|
+
ctx: Plugin.Context
|
|
22
|
+
logger: Logger
|
|
23
|
+
manager: SessionManager
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 禁止模型连续调用发送工具,避免同一条消息被重复发送。
|
|
28
|
+
* 只约束 QQ 轮次,人工在 TUI 里驱动时不受影响。
|
|
29
|
+
*/
|
|
30
|
+
export async function registerSendGuard(
|
|
31
|
+
deps: SendGuardDeps,
|
|
32
|
+
): Promise<{ dispose(): Promise<void> }> {
|
|
33
|
+
const { ctx, logger, manager } = deps
|
|
34
|
+
const last = new Map<string, LastCall>()
|
|
35
|
+
|
|
36
|
+
const before = await ctx.tool.hook("execute.before", async (event) => {
|
|
37
|
+
if (!manager.hasActiveTurn(event.sessionID)) return
|
|
38
|
+
const turn = manager.currentTurn(event.sessionID)
|
|
39
|
+
const previous = last.get(event.sessionID)
|
|
40
|
+
const send = SEND_TOOL.test(event.tool)
|
|
41
|
+
if (previous !== undefined && previous.turn === turn && previous.send && send) {
|
|
42
|
+
// 保持上一条已放行调用的记录:被拒绝的调用不改变状态,连续重试会一直被拒绝。
|
|
43
|
+
logger.warn(`模型连续调用 ${event.tool},已拒绝`)
|
|
44
|
+
throw new Error(DUPLICATE_SEND_REFUSAL)
|
|
45
|
+
}
|
|
46
|
+
last.set(event.sessionID, { turn, send, ...(send ? { callID: event.id } : {}) })
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
const after = await ctx.tool.hook("execute.after", async (event) => {
|
|
50
|
+
// 发送失败不算“已经发过”,允许立刻重试;被拒绝的调用不会走到这里。
|
|
51
|
+
// 工具返回 error 文本时状态仍是 completed,需要看结果里的 failed 标记;
|
|
52
|
+
// 限流拒绝会带 retryable: false,保持“已发送”状态,避免模型反复重试。
|
|
53
|
+
const metadata =
|
|
54
|
+
event.status === "completed"
|
|
55
|
+
? (event.result.metadata as { failed?: boolean; retryable?: boolean } | undefined)
|
|
56
|
+
: undefined
|
|
57
|
+
if (event.status !== "error" && !(metadata?.failed === true && metadata.retryable !== false)) {
|
|
58
|
+
return
|
|
59
|
+
}
|
|
60
|
+
const entry = last.get(event.sessionID)
|
|
61
|
+
if (entry?.callID !== event.id) return
|
|
62
|
+
entry.send = false
|
|
63
|
+
delete entry.callID
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
async dispose() {
|
|
68
|
+
await before.dispose()
|
|
69
|
+
await after.dispose()
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
}
|