@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
package/dist/api.js ADDED
@@ -0,0 +1,646 @@
1
+ import { C as recordMessageReply, E as setOutboundAudioPort, S as getMessageReplyStats, T as OUTBOUND_ERROR_CODES, _ as sendVoice, a as sendText, b as checkMessageReplyLimit, d as buildMediaTarget, f as parseTarget, g as sendVideoMsg, h as sendPhoto, i as sendProactiveMessage, m as sendDocument, n as sendCronMessage, p as resolveOutboundMediaPath, r as sendMedia, v as resolveUserFacingMediaError, w as DEFAULT_MEDIA_SEND_ERROR, x as getMessageReplyConfig, y as MESSAGE_REPLY_LIMIT } from "./outbound-BJfhwrPg.js";
2
+ import { a as resolveQQBotAccount, i as resolveDefaultQQBotAccountId, n as applyQQBotAccountConfig, r as listQQBotAccountIds, t as DEFAULT_ACCOUNT_ID } from "./config-D6545NkC.js";
3
+ import { t as qqbotPlugin } from "./channel-N6Y_Rcjp.js";
4
+ import { C as debugLog, L as formatErrorMessage, S as debugError, o as getAccessToken } from "./sender-p-B14eLG.js";
5
+ import { t as qqbotSetupPlugin } from "./channel.setup-ByCRAe5H.js";
6
+ import { r as getFrameworkCommands, t as getRequestContext } from "./request-context-DXtpwWui.js";
7
+ import { callGatewayTool } from "openclaw/plugin-sdk/agent-harness-runtime";
8
+ //#region extensions/qqbot/src/engine/tools/channel-api.ts
9
+ /**
10
+ * QQ Channel API proxy tool core logic.
11
+ * QQ 频道 API 代理工具核心逻辑。
12
+ *
13
+ * Provides an authenticated HTTP proxy for the QQ Open Platform channel
14
+ * APIs. The caller (old tools/channel.ts shell) resolves the access
15
+ * token and passes it in; this module handles URL building, path
16
+ * validation, fetch, and structured response formatting.
17
+ */
18
+ const API_BASE = "https://api.sgroup.qq.com";
19
+ const DEFAULT_TIMEOUT_MS = 3e4;
20
+ /**
21
+ * JSON Schema for AI tool parameters (used by framework registration).
22
+ * AI Tool 参数的 JSON Schema 定义(供框架注册使用)。
23
+ */
24
+ const ChannelApiSchema = {
25
+ type: "object",
26
+ properties: {
27
+ method: {
28
+ type: "string",
29
+ description: "HTTP method. Allowed values: GET, POST, PUT, PATCH, DELETE.",
30
+ enum: [
31
+ "GET",
32
+ "POST",
33
+ "PUT",
34
+ "PATCH",
35
+ "DELETE"
36
+ ]
37
+ },
38
+ path: {
39
+ type: "string",
40
+ description: "API path without the host. Replace placeholders with concrete values. Examples: /users/@me/guilds, /guilds/{guild_id}/channels, /channels/{channel_id}."
41
+ },
42
+ body: {
43
+ type: "object",
44
+ description: "JSON request body for POST/PUT/PATCH requests. GET/DELETE usually do not need it."
45
+ },
46
+ query: {
47
+ type: "object",
48
+ description: "URL query parameters as key/value pairs appended to the path. For example, { \"limit\": \"100\", \"after\": \"0\" } becomes ?limit=100&after=0.",
49
+ additionalProperties: { type: "string" }
50
+ }
51
+ },
52
+ required: ["method", "path"]
53
+ };
54
+ /**
55
+ * Build the full API URL from base + path + query params.
56
+ * 拼接 API 基地址 + 路径 + 查询参数。
57
+ */
58
+ function buildUrl(path, query) {
59
+ let url = `${API_BASE}${path}`;
60
+ if (query && Object.keys(query).length > 0) {
61
+ const params = new URLSearchParams();
62
+ for (const [key, value] of Object.entries(query)) if (value !== void 0 && value !== null && value !== "") params.set(key, value);
63
+ const qs = params.toString();
64
+ if (qs) url += `?${qs}`;
65
+ }
66
+ return url;
67
+ }
68
+ /**
69
+ * Validate API path format; returns an error string or null if valid.
70
+ * 校验 API 路径格式,返回错误描述或 null(合法)。
71
+ */
72
+ function validatePath(path) {
73
+ if (!path.startsWith("/")) return "path must start with /";
74
+ if (path.includes("..") || path.includes("//")) return "path must not contain .. or //";
75
+ if (!/^\/[a-zA-Z0-9\-._~:@!$&'()*+,;=/%]+$/.test(path) && path !== "/") return "path contains unsupported characters";
76
+ return null;
77
+ }
78
+ function json$1(data) {
79
+ return {
80
+ content: [{
81
+ type: "text",
82
+ text: JSON.stringify(data, null, 2)
83
+ }],
84
+ details: data
85
+ };
86
+ }
87
+ /**
88
+ * Execute a channel API proxy request.
89
+ * 执行频道 API 代理请求。
90
+ *
91
+ * The caller provides the access token; this function handles
92
+ * URL building, path validation, HTTP fetch, and structured
93
+ * response formatting suitable for AI tool output.
94
+ */
95
+ async function executeChannelApi(params, options) {
96
+ if (!params.method) return json$1({ error: "method is required" });
97
+ if (!params.path) return json$1({ error: "path is required" });
98
+ const method = params.method.toUpperCase();
99
+ if (![
100
+ "GET",
101
+ "POST",
102
+ "PUT",
103
+ "PATCH",
104
+ "DELETE"
105
+ ].includes(method)) return json$1({ error: `Unsupported HTTP method: ${method}. Allowed values: GET, POST, PUT, PATCH, DELETE` });
106
+ const pathError = validatePath(params.path);
107
+ if (pathError) return json$1({ error: pathError });
108
+ if ((method === "GET" || method === "DELETE") && params.body && Object.keys(params.body).length > 0) debugLog(`[qqbot-channel-api] ${method} request with body, body will be ignored`);
109
+ try {
110
+ const url = buildUrl(params.path, params.query);
111
+ const headers = {
112
+ Authorization: `QQBot ${options.accessToken}`,
113
+ "Content-Type": "application/json"
114
+ };
115
+ const controller = new AbortController();
116
+ const timeoutId = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
117
+ const fetchOptions = {
118
+ method,
119
+ headers,
120
+ signal: controller.signal
121
+ };
122
+ if (params.body && [
123
+ "POST",
124
+ "PUT",
125
+ "PATCH"
126
+ ].includes(method)) fetchOptions.body = JSON.stringify(params.body);
127
+ debugLog(`[qqbot-channel-api] >>> ${method} ${url} (timeout: ${DEFAULT_TIMEOUT_MS}ms)`);
128
+ let res;
129
+ try {
130
+ res = await fetch(url, fetchOptions);
131
+ } catch (err) {
132
+ clearTimeout(timeoutId);
133
+ if (err instanceof Error && err.name === "AbortError") {
134
+ debugError(`[qqbot-channel-api] <<< Request timeout after ${DEFAULT_TIMEOUT_MS}ms`);
135
+ return json$1({
136
+ error: `Request timed out after ${DEFAULT_TIMEOUT_MS}ms`,
137
+ path: params.path
138
+ });
139
+ }
140
+ debugError("[qqbot-channel-api] <<< Network error:", err);
141
+ return json$1({
142
+ error: `Network error: ${formatErrorMessage(err)}`,
143
+ path: params.path
144
+ });
145
+ } finally {
146
+ clearTimeout(timeoutId);
147
+ }
148
+ debugLog(`[qqbot-channel-api] <<< Status: ${res.status} ${res.statusText}`);
149
+ const rawBody = await res.text();
150
+ if (!rawBody || rawBody.trim() === "") {
151
+ if (res.ok) return json$1({
152
+ success: true,
153
+ status: res.status,
154
+ path: params.path
155
+ });
156
+ return json$1({
157
+ error: `API returned ${res.status} ${res.statusText}`,
158
+ status: res.status,
159
+ path: params.path
160
+ });
161
+ }
162
+ let parsed;
163
+ try {
164
+ parsed = JSON.parse(rawBody);
165
+ } catch {
166
+ parsed = rawBody;
167
+ }
168
+ if (!res.ok) {
169
+ const errMsg = typeof parsed === "object" && parsed && "message" in parsed ? String(parsed.message) : `${res.status} ${res.statusText}`;
170
+ debugError(`[qqbot-channel-api] Error [${method} ${params.path}]: ${errMsg}`);
171
+ return json$1({
172
+ error: errMsg,
173
+ status: res.status,
174
+ path: params.path,
175
+ details: parsed
176
+ });
177
+ }
178
+ return json$1({
179
+ success: true,
180
+ status: res.status,
181
+ path: params.path,
182
+ data: parsed
183
+ });
184
+ } catch (err) {
185
+ return json$1({
186
+ error: formatErrorMessage(err),
187
+ path: params.path
188
+ });
189
+ }
190
+ }
191
+ //#endregion
192
+ //#region extensions/qqbot/src/bridge/tools/channel.ts
193
+ /**
194
+ * Register the QQ channel API proxy tool.
195
+ *
196
+ * The tool acts as an authenticated HTTP proxy for the QQ Open Platform
197
+ * channel APIs. Agents learn endpoint details from the skill docs and
198
+ * send requests through this proxy.
199
+ */
200
+ function registerChannelTool(api) {
201
+ const cfg = api.config;
202
+ if (!cfg) return;
203
+ const accountIds = listQQBotAccountIds(cfg);
204
+ if (accountIds.length === 0) return;
205
+ const firstAccountId = accountIds[0];
206
+ const account = resolveQQBotAccount(cfg, firstAccountId);
207
+ if (!account.appId || !account.clientSecret) return;
208
+ api.registerTool({
209
+ name: "qqbot_channel_api",
210
+ label: "QQBot Channel API",
211
+ description: "Authenticated HTTP proxy for QQ Open Platform channel APIs. Common endpoints: list guilds GET /users/@me/guilds | list channels GET /guilds/{guild_id}/channels | get channel GET /channels/{channel_id} | create channel POST /guilds/{guild_id}/channels | list members GET /guilds/{guild_id}/members?after=0&limit=100 | get member GET /guilds/{guild_id}/members/{user_id} | list threads GET /channels/{channel_id}/threads | create thread PUT /channels/{channel_id}/threads | create announce POST /guilds/{guild_id}/announces | create schedule POST /channels/{channel_id}/schedules. See the qqbot-channel skill for full endpoint details.",
212
+ parameters: ChannelApiSchema,
213
+ async execute(_toolCallId, params) {
214
+ return executeChannelApi(params, { accessToken: await getAccessToken(account.appId, account.clientSecret) });
215
+ }
216
+ }, { name: "qqbot_channel_api" });
217
+ }
218
+ //#endregion
219
+ //#region extensions/qqbot/src/engine/tools/remind-logic.ts
220
+ /**
221
+ * JSON Schema for AI tool parameters (used by framework registration).
222
+ * AI Tool 参数的 JSON Schema 定义(供框架注册使用)。
223
+ */
224
+ const RemindSchema = {
225
+ type: "object",
226
+ properties: {
227
+ action: {
228
+ type: "string",
229
+ description: "Action type. add=create a reminder, list=show reminders, remove=delete a reminder.",
230
+ enum: [
231
+ "add",
232
+ "list",
233
+ "remove"
234
+ ]
235
+ },
236
+ content: {
237
+ type: "string",
238
+ description: "Reminder content, for example \"drink water\" or \"join the meeting\". Required when action=add."
239
+ },
240
+ to: {
241
+ type: "string",
242
+ description: "Optional delivery target. The runtime automatically resolves the current conversation target, so you usually do not need to supply this. Direct-message format: qqbot:c2c:user_openid. Group format: qqbot:group:group_openid."
243
+ },
244
+ time: {
245
+ type: "string",
246
+ description: "Time description. Supported formats:\n1. Relative time, for example \"5m\", \"1h\", \"1h30m\", or \"2d\"\n2. Cron expression, for example \"0 8 * * *\" or \"0 9 * * 1-5\"\nValues containing spaces are treated as cron expressions; everything else is treated as a one-shot relative delay.\nRequired when action=add."
247
+ },
248
+ timezone: {
249
+ type: "string",
250
+ description: "Timezone used for cron reminders. Defaults to \"Asia/Shanghai\"."
251
+ },
252
+ name: {
253
+ type: "string",
254
+ description: "Optional reminder job name. Defaults to the first 20 characters of content."
255
+ },
256
+ jobId: {
257
+ type: "string",
258
+ description: "Job ID to remove. Required when action=remove; fetch it with list first."
259
+ }
260
+ },
261
+ required: ["action"]
262
+ };
263
+ /**
264
+ * Parse a relative time string into milliseconds.
265
+ * 解析相对时间字符串为毫秒数。
266
+ *
267
+ * Supports: "5m", "1h", "1h30m", "2d", "45s", plain number (as minutes).
268
+ *
269
+ * @returns Milliseconds or null if unparseable.
270
+ */
271
+ function parseRelativeTime(timeStr) {
272
+ const s = timeStr.toLowerCase();
273
+ if (/^\d+$/.test(s)) return Number.parseInt(s, 10) * 6e4;
274
+ let totalMs = 0;
275
+ let matched = false;
276
+ const regex = /(\d+(?:\.\d+)?)\s*(d|h|m|s)/g;
277
+ let match;
278
+ while ((match = regex.exec(s)) !== null) {
279
+ matched = true;
280
+ const value = Number.parseFloat(match[1]);
281
+ switch (match[2]) {
282
+ case "d":
283
+ totalMs += value * 864e5;
284
+ break;
285
+ case "h":
286
+ totalMs += value * 36e5;
287
+ break;
288
+ case "m":
289
+ totalMs += value * 6e4;
290
+ break;
291
+ case "s":
292
+ totalMs += value * 1e3;
293
+ break;
294
+ }
295
+ }
296
+ return matched ? Math.round(totalMs) : null;
297
+ }
298
+ /**
299
+ * Check whether a time string is a cron expression (3–6 space-separated fields).
300
+ * 判断时间字符串是否为 cron 表达式。
301
+ */
302
+ function isCronExpression(timeStr) {
303
+ const parts = timeStr.trim().split(/\s+/);
304
+ if (parts.length < 3 || parts.length > 6) return false;
305
+ return parts.every((p) => /^[0-9*?/,LW#-]/.test(p));
306
+ }
307
+ /**
308
+ * Generate a cron job name from reminder content (first 20 chars).
309
+ * 根据提醒内容生成 cron job 名称。
310
+ */
311
+ function generateJobName(content) {
312
+ const trimmed = content.trim();
313
+ return `Reminder: ${trimmed.length > 20 ? `${trimmed.slice(0, 20)}…` : trimmed}`;
314
+ }
315
+ /** Build the reminder system prompt sent to the AI. */
316
+ function buildReminderPrompt(content) {
317
+ return `You are a warm reminder assistant. Please remind the user about: ${content}. Requirements: (1) do not reply with HEARTBEAT_OK (2) do not explain who you are (3) output a direct and caring reminder message (4) you may add a short encouraging line (5) keep it within 2-3 sentences (6) use a small amount of emoji.`;
318
+ }
319
+ /** Build cron job params for a one-shot delayed reminder. */
320
+ function buildOnceJob(params, delayMs, to, accountId) {
321
+ const atMs = Date.now() + delayMs;
322
+ const content = params.content;
323
+ return {
324
+ action: "add",
325
+ job: {
326
+ name: params.name || generateJobName(content),
327
+ schedule: {
328
+ kind: "at",
329
+ atMs
330
+ },
331
+ sessionTarget: "isolated",
332
+ wakeMode: "now",
333
+ deleteAfterRun: true,
334
+ payload: {
335
+ kind: "agentTurn",
336
+ message: buildReminderPrompt(content)
337
+ },
338
+ delivery: {
339
+ mode: "announce",
340
+ channel: "qqbot",
341
+ to,
342
+ accountId
343
+ }
344
+ }
345
+ };
346
+ }
347
+ /** Build cron job params for a recurring cron reminder. */
348
+ function buildCronJob(params, to, accountId) {
349
+ const content = params.content;
350
+ const name = params.name || generateJobName(content);
351
+ const tz = params.timezone || "Asia/Shanghai";
352
+ return {
353
+ action: "add",
354
+ job: {
355
+ name,
356
+ schedule: {
357
+ kind: "cron",
358
+ expr: params.time.trim(),
359
+ tz
360
+ },
361
+ sessionTarget: "isolated",
362
+ wakeMode: "now",
363
+ payload: {
364
+ kind: "agentTurn",
365
+ message: buildReminderPrompt(content)
366
+ },
367
+ delivery: {
368
+ mode: "announce",
369
+ channel: "qqbot",
370
+ to,
371
+ accountId
372
+ }
373
+ }
374
+ };
375
+ }
376
+ /** Format a delay in milliseconds as a short string (e.g. "5m", "1h30m"). */
377
+ function formatDelay(ms) {
378
+ const totalSeconds = Math.round(ms / 1e3);
379
+ if (totalSeconds < 60) return `${totalSeconds}s`;
380
+ const totalMinutes = Math.round(ms / 6e4);
381
+ if (totalMinutes < 60) return `${totalMinutes}m`;
382
+ const hours = Math.floor(totalMinutes / 60);
383
+ const minutes = totalMinutes % 60;
384
+ if (minutes === 0) return `${hours}h`;
385
+ return `${hours}h${minutes}m`;
386
+ }
387
+ function json(data) {
388
+ return {
389
+ content: [{
390
+ type: "text",
391
+ text: JSON.stringify(data, null, 2)
392
+ }],
393
+ details: data
394
+ };
395
+ }
396
+ function formatSchedulerError(error) {
397
+ return error instanceof Error ? error.message : String(error);
398
+ }
399
+ function prepareRemindCronAction(params, ctx = {}) {
400
+ if (params.action === "list") return {
401
+ ok: true,
402
+ action: "list",
403
+ cronAction: { action: "list" }
404
+ };
405
+ if (params.action === "remove") {
406
+ if (!params.jobId) return {
407
+ ok: false,
408
+ error: "jobId is required when action=remove. Use action=list first."
409
+ };
410
+ return {
411
+ ok: true,
412
+ action: "remove",
413
+ cronAction: {
414
+ action: "remove",
415
+ jobId: params.jobId
416
+ }
417
+ };
418
+ }
419
+ if (!params.content) return {
420
+ ok: false,
421
+ error: "content is required when action=add"
422
+ };
423
+ const resolvedTo = params.to || ctx.fallbackTo;
424
+ if (!resolvedTo) return {
425
+ ok: false,
426
+ error: "Unable to determine delivery target for action=add. The reminder can only be scheduled from within an active conversation."
427
+ };
428
+ if (!params.time) return {
429
+ ok: false,
430
+ error: "time is required when action=add"
431
+ };
432
+ const resolvedAccountId = ctx.fallbackAccountId || "default";
433
+ if (isCronExpression(params.time)) return {
434
+ ok: true,
435
+ action: "add",
436
+ cronAction: buildCronJob(params, resolvedTo, resolvedAccountId),
437
+ summary: `⏰ Recurring reminder: "${params.content}" (${params.time}, tz=${params.timezone || "Asia/Shanghai"})`
438
+ };
439
+ const delayMs = parseRelativeTime(params.time);
440
+ if (delayMs == null) return {
441
+ ok: false,
442
+ error: `Could not parse time format: ${params.time}. Use values like 5m, 1h, 1h30m, or a cron expression.`
443
+ };
444
+ if (delayMs < 3e4) return {
445
+ ok: false,
446
+ error: "Reminder delay must be at least 30 seconds"
447
+ };
448
+ return {
449
+ ok: true,
450
+ action: "add",
451
+ cronAction: buildOnceJob(params, delayMs, resolvedTo, resolvedAccountId),
452
+ summary: `⏰ Reminder in ${formatDelay(delayMs)}: "${params.content}"`
453
+ };
454
+ }
455
+ async function executeScheduledRemind(params, ctx, scheduler) {
456
+ const plan = prepareRemindCronAction(params, ctx);
457
+ if (!plan.ok) return json({ error: plan.error });
458
+ try {
459
+ const cronResult = await scheduler(plan.cronAction);
460
+ return json({
461
+ ok: true,
462
+ action: plan.action,
463
+ summary: plan.summary,
464
+ cronResult
465
+ });
466
+ } catch (error) {
467
+ return json({
468
+ error: `Failed to run Gateway cron action: ${formatSchedulerError(error)}`,
469
+ action: plan.action
470
+ });
471
+ }
472
+ }
473
+ //#endregion
474
+ //#region extensions/qqbot/src/bridge/tools/remind.ts
475
+ const DEFAULT_GATEWAY_TIMEOUT_MS = 6e4;
476
+ function unexpectedCronParams(params) {
477
+ throw new Error(`Unsupported reminder cron action: ${JSON.stringify(params)}`);
478
+ }
479
+ const defaultDeps = { callCron: async (params) => {
480
+ switch (params.action) {
481
+ case "list": return await callGatewayTool("cron.list", { timeoutMs: DEFAULT_GATEWAY_TIMEOUT_MS }, {});
482
+ case "remove": return await callGatewayTool("cron.remove", { timeoutMs: DEFAULT_GATEWAY_TIMEOUT_MS }, { jobId: params.jobId });
483
+ case "add": return await callGatewayTool("cron.add", { timeoutMs: DEFAULT_GATEWAY_TIMEOUT_MS }, { job: params.job });
484
+ }
485
+ return unexpectedCronParams(params);
486
+ } };
487
+ function createRemindTool(toolContext = {}, deps = defaultDeps) {
488
+ return {
489
+ name: "qqbot_remind",
490
+ label: "QQBot Reminder",
491
+ ownerOnly: true,
492
+ description: "Create, list, and remove QQ reminders. This tool schedules Gateway cron jobs directly; do not call the cron tool after it succeeds.\nCreate: action=add, content=message, time=schedule (to is optional, resolved automatically from the current conversation)\nList: action=list\nRemove: action=remove, jobId=job id from list\nTime examples: \"5m\", \"1h\", \"0 8 * * *\"",
493
+ parameters: RemindSchema,
494
+ async execute(_toolCallId, params) {
495
+ if (toolContext.senderIsOwner !== true) return {
496
+ content: [{
497
+ type: "text",
498
+ text: JSON.stringify({ error: "QQ reminders require an owner-authorized sender." })
499
+ }],
500
+ details: { error: "QQ reminders require an owner-authorized sender." }
501
+ };
502
+ const ctx = getRequestContext();
503
+ return await executeScheduledRemind(params, {
504
+ fallbackTo: ctx?.target ?? toolContext.deliveryContext?.to,
505
+ fallbackAccountId: ctx?.accountId ?? toolContext.deliveryContext?.accountId
506
+ }, deps.callCron);
507
+ }
508
+ };
509
+ }
510
+ function registerRemindTool(api) {
511
+ api.registerTool((ctx) => createRemindTool(ctx), { name: "qqbot_remind" });
512
+ }
513
+ //#endregion
514
+ //#region extensions/qqbot/src/bridge/tools/index.ts
515
+ function registerQQBotTools(api) {
516
+ registerChannelTool(api);
517
+ registerRemindTool(api);
518
+ }
519
+ //#endregion
520
+ //#region extensions/qqbot/src/bridge/commands/framework-context-adapter.ts
521
+ /**
522
+ * Default queue snapshot used for framework-registered commands.
523
+ *
524
+ * Framework-side command dispatch runs outside the per-sender queue, so
525
+ * handlers observe an empty snapshot by design.
526
+ */
527
+ const DEFAULT_QUEUE_SNAPSHOT = {
528
+ totalPending: 0,
529
+ activeUsers: 0,
530
+ maxConcurrentUsers: 10,
531
+ senderPending: 0
532
+ };
533
+ function buildFrameworkSlashContext({ ctx, account, from, commandName }) {
534
+ const args = ctx.args ?? "";
535
+ const rawContent = args ? `/${commandName} ${args}` : `/${commandName}`;
536
+ return {
537
+ type: from.msgType,
538
+ senderId: ctx.senderId ?? "",
539
+ messageId: "",
540
+ eventTimestamp: (/* @__PURE__ */ new Date()).toISOString(),
541
+ receivedAt: Date.now(),
542
+ rawContent,
543
+ args,
544
+ accountId: account.accountId,
545
+ appId: account.appId,
546
+ accountConfig: account.config,
547
+ commandAuthorized: true,
548
+ queueSnapshot: { ...DEFAULT_QUEUE_SNAPSHOT }
549
+ };
550
+ }
551
+ //#endregion
552
+ //#region extensions/qqbot/src/bridge/commands/from-parser.ts
553
+ const MSG_TYPE_MAP = {
554
+ c2c: "c2c",
555
+ dm: "dm",
556
+ group: "group",
557
+ channel: "guild"
558
+ };
559
+ const TARGET_TYPE_MAP = {
560
+ c2c: "c2c",
561
+ dm: "dm",
562
+ group: "group",
563
+ channel: "channel"
564
+ };
565
+ function isFromKind(value) {
566
+ return value === "c2c" || value === "dm" || value === "group" || value === "channel";
567
+ }
568
+ /**
569
+ * Parse `ctx.from` into the structured fields the QQBot bridge expects.
570
+ *
571
+ * Unknown or missing prefixes fall back to c2c. The remainder after the first
572
+ * `:` is returned verbatim as the target id, matching what the previous inline
573
+ * implementation did.
574
+ */
575
+ function parseQQBotFrom(from) {
576
+ const stripped = (from ?? "").replace(/^qqbot:/iu, "");
577
+ const colonIdx = stripped.indexOf(":");
578
+ const rawPrefix = colonIdx === -1 ? stripped : stripped.slice(0, colonIdx);
579
+ const targetId = colonIdx === -1 ? stripped : stripped.slice(colonIdx + 1);
580
+ const kind = isFromKind(rawPrefix) ? rawPrefix : "c2c";
581
+ return {
582
+ msgType: MSG_TYPE_MAP[kind],
583
+ targetType: TARGET_TYPE_MAP[kind],
584
+ targetId
585
+ };
586
+ }
587
+ //#endregion
588
+ //#region extensions/qqbot/src/bridge/commands/result-dispatcher.ts
589
+ const UNEXPECTED_RESULT_TEXT = "⚠️ 命令返回了意外结果。";
590
+ function hasFilePath(value) {
591
+ return typeof value === "object" && value !== null && "filePath" in value && typeof value.filePath === "string";
592
+ }
593
+ function buildMediaTarget$1(account, from) {
594
+ return {
595
+ targetType: from.targetType,
596
+ targetId: from.targetId,
597
+ account
598
+ };
599
+ }
600
+ async function dispatchFrameworkSlashResult({ result, account, from, logger }) {
601
+ if (typeof result === "string") return { text: result };
602
+ if (hasFilePath(result)) {
603
+ const mediaCtx = buildMediaTarget$1(account, from);
604
+ try {
605
+ await sendDocument(mediaCtx, result.filePath, { allowQQBotDataDownloads: true });
606
+ } catch (err) {
607
+ logger?.warn(`framework slash file send failed: ${String(err)}`);
608
+ }
609
+ return { text: result.text };
610
+ }
611
+ return { text: UNEXPECTED_RESULT_TEXT };
612
+ }
613
+ //#endregion
614
+ //#region extensions/qqbot/src/bridge/commands/framework-registration.ts
615
+ function registerQQBotFrameworkCommands(api) {
616
+ for (const cmd of getFrameworkCommands()) api.registerCommand({
617
+ name: cmd.name,
618
+ description: cmd.description,
619
+ requireAuth: true,
620
+ acceptsArgs: true,
621
+ handler: async (ctx) => {
622
+ const from = parseQQBotFrom(ctx.from);
623
+ const account = resolveQQBotAccount(ctx.config, ctx.accountId ?? void 0);
624
+ const slashCtx = buildFrameworkSlashContext({
625
+ ctx,
626
+ account,
627
+ from,
628
+ commandName: cmd.name
629
+ });
630
+ return await dispatchFrameworkSlashResult({
631
+ result: await cmd.handler(slashCtx),
632
+ account,
633
+ from,
634
+ logger: api.logger
635
+ });
636
+ }
637
+ });
638
+ }
639
+ //#endregion
640
+ //#region extensions/qqbot/src/bridge/channel-entry.ts
641
+ function registerQQBotFull(api) {
642
+ registerQQBotTools(api);
643
+ registerQQBotFrameworkCommands(api);
644
+ }
645
+ //#endregion
646
+ export { DEFAULT_ACCOUNT_ID, DEFAULT_MEDIA_SEND_ERROR, MESSAGE_REPLY_LIMIT, OUTBOUND_ERROR_CODES, applyQQBotAccountConfig, buildMediaTarget, checkMessageReplyLimit, getFrameworkCommands, getMessageReplyConfig, getMessageReplyStats, listQQBotAccountIds, parseTarget, qqbotPlugin, qqbotSetupPlugin, recordMessageReply, registerChannelTool, registerQQBotFull, registerQQBotTools, registerRemindTool, resolveDefaultQQBotAccountId, resolveOutboundMediaPath, resolveQQBotAccount, resolveUserFacingMediaError, sendCronMessage, sendDocument, sendMedia, sendPhoto, sendProactiveMessage, sendText, sendVideoMsg, sendVoice, setOutboundAudioPort };