@openclaw/qqbot 2026.5.2 → 2026.5.3-beta.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.
Files changed (203) hide show
  1. package/dist/api.js +646 -0
  2. package/dist/approval-cg0SVahb.js +94 -0
  3. package/dist/channel-N6Y_Rcjp.js +551 -0
  4. package/dist/channel-plugin-api.js +2 -0
  5. package/dist/channel.setup-ByCRAe5H.js +25 -0
  6. package/dist/config-D6545NkC.js +94 -0
  7. package/dist/config-schema-DFcjQw73.js +309 -0
  8. package/dist/exec-approvals-COUsM6wZ.js +138 -0
  9. package/dist/gateway-CmSUJKSt.js +6726 -0
  10. package/dist/handler-runtime-Bqm6N0WG.js +120 -0
  11. package/dist/index.js +29 -0
  12. package/dist/narrowing-BoieBTIU.js +25 -0
  13. package/dist/outbound-BJfhwrPg.js +1357 -0
  14. package/dist/request-context-DXtpwWui.js +921 -0
  15. package/dist/resolve-D_06fV6-.js +284 -0
  16. package/dist/runtime-BJAS3eXW.js +18 -0
  17. package/dist/runtime-api.js +2 -0
  18. package/dist/secret-contract-api.js +56 -0
  19. package/dist/sender-p-B14eLG.js +1987 -0
  20. package/dist/setup-entry.js +15 -0
  21. package/dist/setup-plugin-api.js +2 -0
  22. package/dist/string-normalize-Ci6NM5DE.js +98 -0
  23. package/dist/target-parser-Y0prnrXD.js +245 -0
  24. package/package.json +15 -6
  25. package/api.ts +0 -56
  26. package/channel-plugin-api.ts +0 -1
  27. package/index.ts +0 -29
  28. package/runtime-api.ts +0 -9
  29. package/setup-entry.ts +0 -9
  30. package/setup-plugin-api.ts +0 -3
  31. package/src/bridge/approval/capability.ts +0 -237
  32. package/src/bridge/approval/handler-runtime.ts +0 -204
  33. package/src/bridge/bootstrap.ts +0 -135
  34. package/src/bridge/channel-entry.ts +0 -18
  35. package/src/bridge/commands/framework-context-adapter.ts +0 -60
  36. package/src/bridge/commands/framework-registration.ts +0 -47
  37. package/src/bridge/commands/from-parser.test.ts +0 -86
  38. package/src/bridge/commands/from-parser.ts +0 -60
  39. package/src/bridge/commands/result-dispatcher.ts +0 -76
  40. package/src/bridge/config-shared.ts +0 -132
  41. package/src/bridge/config.ts +0 -111
  42. package/src/bridge/gateway.ts +0 -174
  43. package/src/bridge/logger.ts +0 -31
  44. package/src/bridge/narrowing.ts +0 -31
  45. package/src/bridge/plugin-version.test.ts +0 -146
  46. package/src/bridge/plugin-version.ts +0 -102
  47. package/src/bridge/runtime.ts +0 -25
  48. package/src/bridge/sdk-adapter.ts +0 -131
  49. package/src/bridge/setup/finalize.ts +0 -144
  50. package/src/bridge/setup/surface.ts +0 -34
  51. package/src/bridge/tools/channel.ts +0 -58
  52. package/src/bridge/tools/index.ts +0 -15
  53. package/src/bridge/tools/remind.test.ts +0 -124
  54. package/src/bridge/tools/remind.ts +0 -91
  55. package/src/channel.setup.ts +0 -33
  56. package/src/channel.ts +0 -288
  57. package/src/command-auth.test.ts +0 -62
  58. package/src/config-schema.ts +0 -84
  59. package/src/config.test.ts +0 -364
  60. package/src/engine/access/access-control.test.ts +0 -198
  61. package/src/engine/access/access-control.ts +0 -226
  62. package/src/engine/access/index.ts +0 -16
  63. package/src/engine/access/resolve-policy.test.ts +0 -59
  64. package/src/engine/access/resolve-policy.ts +0 -57
  65. package/src/engine/access/sender-match.test.ts +0 -60
  66. package/src/engine/access/sender-match.ts +0 -55
  67. package/src/engine/access/types.ts +0 -53
  68. package/src/engine/adapter/audio.port.ts +0 -27
  69. package/src/engine/adapter/commands.port.ts +0 -22
  70. package/src/engine/adapter/history.port.ts +0 -52
  71. package/src/engine/adapter/index.ts +0 -139
  72. package/src/engine/adapter/mention-gate.port.ts +0 -50
  73. package/src/engine/adapter/types.ts +0 -38
  74. package/src/engine/api/api-client.ts +0 -212
  75. package/src/engine/api/media-chunked.test.ts +0 -336
  76. package/src/engine/api/media-chunked.ts +0 -622
  77. package/src/engine/api/media.ts +0 -218
  78. package/src/engine/api/messages.ts +0 -293
  79. package/src/engine/api/retry.ts +0 -217
  80. package/src/engine/api/routes.ts +0 -95
  81. package/src/engine/api/token.ts +0 -271
  82. package/src/engine/approval/index.test.ts +0 -22
  83. package/src/engine/approval/index.ts +0 -224
  84. package/src/engine/commands/builtin/log-helpers.ts +0 -319
  85. package/src/engine/commands/builtin/register-all.ts +0 -17
  86. package/src/engine/commands/builtin/register-approve.ts +0 -201
  87. package/src/engine/commands/builtin/register-basic.ts +0 -95
  88. package/src/engine/commands/builtin/register-clear-storage.ts +0 -187
  89. package/src/engine/commands/builtin/register-logs.ts +0 -20
  90. package/src/engine/commands/builtin/register-streaming.ts +0 -137
  91. package/src/engine/commands/builtin/state.ts +0 -31
  92. package/src/engine/commands/slash-command-auth.ts +0 -48
  93. package/src/engine/commands/slash-command-handler.ts +0 -146
  94. package/src/engine/commands/slash-commands-impl.test.ts +0 -8
  95. package/src/engine/commands/slash-commands-impl.ts +0 -61
  96. package/src/engine/commands/slash-commands.ts +0 -199
  97. package/src/engine/config/credential-backup.test.ts +0 -88
  98. package/src/engine/config/credential-backup.ts +0 -107
  99. package/src/engine/config/credentials.ts +0 -76
  100. package/src/engine/config/group.test.ts +0 -234
  101. package/src/engine/config/group.ts +0 -299
  102. package/src/engine/config/resolve.test.ts +0 -152
  103. package/src/engine/config/resolve.ts +0 -283
  104. package/src/engine/config/setup-logic.ts +0 -84
  105. package/src/engine/engine-import-boundary.test.ts +0 -73
  106. package/src/engine/gateway/codec.ts +0 -47
  107. package/src/engine/gateway/constants.ts +0 -117
  108. package/src/engine/gateway/event-dispatcher.ts +0 -177
  109. package/src/engine/gateway/gateway-connection.ts +0 -371
  110. package/src/engine/gateway/gateway.ts +0 -291
  111. package/src/engine/gateway/inbound-attachments.test.ts +0 -126
  112. package/src/engine/gateway/inbound-attachments.ts +0 -360
  113. package/src/engine/gateway/inbound-context.ts +0 -195
  114. package/src/engine/gateway/inbound-pipeline.self-echo.test.ts +0 -218
  115. package/src/engine/gateway/inbound-pipeline.ts +0 -235
  116. package/src/engine/gateway/interaction-handler.ts +0 -220
  117. package/src/engine/gateway/message-queue.test.ts +0 -282
  118. package/src/engine/gateway/message-queue.ts +0 -499
  119. package/src/engine/gateway/outbound-dispatch.test.ts +0 -231
  120. package/src/engine/gateway/outbound-dispatch.ts +0 -575
  121. package/src/engine/gateway/reconnect.ts +0 -199
  122. package/src/engine/gateway/stages/access-stage.ts +0 -132
  123. package/src/engine/gateway/stages/assembly-stage.ts +0 -156
  124. package/src/engine/gateway/stages/content-stage.test.ts +0 -77
  125. package/src/engine/gateway/stages/content-stage.ts +0 -77
  126. package/src/engine/gateway/stages/envelope-stage.test.ts +0 -152
  127. package/src/engine/gateway/stages/envelope-stage.ts +0 -144
  128. package/src/engine/gateway/stages/group-gate-stage.ts +0 -292
  129. package/src/engine/gateway/stages/index.ts +0 -18
  130. package/src/engine/gateway/stages/quote-stage.ts +0 -113
  131. package/src/engine/gateway/stages/refidx-stage.ts +0 -62
  132. package/src/engine/gateway/stages/stub-contexts.ts +0 -116
  133. package/src/engine/gateway/types.ts +0 -264
  134. package/src/engine/gateway/typing-keepalive.ts +0 -79
  135. package/src/engine/group/activation.test.ts +0 -114
  136. package/src/engine/group/activation.ts +0 -147
  137. package/src/engine/group/history.test.ts +0 -314
  138. package/src/engine/group/history.ts +0 -321
  139. package/src/engine/group/mention.test.ts +0 -141
  140. package/src/engine/group/mention.ts +0 -197
  141. package/src/engine/group/message-gating.test.ts +0 -188
  142. package/src/engine/group/message-gating.ts +0 -216
  143. package/src/engine/messaging/decode-media-path.ts +0 -82
  144. package/src/engine/messaging/media-source.ts +0 -215
  145. package/src/engine/messaging/media-type-detect.ts +0 -37
  146. package/src/engine/messaging/outbound-audio-port.ts +0 -38
  147. package/src/engine/messaging/outbound-deliver.ts +0 -810
  148. package/src/engine/messaging/outbound-media-send.ts +0 -702
  149. package/src/engine/messaging/outbound-reply.ts +0 -27
  150. package/src/engine/messaging/outbound-result-helpers.ts +0 -54
  151. package/src/engine/messaging/outbound-types.ts +0 -45
  152. package/src/engine/messaging/outbound.ts +0 -485
  153. package/src/engine/messaging/reply-dispatcher.ts +0 -597
  154. package/src/engine/messaging/reply-limiter.ts +0 -164
  155. package/src/engine/messaging/sender.ts +0 -729
  156. package/src/engine/messaging/streaming-c2c.ts +0 -1192
  157. package/src/engine/messaging/streaming-media-send.ts +0 -544
  158. package/src/engine/messaging/target-parser.ts +0 -104
  159. package/src/engine/ref/format-message-ref.ts +0 -142
  160. package/src/engine/ref/format-ref-entry.test.ts +0 -60
  161. package/src/engine/ref/format-ref-entry.ts +0 -27
  162. package/src/engine/ref/store.ts +0 -208
  163. package/src/engine/ref/types.ts +0 -27
  164. package/src/engine/session/known-users.ts +0 -137
  165. package/src/engine/session/session-store.ts +0 -204
  166. package/src/engine/tools/channel-api.ts +0 -244
  167. package/src/engine/tools/remind-logic.test.ts +0 -280
  168. package/src/engine/tools/remind-logic.ts +0 -377
  169. package/src/engine/types.ts +0 -313
  170. package/src/engine/utils/attachment-tags.test.ts +0 -186
  171. package/src/engine/utils/attachment-tags.ts +0 -174
  172. package/src/engine/utils/audio.test.ts +0 -250
  173. package/src/engine/utils/audio.ts +0 -585
  174. package/src/engine/utils/data-paths.ts +0 -38
  175. package/src/engine/utils/diagnostics.ts +0 -109
  176. package/src/engine/utils/file-utils.test.ts +0 -72
  177. package/src/engine/utils/file-utils.ts +0 -225
  178. package/src/engine/utils/format.test.ts +0 -68
  179. package/src/engine/utils/format.ts +0 -70
  180. package/src/engine/utils/image-size.test.ts +0 -158
  181. package/src/engine/utils/image-size.ts +0 -249
  182. package/src/engine/utils/log.test.ts +0 -28
  183. package/src/engine/utils/log.ts +0 -61
  184. package/src/engine/utils/media-tags.test.ts +0 -32
  185. package/src/engine/utils/media-tags.ts +0 -177
  186. package/src/engine/utils/payload.test.ts +0 -68
  187. package/src/engine/utils/payload.ts +0 -145
  188. package/src/engine/utils/platform-storage-laziness.test.ts +0 -63
  189. package/src/engine/utils/platform.test.ts +0 -148
  190. package/src/engine/utils/platform.ts +0 -343
  191. package/src/engine/utils/request-context.ts +0 -60
  192. package/src/engine/utils/string-normalize.ts +0 -91
  193. package/src/engine/utils/stt.test.ts +0 -104
  194. package/src/engine/utils/stt.ts +0 -100
  195. package/src/engine/utils/text-parsing.test.ts +0 -29
  196. package/src/engine/utils/text-parsing.ts +0 -155
  197. package/src/engine/utils/upload-cache.ts +0 -96
  198. package/src/engine/utils/voice-text.ts +0 -15
  199. package/src/exec-approvals.ts +0 -218
  200. package/src/manifest-schema.test.ts +0 -56
  201. package/src/qqbot-test-support.ts +0 -29
  202. package/src/types.ts +0 -210
  203. package/tsconfig.json +0 -16
@@ -1,575 +0,0 @@
1
- /**
2
- * Outbound dispatcher — manage AI reply delivery, tool fallback, and timeouts.
3
- *
4
- * Responsibilities:
5
- * 1. Build ctxPayload and call runtime.dispatchReply
6
- * 2. Tool deliver collection + fallback timeout
7
- * 3. Block deliver pipeline (consumeQuoteRef → media tags → structured payload → plain text)
8
- * 4. Timeout / error handling
9
- *
10
- * Separated from gateway.ts for testability and to keep handleMessage thin.
11
- */
12
-
13
- import type { FinalizedMsgContext } from "openclaw/plugin-sdk/reply-runtime";
14
- import {
15
- parseAndSendMediaTags,
16
- sendPlainReply,
17
- type DeliverDeps,
18
- } from "../messaging/outbound-deliver.js";
19
- import {
20
- sendDocument,
21
- sendMedia,
22
- sendPhoto,
23
- sendVoice,
24
- sendVideoMsg,
25
- } from "../messaging/outbound.js";
26
- import {
27
- handleStructuredPayload,
28
- sendTextAsVoiceReply,
29
- sendErrorToTarget,
30
- sendWithTokenRetry,
31
- type ReplyDispatcherDeps,
32
- } from "../messaging/reply-dispatcher.js";
33
- import { StreamingController, shouldUseOfficialC2cStream } from "../messaging/streaming-c2c.js";
34
- import { audioFileToSilkBase64 } from "../utils/audio.js";
35
- import type { InboundContext } from "./inbound-context.js";
36
- import type {
37
- GatewayAccount,
38
- EngineLogger,
39
- GatewayPluginRuntime,
40
- OutboundResult,
41
- } from "./types.js";
42
-
43
- // ============ Config ============
44
-
45
- const RESPONSE_TIMEOUT = 300_000;
46
- const TOOL_ONLY_TIMEOUT = 60_000;
47
- const MAX_TOOL_RENEWALS = 3;
48
- const TOOL_MEDIA_SEND_TIMEOUT = 45_000;
49
-
50
- // ============ Dependencies ============
51
-
52
- interface OutboundDispatchDeps {
53
- runtime: GatewayPluginRuntime;
54
- cfg: unknown;
55
- account: GatewayAccount;
56
- log?: EngineLogger;
57
- }
58
-
59
- type ReplyDeliverPayload = {
60
- text?: string;
61
- mediaUrls?: string[];
62
- mediaUrl?: string;
63
- audioAsVoice?: boolean;
64
- };
65
-
66
- // ============ dispatchOutbound ============
67
-
68
- /**
69
- * Dispatch the AI reply for the given inbound context.
70
- *
71
- * Handles tool deliver collection, block deliver pipeline, and timeouts.
72
- * The caller is responsible for stopping typing.keepAlive in `finally`.
73
- */
74
- export async function dispatchOutbound(
75
- inbound: InboundContext,
76
- deps: OutboundDispatchDeps,
77
- ): Promise<void> {
78
- const { runtime, cfg, account, log } = deps;
79
- const { event, qualifiedTarget } = inbound;
80
-
81
- const replyTarget = {
82
- type: event.type,
83
- senderId: event.senderId,
84
- messageId: event.messageId,
85
- channelId: event.channelId,
86
- guildId: event.guildId,
87
- groupOpenid: event.groupOpenid,
88
- };
89
- const replyCtx = { target: replyTarget, account, cfg, log };
90
-
91
- const sendWithRetry = <T>(sendFn: (token: string) => Promise<T>) =>
92
- sendWithTokenRetry(account.appId, account.clientSecret, sendFn, log, account.accountId);
93
-
94
- const sendErrorMessage = (errorText: string) => sendErrorToTarget(replyCtx, errorText);
95
-
96
- // ---- Build ctxPayload ----
97
- const ctxPayload = buildCtxPayload(inbound, runtime);
98
-
99
- // ---- Deliver state ----
100
- let hasResponse = false;
101
- let hasBlockResponse = false;
102
- let toolDeliverCount = 0;
103
- const toolTexts: string[] = [];
104
- const toolMediaUrls: string[] = [];
105
- let toolFallbackSent = false;
106
- let toolRenewalCount = 0;
107
- let timeoutId: ReturnType<typeof setTimeout> | null = null;
108
- let toolOnlyTimeoutId: ReturnType<typeof setTimeout> | null = null;
109
-
110
- // ---- Tool fallback ----
111
- const sendToolFallback = async (): Promise<void> => {
112
- if (toolMediaUrls.length > 0) {
113
- for (const mediaUrl of toolMediaUrls) {
114
- const ac = new AbortController();
115
- try {
116
- const result = await Promise.race([
117
- sendMedia({
118
- to: qualifiedTarget,
119
- text: "",
120
- mediaUrl,
121
- accountId: account.accountId,
122
- replyToId: event.messageId,
123
- account,
124
- }).then((r) => {
125
- if (ac.signal.aborted) {
126
- return { channel: "qqbot", error: "suppressed" } as OutboundResult;
127
- }
128
- return r;
129
- }),
130
- new Promise<OutboundResult>((resolve) =>
131
- setTimeout(() => {
132
- ac.abort();
133
- resolve({ channel: "qqbot", error: "timeout" });
134
- }, TOOL_MEDIA_SEND_TIMEOUT),
135
- ),
136
- ]);
137
- if (result.error) {
138
- log?.error(`Tool fallback error: ${result.error}`);
139
- }
140
- } catch (err) {
141
- log?.error(`Tool fallback failed: ${String(err)}`);
142
- }
143
- }
144
- return;
145
- }
146
- if (toolTexts.length > 0) {
147
- await sendErrorMessage(toolTexts.slice(-3).join("\n---\n").slice(0, 2000));
148
- }
149
- };
150
-
151
- // ---- Timeout promise ----
152
- const timeoutPromise = new Promise<void>((_, reject) => {
153
- timeoutId = setTimeout(() => {
154
- if (!hasResponse) {
155
- reject(new Error("Response timeout"));
156
- }
157
- }, RESPONSE_TIMEOUT);
158
- });
159
-
160
- // ---- Deliver deps ----
161
- const deliverDeps: DeliverDeps = {
162
- mediaSender: {
163
- sendPhoto: (target, imageUrl) => sendPhoto(target, imageUrl),
164
- sendVoice: (target, voicePath, uploadFormats, transcodeEnabled) =>
165
- sendVoice(target, voicePath, uploadFormats, transcodeEnabled),
166
- sendVideoMsg: (target, videoPath) => sendVideoMsg(target, videoPath),
167
- sendDocument: (target, filePath) => sendDocument(target, filePath),
168
- sendMedia: (opts) => sendMedia(opts),
169
- },
170
- chunkText: (text, limit) => runtime.channel.text.chunkMarkdownText(text, limit),
171
- };
172
-
173
- const replyDeps: ReplyDispatcherDeps = {
174
- tts: {
175
- textToSpeech: (params) => runtime.tts.textToSpeech(params),
176
- audioFileToSilkBase64: async (p) => (await audioFileToSilkBase64(p)) ?? undefined,
177
- },
178
- };
179
-
180
- const recordOutbound = () =>
181
- runtime.channel.activity.record({
182
- channel: "qqbot",
183
- accountId: account.accountId,
184
- direction: "outbound",
185
- });
186
-
187
- // ---- Dispatch ----
188
- const messagesConfig = runtime.channel.reply.resolveEffectiveMessagesConfig(
189
- cfg,
190
- inbound.route.agentId,
191
- );
192
-
193
- const targetType =
194
- event.type === "c2c"
195
- ? ("c2c" as const)
196
- : event.type === "group"
197
- ? ("group" as const)
198
- : ("channel" as const);
199
- const useOfficialC2cStream = shouldUseOfficialC2cStream(account, targetType);
200
- let streamingController: StreamingController | null = null;
201
- if (useOfficialC2cStream) {
202
- streamingController = new StreamingController({
203
- account,
204
- userId: event.senderId,
205
- replyToMsgId: event.messageId,
206
- eventId: event.messageId,
207
- logPrefix: `[qqbot:${account.accountId}:streaming]`,
208
- log,
209
- mediaContext: {
210
- account,
211
- event: {
212
- type: event.type as "c2c" | "group" | "channel",
213
- senderId: event.senderId,
214
- messageId: event.messageId,
215
- groupOpenid: event.groupOpenid,
216
- channelId: event.channelId,
217
- },
218
- log,
219
- },
220
- });
221
- }
222
-
223
- const cfgWithSession = cfg as { session?: { store?: unknown } };
224
- const agentId = inbound.route.agentId ?? "default";
225
- const storePath = runtime.channel.session.resolveStorePath(cfgWithSession.session?.store, {
226
- agentId,
227
- });
228
- const dispatchPromise = runtime.channel.turn.run({
229
- channel: "qqbot",
230
- accountId: inbound.route.accountId,
231
- raw: inbound,
232
- adapter: {
233
- ingest: () => ({
234
- id: ctxPayload.MessageSid ?? `${ctxPayload.From}:${Date.now()}`,
235
- rawText: ctxPayload.RawBody ?? "",
236
- textForAgent: ctxPayload.BodyForAgent,
237
- textForCommands: ctxPayload.CommandBody,
238
- raw: inbound,
239
- }),
240
- resolveTurn: () => ({
241
- channel: "qqbot",
242
- accountId: inbound.route.accountId,
243
- routeSessionKey: inbound.route.sessionKey,
244
- storePath,
245
- ctxPayload,
246
- recordInboundSession: runtime.channel.session.recordInboundSession,
247
- record: {
248
- onRecordError: (err: unknown) => {
249
- log?.error(
250
- `Session metadata update failed: ${err instanceof Error ? err.message : String(err)}`,
251
- );
252
- },
253
- },
254
- runDispatch: () =>
255
- runtime.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
256
- ctx: ctxPayload,
257
- cfg,
258
- dispatcherOptions: {
259
- responsePrefix: messagesConfig.responsePrefix,
260
- deliver: async (payload: ReplyDeliverPayload, info: { kind: string }) => {
261
- hasResponse = true;
262
-
263
- // ---- Tool deliver ----
264
- if (info.kind === "tool") {
265
- toolDeliverCount++;
266
- const toolText = (payload.text ?? "").trim();
267
- if (toolText) {
268
- toolTexts.push(toolText);
269
- }
270
- if (payload.mediaUrls?.length) {
271
- toolMediaUrls.push(...payload.mediaUrls);
272
- }
273
- if (payload.mediaUrl && !toolMediaUrls.includes(payload.mediaUrl)) {
274
- toolMediaUrls.push(payload.mediaUrl);
275
- }
276
-
277
- if (hasBlockResponse && toolMediaUrls.length > 0) {
278
- const urlsToSend = [...toolMediaUrls];
279
- toolMediaUrls.length = 0;
280
- for (const mediaUrl of urlsToSend) {
281
- try {
282
- await sendMedia({
283
- to: qualifiedTarget,
284
- text: "",
285
- mediaUrl,
286
- accountId: account.accountId,
287
- replyToId: event.messageId,
288
- account,
289
- });
290
- } catch {}
291
- }
292
- return;
293
- }
294
- if (toolFallbackSent) {
295
- return;
296
- }
297
- if (toolOnlyTimeoutId) {
298
- if (toolRenewalCount < MAX_TOOL_RENEWALS) {
299
- clearTimeout(toolOnlyTimeoutId);
300
- toolRenewalCount++;
301
- } else {
302
- return;
303
- }
304
- }
305
- toolOnlyTimeoutId = setTimeout(async () => {
306
- if (!hasBlockResponse && !toolFallbackSent) {
307
- toolFallbackSent = true;
308
- try {
309
- await sendToolFallback();
310
- } catch {}
311
- }
312
- }, TOOL_ONLY_TIMEOUT);
313
- return;
314
- }
315
-
316
- // ---- Block deliver ----
317
- hasBlockResponse = true;
318
- inbound.typing.keepAlive?.stop();
319
- if (timeoutId) {
320
- clearTimeout(timeoutId);
321
- timeoutId = null;
322
- }
323
- if (toolOnlyTimeoutId) {
324
- clearTimeout(toolOnlyTimeoutId);
325
- toolOnlyTimeoutId = null;
326
- }
327
-
328
- if (streamingController && !streamingController.isTerminalPhase) {
329
- try {
330
- await streamingController.onDeliver(payload);
331
- } catch (err) {
332
- log?.error(
333
- `Streaming deliver error: ${err instanceof Error ? err.message : String(err)}`,
334
- );
335
- }
336
-
337
- const replyPreview = (payload.text ?? "").trim();
338
- if (
339
- event.type === "group" &&
340
- (replyPreview === "NO_REPLY" || replyPreview === "[SKIP]")
341
- ) {
342
- log?.info(
343
- `Model decided to skip group message (${replyPreview}) from ${event.senderId}`,
344
- );
345
- return;
346
- }
347
-
348
- if (streamingController.shouldFallbackToStatic) {
349
- log?.info("Streaming API unavailable, falling back to static for this deliver");
350
- } else {
351
- recordOutbound();
352
- return;
353
- }
354
- }
355
-
356
- const quoteRef = event.msgIdx;
357
- let quoteRefUsed = false;
358
- const consumeQuoteRef = (): string | undefined => {
359
- if (quoteRef && !quoteRefUsed) {
360
- quoteRefUsed = true;
361
- return quoteRef;
362
- }
363
- return undefined;
364
- };
365
-
366
- let replyText = payload.text ?? "";
367
- const deliverEvent = {
368
- type: event.type,
369
- senderId: event.senderId,
370
- messageId: event.messageId,
371
- channelId: event.channelId,
372
- groupOpenid: event.groupOpenid,
373
- msgIdx: event.msgIdx,
374
- };
375
- const deliverActx = { account, qualifiedTarget, log };
376
-
377
- // 1. Media tags
378
- const mediaResult = await parseAndSendMediaTags(
379
- replyText,
380
- deliverEvent,
381
- deliverActx,
382
- sendWithRetry,
383
- consumeQuoteRef,
384
- deliverDeps,
385
- );
386
- if (mediaResult.handled) {
387
- recordOutbound();
388
- return;
389
- }
390
- replyText = mediaResult.normalizedText;
391
-
392
- // 2. Structured payload (QQBOT_PAYLOAD:)
393
- const handled = await handleStructuredPayload(
394
- replyCtx,
395
- replyText,
396
- recordOutbound,
397
- replyDeps,
398
- );
399
- if (handled) {
400
- return;
401
- }
402
-
403
- // 3. Voice-intent plain text
404
- if (
405
- payload.audioAsVoice === true &&
406
- !payload.mediaUrl &&
407
- !payload.mediaUrls?.length
408
- ) {
409
- const sentVoice = await sendTextAsVoiceReply(replyCtx, replyText, replyDeps);
410
- if (sentVoice) {
411
- recordOutbound();
412
- return;
413
- }
414
- }
415
-
416
- // 4. Plain text + images/media
417
- await sendPlainReply(
418
- payload,
419
- replyText,
420
- deliverEvent,
421
- deliverActx,
422
- sendWithRetry,
423
- consumeQuoteRef,
424
- toolMediaUrls,
425
- deliverDeps,
426
- );
427
- recordOutbound();
428
- },
429
- onError: async (err: unknown) => {
430
- if (streamingController && !streamingController.isTerminalPhase) {
431
- try {
432
- await streamingController.onError(err);
433
- } catch (streamErr) {
434
- const streamErrMsg =
435
- streamErr instanceof Error ? streamErr.message : String(streamErr);
436
- log?.error(`Streaming onError failed: ${streamErrMsg}`);
437
- }
438
- if (!streamingController.shouldFallbackToStatic) {
439
- return;
440
- }
441
- }
442
- const errMsg = err instanceof Error ? err.message : String(err);
443
- log?.error(`Dispatch error: ${errMsg}`);
444
- hasResponse = true;
445
- if (timeoutId) {
446
- clearTimeout(timeoutId);
447
- timeoutId = null;
448
- }
449
- },
450
- },
451
- replyOptions: {
452
- disableBlockStreaming: useOfficialC2cStream
453
- ? true
454
- : (() => {
455
- const s = account.config?.streaming;
456
- if (s === false) {
457
- return true;
458
- }
459
- return typeof s === "object" && s !== null && s.mode === "off";
460
- })(),
461
- ...(streamingController
462
- ? {
463
- onPartialReply: async (payload: { text?: string }) => {
464
- try {
465
- await streamingController.onPartialReply(payload);
466
- } catch (partialErr) {
467
- log?.error(
468
- `Streaming onPartialReply error: ${partialErr instanceof Error ? partialErr.message : String(partialErr)}`,
469
- );
470
- }
471
- },
472
- }
473
- : {}),
474
- },
475
- }),
476
- }),
477
- },
478
- });
479
-
480
- try {
481
- await Promise.race([dispatchPromise, timeoutPromise]);
482
- } catch {
483
- if (timeoutId) {
484
- clearTimeout(timeoutId);
485
- }
486
- } finally {
487
- if (toolOnlyTimeoutId) {
488
- clearTimeout(toolOnlyTimeoutId);
489
- toolOnlyTimeoutId = null;
490
- }
491
- if (toolDeliverCount > 0 && !hasBlockResponse && !toolFallbackSent) {
492
- toolFallbackSent = true;
493
- await sendToolFallback();
494
- }
495
- if (streamingController && !streamingController.isTerminalPhase) {
496
- try {
497
- streamingController.markFullyComplete();
498
- await streamingController.onIdle();
499
- } catch (finalizeErr) {
500
- log?.error(
501
- `Streaming finalization error: ${finalizeErr instanceof Error ? finalizeErr.message : String(finalizeErr)}`,
502
- );
503
- try {
504
- await streamingController.abortStreaming();
505
- } catch {
506
- /* ignore */
507
- }
508
- }
509
- }
510
- }
511
- }
512
-
513
- // ============ ctxPayload builder ============
514
-
515
- function buildCtxPayload(
516
- inbound: InboundContext,
517
- runtime: GatewayPluginRuntime,
518
- ): FinalizedMsgContext {
519
- const { event } = inbound;
520
- return runtime.channel.reply.finalizeInboundContext({
521
- Body: inbound.body,
522
- BodyForAgent: inbound.agentBody,
523
- RawBody: event.content,
524
- CommandBody: event.content,
525
- From: inbound.fromAddress,
526
- To: inbound.fromAddress,
527
- SessionKey: inbound.route.sessionKey,
528
- AccountId: inbound.route.accountId,
529
- ChatType: inbound.isGroupChat ? "group" : "direct",
530
- GroupSystemPrompt: inbound.groupSystemPrompt,
531
- SenderId: event.senderId,
532
- SenderName: event.senderName,
533
- Provider: "qqbot",
534
- Surface: "qqbot",
535
- MessageSid: event.messageId,
536
- Timestamp: new Date(event.timestamp).getTime(),
537
- OriginatingChannel: "qqbot",
538
- OriginatingTo: inbound.fromAddress,
539
- QQChannelId: event.channelId,
540
- QQGuildId: event.guildId,
541
- QQGroupOpenid: event.groupOpenid,
542
- QQVoiceAsrReferAvailable: inbound.hasAsrReferFallback,
543
- QQVoiceTranscriptSources: inbound.voiceTranscriptSources,
544
- QQVoiceAttachmentPaths: inbound.uniqueVoicePaths,
545
- QQVoiceAttachmentUrls: inbound.uniqueVoiceUrls,
546
- QQVoiceAsrReferTexts: inbound.uniqueVoiceAsrReferTexts,
547
- QQVoiceInputStrategy: "prefer_audio_stt_then_asr_fallback",
548
- CommandAuthorized: inbound.commandAuthorized,
549
- ...(inbound.voiceMediaTypes.length > 0
550
- ? {
551
- MediaTypes: inbound.voiceMediaTypes,
552
- MediaType: inbound.voiceMediaTypes[0],
553
- }
554
- : {}),
555
- ...(inbound.localMediaPaths.length > 0
556
- ? {
557
- MediaPaths: inbound.localMediaPaths,
558
- MediaPath: inbound.localMediaPaths[0],
559
- MediaTypes: inbound.localMediaTypes,
560
- MediaType: inbound.localMediaTypes[0],
561
- }
562
- : {}),
563
- ...(inbound.remoteMediaUrls.length > 0
564
- ? { MediaUrls: inbound.remoteMediaUrls, MediaUrl: inbound.remoteMediaUrls[0] }
565
- : {}),
566
- ...(inbound.replyTo
567
- ? {
568
- ReplyToId: inbound.replyTo.id,
569
- ReplyToBody: inbound.replyTo.body,
570
- ReplyToSender: inbound.replyTo.sender,
571
- ReplyToIsQuote: inbound.replyTo.isQuote,
572
- }
573
- : {}),
574
- }) as FinalizedMsgContext;
575
- }