@mocrane/wecom 2026.2.5

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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +0 -0
  3. package/clawdbot.plugin.json +10 -0
  4. package/index.ts +28 -0
  5. package/openclaw.plugin.json +10 -0
  6. package/package.json +81 -0
  7. package/src/accounts.ts +72 -0
  8. package/src/agent/api-client.ts +336 -0
  9. package/src/agent/handler.ts +566 -0
  10. package/src/agent/index.ts +12 -0
  11. package/src/channel.ts +259 -0
  12. package/src/config/accounts.ts +99 -0
  13. package/src/config/index.ts +12 -0
  14. package/src/config/media.ts +14 -0
  15. package/src/config/network.ts +16 -0
  16. package/src/config/schema.ts +104 -0
  17. package/src/config-schema.ts +41 -0
  18. package/src/crypto/aes.ts +108 -0
  19. package/src/crypto/index.ts +24 -0
  20. package/src/crypto/signature.ts +43 -0
  21. package/src/crypto/xml.ts +49 -0
  22. package/src/crypto.test.ts +32 -0
  23. package/src/crypto.ts +176 -0
  24. package/src/http.ts +102 -0
  25. package/src/media.test.ts +55 -0
  26. package/src/media.ts +55 -0
  27. package/src/monitor/state.queue.test.ts +185 -0
  28. package/src/monitor/state.ts +514 -0
  29. package/src/monitor/types.ts +136 -0
  30. package/src/monitor.active.test.ts +239 -0
  31. package/src/monitor.integration.test.ts +207 -0
  32. package/src/monitor.ts +1802 -0
  33. package/src/monitor.webhook.test.ts +311 -0
  34. package/src/onboarding.ts +472 -0
  35. package/src/outbound.test.ts +143 -0
  36. package/src/outbound.ts +200 -0
  37. package/src/runtime.ts +14 -0
  38. package/src/shared/command-auth.ts +101 -0
  39. package/src/shared/index.ts +5 -0
  40. package/src/shared/xml-parser.test.ts +30 -0
  41. package/src/shared/xml-parser.ts +183 -0
  42. package/src/target.ts +80 -0
  43. package/src/types/account.ts +76 -0
  44. package/src/types/config.ts +88 -0
  45. package/src/types/constants.ts +42 -0
  46. package/src/types/global.d.ts +9 -0
  47. package/src/types/index.ts +38 -0
  48. package/src/types/message.ts +185 -0
  49. package/src/types.ts +159 -0
package/src/monitor.ts ADDED
@@ -0,0 +1,1802 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { pathToFileURL } from "node:url";
3
+
4
+ import crypto from "node:crypto";
5
+
6
+ import type { OpenClawConfig, PluginRuntime } from "openclaw/plugin-sdk";
7
+
8
+ import type { ResolvedAgentAccount } from "./types/index.js";
9
+ import type { ResolvedBotAccount } from "./types/index.js";
10
+ import type { WecomInboundMessage, WecomInboundQuote } from "./types.js";
11
+ import { decryptWecomEncrypted, encryptWecomPlaintext, verifyWecomSignature, computeWecomMsgSignature } from "./crypto.js";
12
+ import { getWecomRuntime } from "./runtime.js";
13
+ import { decryptWecomMedia, decryptWecomMediaWithHttp } from "./media.js";
14
+ import { WEBHOOK_PATHS } from "./types/constants.js";
15
+ import { handleAgentWebhook } from "./agent/index.js";
16
+ import { resolveWecomAccounts, resolveWecomEgressProxyUrl, resolveWecomMediaMaxBytes } from "./config/index.js";
17
+ import { wecomFetch } from "./http.js";
18
+ import { sendText as sendAgentText, sendMedia as sendAgentMedia, uploadMedia } from "./agent/api-client.js";
19
+ import axios from "axios";
20
+
21
+ /**
22
+ * **核心监控模块 (Monitor Loop)**
23
+ *
24
+ * 负责接收企业微信 Webhook 回调,处理消息流、媒体解密、消息去重防抖,并分发给 Agent 处理。
25
+ * 它是插件与企业微信交互的“心脏”,管理着所有会话的生命周期。
26
+ */
27
+
28
+ import type { WecomRuntimeEnv, WecomWebhookTarget, StreamState, PendingInbound, ActiveReplyState } from "./monitor/types.js";
29
+ import { monitorState, LIMITS } from "./monitor/state.js";
30
+ import { buildWecomUnauthorizedCommandPrompt, resolveWecomCommandAuthorization } from "./shared/command-auth.js";
31
+
32
+ // Global State
33
+ monitorState.streamStore.setFlushHandler((pending) => void flushPending(pending));
34
+
35
+ // Stores (convenience aliases)
36
+ const streamStore = monitorState.streamStore;
37
+ const activeReplyStore = monitorState.activeReplyStore;
38
+
39
+ // Target Registry
40
+ const webhookTargets = new Map<string, WecomWebhookTarget[]>();
41
+
42
+ // Agent 模式 target 存储
43
+ type AgentWebhookTarget = {
44
+ agent: ResolvedAgentAccount;
45
+ config: OpenClawConfig;
46
+ runtime: WecomRuntimeEnv;
47
+ // ...
48
+ };
49
+ const agentTargets = new Map<string, AgentWebhookTarget>();
50
+
51
+ const pendingInbounds = new Map<string, PendingInbound>();
52
+
53
+ const STREAM_MAX_BYTES = LIMITS.STREAM_MAX_BYTES;
54
+ const STREAM_MAX_DM_BYTES = 200_000;
55
+ const BOT_WINDOW_MS = 6 * 60 * 1000;
56
+ const BOT_SWITCH_MARGIN_MS = 30 * 1000;
57
+ // REQUEST_TIMEOUT_MS is available in LIMITS but defined locally in other functions, we can leave it or use LIMITS.REQUEST_TIMEOUT_MS
58
+ // Keeping local variables for now if they are used, or we can replace usages.
59
+ // The constants STREAM_TTL_MS and ACTIVE_REPLY_TTL_MS are internalized in state.ts, so we can remove them here.
60
+
61
+ /** 错误提示信息 */
62
+ const ERROR_HELP = "";
63
+
64
+ /**
65
+ * **normalizeWebhookPath (标准化 Webhook 路径)**
66
+ *
67
+ * 将用户配置的路径统一格式化为以 `/` 开头且不以 `/` 结尾的字符串。
68
+ * 例如: `wecom` -> `/wecom`
69
+ */
70
+ function normalizeWebhookPath(raw: string): string {
71
+ const trimmed = raw.trim();
72
+ if (!trimmed) return "/";
73
+ const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
74
+ if (withSlash.length > 1 && withSlash.endsWith("/")) return withSlash.slice(0, -1);
75
+ return withSlash;
76
+ }
77
+
78
+
79
+ /**
80
+ * **ensurePruneTimer (启动清理定时器)**
81
+ *
82
+ * 当有活跃的 Webhook Target 注册时,调用 MonitorState 启动自动清理任务。
83
+ * 清理任务包括:删除过期 Stream、移除无效 Active Reply URL 等。
84
+ */
85
+ function ensurePruneTimer() {
86
+ monitorState.startPruning();
87
+ }
88
+
89
+ /**
90
+ * **checkPruneTimer (检查并停止清理定时器)**
91
+ *
92
+ * 当没有活跃的 Webhook Target 时(Bot 和 Agent 均移除),停止清理任务以节省资源。
93
+ */
94
+ function checkPruneTimer() {
95
+ const hasBot = webhookTargets.size > 0;
96
+ const hasAgent = agentTargets.size > 0;
97
+ if (!hasBot && !hasAgent) {
98
+ monitorState.stopPruning();
99
+ }
100
+ }
101
+
102
+
103
+
104
+
105
+ function truncateUtf8Bytes(text: string, maxBytes: number): string {
106
+ const buf = Buffer.from(text, "utf8");
107
+ if (buf.length <= maxBytes) return text;
108
+ const slice = buf.subarray(buf.length - maxBytes);
109
+ return slice.toString("utf8");
110
+ }
111
+
112
+ /**
113
+ * **jsonOk (返回 JSON 响应)**
114
+ *
115
+ * 辅助函数:向企业微信服务器返回 HTTP 200 及 JSON 内容。
116
+ * 注意企业微信要求加密内容以 Content-Type: text/plain 返回,但这里为了通用性使用了标准 JSON 响应,
117
+ * 并通过 Content-Type 修正适配。
118
+ */
119
+ function jsonOk(res: ServerResponse, body: unknown): void {
120
+ res.statusCode = 200;
121
+ // WeCom's reference implementation returns the encrypted JSON as text/plain.
122
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
123
+ res.end(JSON.stringify(body));
124
+ }
125
+
126
+ /**
127
+ * **readJsonBody (读取 JSON 请求体)**
128
+ *
129
+ * 异步读取 HTTP 请求体并解析为 JSON。包含大小限制检查,防止大包攻击。
130
+ *
131
+ * @param req HTTP 请求对象
132
+ * @param maxBytes 最大允许字节数
133
+ */
134
+ async function readJsonBody(req: IncomingMessage, maxBytes: number) {
135
+ const chunks: Buffer[] = [];
136
+ let total = 0;
137
+ return await new Promise<{ ok: boolean; value?: unknown; error?: string }>((resolve) => {
138
+ req.on("data", (chunk: Buffer) => {
139
+ total += chunk.length;
140
+ if (total > maxBytes) {
141
+ resolve({ ok: false, error: "payload too large" });
142
+ req.destroy();
143
+ return;
144
+ }
145
+ chunks.push(chunk);
146
+ });
147
+ req.on("end", () => {
148
+ try {
149
+ const raw = Buffer.concat(chunks).toString("utf8");
150
+ if (!raw.trim()) {
151
+ resolve({ ok: false, error: "empty payload" });
152
+ return;
153
+ }
154
+ resolve({ ok: true, value: JSON.parse(raw) as unknown });
155
+ } catch (err) {
156
+ resolve({ ok: false, error: err instanceof Error ? err.message : String(err) });
157
+ }
158
+ });
159
+ req.on("error", (err) => {
160
+ resolve({ ok: false, error: err instanceof Error ? err.message : String(err) });
161
+ });
162
+ });
163
+ }
164
+
165
+ /**
166
+ * **buildEncryptedJsonReply (构建加密回复)**
167
+ *
168
+ * 将明文 JSON 包装成企业微信要求的加密 XML/JSON 格式(此处实际返回 JSON 结构)。
169
+ * 包含签名计算逻辑。
170
+ */
171
+ function buildEncryptedJsonReply(params: {
172
+ account: ResolvedBotAccount;
173
+ plaintextJson: unknown;
174
+ nonce: string;
175
+ timestamp: string;
176
+ }): { encrypt: string; msgsignature: string; timestamp: string; nonce: string } {
177
+ const plaintext = JSON.stringify(params.plaintextJson ?? {});
178
+ const encrypt = encryptWecomPlaintext({
179
+ encodingAESKey: params.account.encodingAESKey ?? "",
180
+ receiveId: params.account.receiveId ?? "",
181
+ plaintext,
182
+ });
183
+ const msgsignature = computeWecomMsgSignature({
184
+ token: params.account.token ?? "",
185
+ timestamp: params.timestamp,
186
+ nonce: params.nonce,
187
+ encrypt,
188
+ });
189
+ return {
190
+ encrypt,
191
+ msgsignature,
192
+ timestamp: params.timestamp,
193
+ nonce: params.nonce,
194
+ };
195
+ }
196
+
197
+ function resolveQueryParams(req: IncomingMessage): URLSearchParams {
198
+ const url = new URL(req.url ?? "/", "http://localhost");
199
+ return url.searchParams;
200
+ }
201
+
202
+ function resolvePath(req: IncomingMessage): string {
203
+ const url = new URL(req.url ?? "/", "http://localhost");
204
+ return normalizeWebhookPath(url.pathname || "/");
205
+ }
206
+
207
+ function resolveSignatureParam(params: URLSearchParams): string {
208
+ return (
209
+ params.get("msg_signature") ??
210
+ params.get("msgsignature") ??
211
+ params.get("signature") ??
212
+ ""
213
+ );
214
+ }
215
+
216
+ function buildStreamPlaceholderReply(params: {
217
+ streamId: string;
218
+ placeholderContent?: string;
219
+ }): { msgtype: "stream"; stream: { id: string; finish: boolean; content: string } } {
220
+ const content = params.placeholderContent?.trim() || "1";
221
+ return {
222
+ msgtype: "stream",
223
+ stream: {
224
+ id: params.streamId,
225
+ finish: false,
226
+ // Spec: "第一次回复内容为 1" works as a minimal placeholder.
227
+ content,
228
+ },
229
+ };
230
+ }
231
+
232
+ function buildStreamImmediateTextReply(params: { streamId: string; content: string }): { msgtype: "stream"; stream: { id: string; finish: boolean; content: string } } {
233
+ return {
234
+ msgtype: "stream",
235
+ stream: {
236
+ id: params.streamId,
237
+ finish: true,
238
+ content: params.content.trim() || "1",
239
+ },
240
+ };
241
+ }
242
+
243
+ function buildStreamTextPlaceholderReply(params: { streamId: string; content: string }): { msgtype: "stream"; stream: { id: string; finish: boolean; content: string } } {
244
+ return {
245
+ msgtype: "stream",
246
+ stream: {
247
+ id: params.streamId,
248
+ finish: false,
249
+ content: params.content.trim() || "1",
250
+ },
251
+ };
252
+ }
253
+
254
+ function buildStreamReplyFromState(state: StreamState): { msgtype: "stream"; stream: { id: string; finish: boolean; content: string } } {
255
+ const content = truncateUtf8Bytes(state.content, STREAM_MAX_BYTES);
256
+ // Images handled? The original code had image logic.
257
+ // Ensure we return message item if images exist
258
+ return {
259
+ msgtype: "stream",
260
+ stream: {
261
+ id: state.streamId,
262
+ finish: state.finished,
263
+ content,
264
+ ...(state.finished && state.images?.length ? {
265
+ msg_item: state.images.map(img => ({
266
+ msgtype: "image",
267
+ image: { base64: img.base64, md5: img.md5 }
268
+ }))
269
+ } : {})
270
+ },
271
+ };
272
+ }
273
+
274
+ function appendDmContent(state: StreamState, text: string): void {
275
+ const next = state.dmContent ? `${state.dmContent}\n\n${text}`.trim() : text.trim();
276
+ state.dmContent = truncateUtf8Bytes(next, STREAM_MAX_DM_BYTES);
277
+ }
278
+
279
+ function computeTaskKey(target: WecomWebhookTarget, msg: WecomInboundMessage): string | undefined {
280
+ const msgid = msg.msgid ? String(msg.msgid) : "";
281
+ if (!msgid) return undefined;
282
+ const aibotid = String((msg as any).aibotid ?? "unknown").trim() || "unknown";
283
+ return `bot:${target.account.accountId}:${aibotid}:${msgid}`;
284
+ }
285
+
286
+ function resolveAgentAccountOrUndefined(cfg: OpenClawConfig): ResolvedAgentAccount | undefined {
287
+ const agent = resolveWecomAccounts(cfg).agent;
288
+ return agent?.configured ? agent : undefined;
289
+ }
290
+
291
+ function buildFallbackPrompt(params: {
292
+ kind: "media" | "timeout" | "error";
293
+ agentConfigured: boolean;
294
+ userId?: string;
295
+ filename?: string;
296
+ chatType?: "group" | "direct";
297
+ }): string {
298
+ const who = params.userId ? `(${params.userId})` : "";
299
+ const scope = params.chatType === "group" ? "群聊" : params.chatType === "direct" ? "私聊" : "会话";
300
+ if (!params.agentConfigured) {
301
+ return `${scope}中需要通过应用私信发送${params.filename ? `(${params.filename})` : ""},但管理员尚未配置企业微信自建应用(Agent)通道。请联系管理员配置后再试。${who}`.trim();
302
+ }
303
+ if (!params.userId) {
304
+ return `${scope}中需要通过应用私信兜底发送${params.filename ? `(${params.filename})` : ""},但本次回调未能识别触发者 userid(请检查企微回调字段 from.userid / fromuserid)。请联系管理员排查配置。`.trim();
305
+ }
306
+ if (params.kind === "media") {
307
+ return `已生成文件${params.filename ? `(${params.filename})` : ""},将通过应用私信发送给你。${who}`.trim();
308
+ }
309
+ if (params.kind === "timeout") {
310
+ return `内容较长,为避免超时,后续内容将通过应用私信发送给你。${who}`.trim();
311
+ }
312
+ return `交付出现异常,已尝试通过应用私信发送给你。${who}`.trim();
313
+ }
314
+
315
+ async function sendBotFallbackPromptNow(params: { streamId: string; text: string }): Promise<void> {
316
+ const responseUrl = getActiveReplyUrl(params.streamId);
317
+ if (!responseUrl) {
318
+ throw new Error("no response_url(无法主动推送群内提示)");
319
+ }
320
+ await useActiveReplyOnce(params.streamId, async ({ responseUrl, proxyUrl }) => {
321
+ const payload = {
322
+ msgtype: "stream",
323
+ stream: {
324
+ id: params.streamId,
325
+ finish: true,
326
+ content: truncateUtf8Bytes(params.text, STREAM_MAX_BYTES) || "1",
327
+ },
328
+ };
329
+ const res = await wecomFetch(
330
+ responseUrl,
331
+ {
332
+ method: "POST",
333
+ headers: { "Content-Type": "application/json" },
334
+ body: JSON.stringify(payload),
335
+ },
336
+ { proxyUrl, timeoutMs: LIMITS.REQUEST_TIMEOUT_MS },
337
+ );
338
+ if (!res.ok) {
339
+ throw new Error(`fallback prompt push failed: ${res.status}`);
340
+ }
341
+ });
342
+ }
343
+
344
+ async function sendAgentDmText(params: {
345
+ agent: ResolvedAgentAccount;
346
+ userId: string;
347
+ text: string;
348
+ core: PluginRuntime;
349
+ }): Promise<void> {
350
+ const chunks = params.core.channel.text.chunkText(params.text, 20480);
351
+ for (const chunk of chunks) {
352
+ const trimmed = chunk.trim();
353
+ if (!trimmed) continue;
354
+ await sendAgentText({ agent: params.agent, toUser: params.userId, text: trimmed });
355
+ }
356
+ }
357
+
358
+ async function sendAgentDmMedia(params: {
359
+ agent: ResolvedAgentAccount;
360
+ userId: string;
361
+ mediaUrlOrPath: string;
362
+ contentType?: string;
363
+ filename: string;
364
+ }): Promise<void> {
365
+ let buffer: Buffer;
366
+ let inferredContentType = params.contentType;
367
+
368
+ const looksLikeUrl = /^https?:\/\//i.test(params.mediaUrlOrPath);
369
+ if (looksLikeUrl) {
370
+ const res = await fetch(params.mediaUrlOrPath, { signal: AbortSignal.timeout(30_000) });
371
+ if (!res.ok) throw new Error(`media download failed: ${res.status}`);
372
+ buffer = Buffer.from(await res.arrayBuffer());
373
+ inferredContentType = inferredContentType || res.headers.get("content-type") || "application/octet-stream";
374
+ } else {
375
+ const fs = await import("node:fs/promises");
376
+ buffer = await fs.readFile(params.mediaUrlOrPath);
377
+ }
378
+
379
+ let mediaType: "image" | "voice" | "video" | "file" = "file";
380
+ const ct = (inferredContentType || "").toLowerCase();
381
+ if (ct.startsWith("image/")) mediaType = "image";
382
+ else if (ct.startsWith("audio/")) mediaType = "voice";
383
+ else if (ct.startsWith("video/")) mediaType = "video";
384
+
385
+ const mediaId = await uploadMedia({
386
+ agent: params.agent,
387
+ type: mediaType,
388
+ buffer,
389
+ filename: params.filename,
390
+ });
391
+ await sendAgentMedia({
392
+ agent: params.agent,
393
+ toUser: params.userId,
394
+ mediaId,
395
+ mediaType,
396
+ });
397
+ }
398
+
399
+ function extractLocalImagePathsFromText(params: {
400
+ text: string;
401
+ mustAlsoAppearIn: string;
402
+ }): string[] {
403
+ const text = params.text;
404
+ const mustAlsoAppearIn = params.mustAlsoAppearIn;
405
+ if (!text.trim()) return [];
406
+
407
+ // Conservative: only accept common macOS absolute paths for images.
408
+ // Also require that the exact path appeared in the user's original message to prevent exfil.
409
+ const exts = "(png|jpg|jpeg|gif|webp|bmp)";
410
+ const re = new RegExp(String.raw`(\/(?:Users|tmp)\/[^\s"'<>]+?\.${exts})`, "gi");
411
+ const found = new Set<string>();
412
+ let m: RegExpExecArray | null;
413
+ while ((m = re.exec(text))) {
414
+ const p = m[1];
415
+ if (!p) continue;
416
+ if (!mustAlsoAppearIn.includes(p)) continue;
417
+ found.add(p);
418
+ }
419
+ return Array.from(found);
420
+ }
421
+
422
+ function extractLocalFilePathsFromText(text: string): string[] {
423
+ if (!text.trim()) return [];
424
+
425
+ // Conservative: only accept common macOS absolute paths.
426
+ // This is primarily for “send local file” style requests (operator/debug usage).
427
+ const re = new RegExp(String.raw`(\/(?:Users|tmp)\/[^\s"'<>]+)`, "g");
428
+ const found = new Set<string>();
429
+ let m: RegExpExecArray | null;
430
+ while ((m = re.exec(text))) {
431
+ const p = m[1];
432
+ if (!p) continue;
433
+ found.add(p);
434
+ }
435
+ return Array.from(found);
436
+ }
437
+
438
+ function guessContentTypeFromPath(filePath: string): string | undefined {
439
+ const ext = filePath.split(".").pop()?.toLowerCase();
440
+ if (!ext) return undefined;
441
+ const map: Record<string, string> = {
442
+ png: "image/png",
443
+ jpg: "image/jpeg",
444
+ jpeg: "image/jpeg",
445
+ gif: "image/gif",
446
+ webp: "image/webp",
447
+ bmp: "image/bmp",
448
+ pdf: "application/pdf",
449
+ txt: "text/plain",
450
+ md: "text/markdown",
451
+ json: "application/json",
452
+ zip: "application/zip",
453
+ };
454
+ return map[ext];
455
+ }
456
+
457
+ function looksLikeSendLocalFileIntent(rawBody: string): boolean {
458
+ const t = rawBody.trim();
459
+ if (!t) return false;
460
+ // Heuristic: treat as “send file” intent only when there is an explicit local path AND a send-ish verb.
461
+ // This avoids accidentally sending a file when the user is merely referencing a path.
462
+ return /(发送|发给|发到|转发|把.*发|把.*发送|帮我发|给我发)/.test(t);
463
+ }
464
+
465
+ function storeActiveReply(streamId: string, responseUrl?: string, proxyUrl?: string): void {
466
+ activeReplyStore.store(streamId, responseUrl, proxyUrl);
467
+ }
468
+
469
+ function getActiveReplyUrl(streamId: string): string | undefined {
470
+ return activeReplyStore.getUrl(streamId);
471
+ }
472
+
473
+ async function useActiveReplyOnce(streamId: string, fn: (params: { responseUrl: string; proxyUrl?: string }) => Promise<void>): Promise<void> {
474
+ return activeReplyStore.use(streamId, fn);
475
+ }
476
+
477
+
478
+ function logVerbose(target: WecomWebhookTarget, message: string): void {
479
+ const should =
480
+ target.core.logging?.shouldLogVerbose?.() ??
481
+ (() => {
482
+ try {
483
+ return getWecomRuntime().logging.shouldLogVerbose();
484
+ } catch {
485
+ return false;
486
+ }
487
+ })();
488
+ if (!should) return;
489
+ target.runtime.log?.(`[wecom] ${message}`);
490
+ }
491
+
492
+ function logInfo(target: WecomWebhookTarget, message: string): void {
493
+ target.runtime.log?.(`[wecom] ${message}`);
494
+ }
495
+
496
+ function resolveWecomSenderUserId(msg: WecomInboundMessage): string | undefined {
497
+ const direct = msg.from?.userid?.trim();
498
+ if (direct) return direct;
499
+ const legacy = String((msg as any).fromuserid ?? (msg as any).from_userid ?? (msg as any).fromUserId ?? "").trim();
500
+ return legacy || undefined;
501
+ }
502
+
503
+ function parseWecomPlainMessage(raw: string): WecomInboundMessage {
504
+ const parsed = JSON.parse(raw) as unknown;
505
+ if (!parsed || typeof parsed !== "object") {
506
+ return {};
507
+ }
508
+ return parsed as WecomInboundMessage;
509
+ }
510
+
511
+ type InboundResult = {
512
+ body: string;
513
+ media?: {
514
+ buffer: Buffer;
515
+ contentType: string;
516
+ filename: string;
517
+ };
518
+ };
519
+
520
+ /**
521
+ * **processInboundMessage (处理接收消息)**
522
+ *
523
+ * 解析企业微信传入的消息体。
524
+ * 主要职责:
525
+ * 1. 识别媒体消息(Image/File/Mixed)。
526
+ * 2. 如果存在媒体文件,调用 `media.ts` 进行解密和下载。
527
+ * 3. 构造统一的 `InboundResult` 供后续 Agent 处理。
528
+ *
529
+ * @param target Webhook 目标配置
530
+ * @param msg 企业微信原始消息对象
531
+ */
532
+ async function processInboundMessage(target: WecomWebhookTarget, msg: WecomInboundMessage): Promise<InboundResult> {
533
+ const msgtype = String(msg.msgtype ?? "").toLowerCase();
534
+ const aesKey = target.account.encodingAESKey;
535
+ const maxBytes = resolveWecomMediaMaxBytes(target.config);
536
+ const proxyUrl = resolveWecomEgressProxyUrl(target.config);
537
+
538
+ // 图片消息处理:如果存在 url 且配置了 aesKey,则尝试解密下载
539
+ if (msgtype === "image") {
540
+ const url = String((msg as any).image?.url ?? "").trim();
541
+ if (url && aesKey) {
542
+ try {
543
+ const buf = await decryptWecomMediaWithHttp(url, aesKey, { maxBytes, http: { proxyUrl } });
544
+ return {
545
+ body: "[image]",
546
+ media: {
547
+ buffer: buf,
548
+ contentType: "image/jpeg", // WeCom images are usually generic; safest assumption or could act as generic
549
+ filename: "image.jpg",
550
+ }
551
+ };
552
+ } catch (err) {
553
+ target.runtime.error?.(`Failed to decrypt inbound image: ${String(err)}`);
554
+ target.runtime.error?.(
555
+ `图片解密失败: ${String(err)}; 可调大 channels.wecom.media.maxBytes(当前=${maxBytes})例如:openclaw config set channels.wecom.media.maxBytes ${50 * 1024 * 1024}`,
556
+ );
557
+ return { body: `[image] (decryption failed: ${typeof err === 'object' && err ? (err as any).message : String(err)})` };
558
+ }
559
+ }
560
+ }
561
+
562
+ if (msgtype === "file") {
563
+ const url = String((msg as any).file?.url ?? "").trim();
564
+ if (url && aesKey) {
565
+ try {
566
+ const buf = await decryptWecomMediaWithHttp(url, aesKey, { maxBytes, http: { proxyUrl } });
567
+ return {
568
+ body: "[file]",
569
+ media: {
570
+ buffer: buf,
571
+ contentType: "application/octet-stream",
572
+ filename: "file.bin", // WeCom doesn't guarantee filename in webhook payload always, defaulting
573
+ }
574
+ };
575
+ } catch (err) {
576
+ target.runtime.error?.(
577
+ `Failed to decrypt inbound file: ${String(err)}; 可调大 channels.wecom.media.maxBytes(当前=${maxBytes})例如:openclaw config set channels.wecom.media.maxBytes ${50 * 1024 * 1024}`,
578
+ );
579
+ return { body: `[file] (decryption failed: ${typeof err === 'object' && err ? (err as any).message : String(err)})` };
580
+ }
581
+ }
582
+ }
583
+
584
+ // Mixed message handling: extract first media if available
585
+ if (msgtype === "mixed") {
586
+ const items = (msg as any).mixed?.msg_item;
587
+ if (Array.isArray(items)) {
588
+ let foundMedia: InboundResult["media"] | undefined = undefined;
589
+ let bodyParts: string[] = [];
590
+
591
+ for (const item of items) {
592
+ const t = String(item.msgtype ?? "").toLowerCase();
593
+ if (t === "text") {
594
+ const content = String(item.text?.content ?? "").trim();
595
+ if (content) bodyParts.push(content);
596
+ } else if ((t === "image" || t === "file") && !foundMedia && aesKey) {
597
+ // Found first media, try to download
598
+ const url = String(item[t]?.url ?? "").trim();
599
+ if (url) {
600
+ try {
601
+ const buf = await decryptWecomMediaWithHttp(url, aesKey, { maxBytes, http: { proxyUrl } });
602
+ foundMedia = {
603
+ buffer: buf,
604
+ contentType: t === "image" ? "image/jpeg" : "application/octet-stream",
605
+ filename: t === "image" ? "image.jpg" : "file.bin"
606
+ };
607
+ bodyParts.push(`[${t}]`);
608
+ } catch (err) {
609
+ target.runtime.error?.(
610
+ `Failed to decrypt mixed ${t}: ${String(err)}; 可调大 channels.wecom.media.maxBytes(当前=${maxBytes})例如:openclaw config set channels.wecom.media.maxBytes ${50 * 1024 * 1024}`,
611
+ );
612
+ bodyParts.push(`[${t}] (decryption failed)`);
613
+ }
614
+ } else {
615
+ bodyParts.push(`[${t}]`);
616
+ }
617
+ } else {
618
+ // Other items or already found media -> just placeholder
619
+ bodyParts.push(`[${t}]`);
620
+ }
621
+ }
622
+ return {
623
+ body: bodyParts.join("\n"),
624
+ media: foundMedia
625
+ };
626
+ }
627
+ }
628
+
629
+ return { body: buildInboundBody(msg) };
630
+ }
631
+
632
+
633
+ /**
634
+ * Flush pending inbound messages after debounce timeout.
635
+ * Merges all buffered message contents and starts agent processing.
636
+ */
637
+ /**
638
+ * **flushPending (刷新待处理消息 / 核心 Agent 触发点)**
639
+ *
640
+ * 当防抖计时器结束时被调用。
641
+ * 核心逻辑:
642
+ * 1. 聚合所有 pending 的消息内容(用于上下文)。
643
+ * 2. 获取 PluginRuntime。
644
+ * 3. 标记 Stream 为 Started。
645
+ * 4. 调用 `startAgentForStream` 启动 Agent 流程。
646
+ * 5. 处理异常并更新 Stream 状态为 Error。
647
+ */
648
+ async function flushPending(pending: PendingInbound): Promise<void> {
649
+ const { streamId, target, msg, contents, msgids, conversationKey, batchKey } = pending;
650
+
651
+ // Merge all message contents (each is already formatted by buildInboundBody)
652
+ const mergedContents = contents.filter(c => c.trim()).join("\n").trim();
653
+
654
+ let core: PluginRuntime | null = null;
655
+ try {
656
+ core = getWecomRuntime();
657
+ } catch (err) {
658
+ logVerbose(target, `flush pending: runtime not ready: ${String(err)}`);
659
+ streamStore.markFinished(streamId);
660
+ logInfo(target, `queue: runtime not ready,结束批次并推进 streamId=${streamId}`);
661
+ streamStore.onStreamFinished(streamId);
662
+ return;
663
+ }
664
+
665
+ if (core) {
666
+ streamStore.markStarted(streamId);
667
+ const enrichedTarget: WecomWebhookTarget = { ...target, core };
668
+ logInfo(target, `flush pending: start batch streamId=${streamId} batchKey=${batchKey} conversationKey=${conversationKey} mergedCount=${contents.length}`);
669
+ logVerbose(target, `防抖结束: 开始处理聚合消息 数量=${contents.length} streamId=${streamId}`);
670
+
671
+ // Pass the first msg (with its media structure), and mergedContents for multi-message context
672
+ startAgentForStream({
673
+ target: enrichedTarget,
674
+ accountId: target.account.accountId,
675
+ msg,
676
+ streamId,
677
+ mergedContents: contents.length > 1 ? mergedContents : undefined,
678
+ mergedMsgids: msgids.length > 1 ? msgids : undefined,
679
+ }).catch((err) => {
680
+ streamStore.updateStream(streamId, (state) => {
681
+ state.error = err instanceof Error ? err.message : String(err);
682
+ state.content = state.content || `Error: ${state.error}`;
683
+ state.finished = true;
684
+ });
685
+ target.runtime.error?.(`[${target.account.accountId}] wecom agent failed (处理失败): ${String(err)}`);
686
+ streamStore.onStreamFinished(streamId);
687
+ });
688
+ }
689
+ }
690
+
691
+
692
+ /**
693
+ * **waitForStreamContent (等待流内容)**
694
+ *
695
+ * 用于长轮询 (Long Polling) 场景:阻塞等待流输出内容,直到超时或流结束。
696
+ * 这保证了用户能尽快收到第一批响应,而不是空转。
697
+ */
698
+ async function waitForStreamContent(streamId: string, maxWaitMs: number): Promise<void> {
699
+ if (maxWaitMs <= 0) return;
700
+ const startedAt = Date.now();
701
+ await new Promise<void>((resolve) => {
702
+ const tick = () => {
703
+ const state = streamStore.getStream(streamId);
704
+ if (!state) return resolve();
705
+ if (state.error || state.finished) return resolve();
706
+ if (state.content.trim()) return resolve();
707
+ if (Date.now() - startedAt >= maxWaitMs) return resolve();
708
+ setTimeout(tick, 25);
709
+ };
710
+ tick();
711
+ });
712
+ }
713
+
714
+ /**
715
+ * **startAgentForStream (启动 Agent 处理流程)**
716
+ *
717
+ * 将接收到的(或聚合的)消息转换为 OpenClaw 内部格式,并分发给对应的 Agent。
718
+ * 包含:
719
+ * 1. 消息解密与媒体保存。
720
+ * 2. 路由解析 (Agent Route)。
721
+ * 3. 鉴权 (Command Authorization)。
722
+ * 4. 会话记录 (Session Recording)。
723
+ * 5. 触发 Agent 响应 (Dispatch Reply)。
724
+ * 6. 处理 Agent 输出(包括文本、Markdown 表格转换、<think> 标签保护、模板卡片识别)。
725
+ */
726
+ async function startAgentForStream(params: {
727
+ target: WecomWebhookTarget;
728
+ accountId: string;
729
+ msg: WecomInboundMessage;
730
+ streamId: string;
731
+ mergedContents?: string; // Combined content from debounced messages
732
+ mergedMsgids?: string[];
733
+ }): Promise<void> {
734
+ const { target, msg, streamId } = params;
735
+ const core = target.core;
736
+ const config = target.config;
737
+ const account = target.account;
738
+
739
+ const userid = resolveWecomSenderUserId(msg) || "unknown";
740
+ const chatType = msg.chattype === "group" ? "group" : "direct";
741
+ const chatId = msg.chattype === "group" ? (msg.chatid?.trim() || "unknown") : userid;
742
+ const taskKey = computeTaskKey(target, msg);
743
+ const aibotid = String((msg as any).aibotid ?? "").trim() || undefined;
744
+
745
+ // 更新 Stream 状态:记录上下文信息(用户ID、ChatType等)
746
+ streamStore.updateStream(streamId, (s) => {
747
+ s.userId = userid;
748
+ s.chatType = chatType === "group" ? "group" : "direct";
749
+ s.chatId = chatId;
750
+ s.taskKey = taskKey;
751
+ s.aibotid = aibotid;
752
+ });
753
+
754
+ // 1. 处理入站消息 (Decrypt media if any)
755
+ // 解析消息体,若是图片/文件则自动解密
756
+ let { body: rawBody, media } = await processInboundMessage(target, msg);
757
+
758
+ // 若存在从防抖逻辑聚合来的多条消息内容,则覆盖 rawBody
759
+ if (params.mergedContents) {
760
+ rawBody = params.mergedContents;
761
+ }
762
+
763
+ // P0: 群聊/私聊里“让 Bot 发送本机图片/文件路径”的场景,优先走 Bot 原会话交付(图片),
764
+ // 非图片文件则走 Agent 私信兜底,并确保 Bot 会话里有中文提示。
765
+ //
766
+ // 典型背景:Agent 主动发群 chatId(wr/wc...)在很多情况下会 86008,无论怎么“修复”都发不出去;
767
+ // 这种请求如果能被动回复图片,就必须由 Bot 在群内交付。
768
+ const directLocalPaths = extractLocalFilePathsFromText(rawBody);
769
+ if (directLocalPaths.length) {
770
+ logVerbose(
771
+ target,
772
+ `local-path: 检测到用户消息包含本机路径 count=${directLocalPaths.length} intent=${looksLikeSendLocalFileIntent(rawBody)}`,
773
+ );
774
+ }
775
+ if (directLocalPaths.length && looksLikeSendLocalFileIntent(rawBody)) {
776
+ const fs = await import("node:fs/promises");
777
+ const pathModule = await import("node:path");
778
+ const imageExts = new Set(["png", "jpg", "jpeg", "gif", "webp", "bmp"]);
779
+
780
+ const imagePaths: string[] = [];
781
+ const otherPaths: string[] = [];
782
+ for (const p of directLocalPaths) {
783
+ const ext = pathModule.extname(p).slice(1).toLowerCase();
784
+ if (imageExts.has(ext)) imagePaths.push(p);
785
+ else otherPaths.push(p);
786
+ }
787
+
788
+ // 1) 图片:优先 Bot 群内/原会话交付(被动/流式 msg_item)
789
+ if (imagePaths.length > 0 && otherPaths.length === 0) {
790
+ const loaded: Array<{ base64: string; md5: string; path: string }> = [];
791
+ for (const p of imagePaths) {
792
+ try {
793
+ const buf = await fs.readFile(p);
794
+ const base64 = buf.toString("base64");
795
+ const md5 = crypto.createHash("md5").update(buf).digest("hex");
796
+ loaded.push({ base64, md5, path: p });
797
+ } catch (err) {
798
+ target.runtime.error?.(`local-path: 读取图片失败 path=${p}: ${String(err)}`);
799
+ }
800
+ }
801
+
802
+ if (loaded.length > 0) {
803
+ streamStore.updateStream(streamId, (s) => {
804
+ s.images = loaded.map(({ base64, md5 }) => ({ base64, md5 }));
805
+ s.content = loaded.length === 1
806
+ ? `已发送图片(${pathModule.basename(loaded[0]!.path)})`
807
+ : `已发送 ${loaded.length} 张图片`;
808
+ s.finished = true;
809
+ });
810
+
811
+ const responseUrl = getActiveReplyUrl(streamId);
812
+ if (responseUrl) {
813
+ try {
814
+ const finalReply = buildStreamReplyFromState(streamStore.getStream(streamId)!) as unknown as Record<string, unknown>;
815
+ await useActiveReplyOnce(streamId, async ({ responseUrl, proxyUrl }) => {
816
+ const res = await wecomFetch(
817
+ responseUrl,
818
+ {
819
+ method: "POST",
820
+ headers: { "Content-Type": "application/json" },
821
+ body: JSON.stringify(finalReply),
822
+ },
823
+ { proxyUrl, timeoutMs: LIMITS.REQUEST_TIMEOUT_MS },
824
+ );
825
+ if (!res.ok) throw new Error(`local-path image push failed: ${res.status}`);
826
+ });
827
+ logVerbose(target, `local-path: 已通过 Bot response_url 推送图片 frames=final images=${loaded.length}`);
828
+ } catch (err) {
829
+ target.runtime.error?.(`local-path: Bot 主动推送图片失败(将依赖 stream_refresh 拉取): ${String(err)}`);
830
+ }
831
+ } else {
832
+ logVerbose(target, `local-path: 无 response_url,等待 stream_refresh 拉取最终图片`);
833
+ }
834
+ // 该消息已完成,推进队列处理下一批
835
+ streamStore.onStreamFinished(streamId);
836
+ return;
837
+ }
838
+ }
839
+
840
+ // 2) 非图片文件:Bot 会话里提示 + Agent 私信兜底(目标锁定 userId)
841
+ if (otherPaths.length > 0) {
842
+ const agentCfg = resolveAgentAccountOrUndefined(config);
843
+ const agentOk = Boolean(agentCfg);
844
+
845
+ const filename = otherPaths.length === 1 ? otherPaths[0]!.split("/").pop()! : `${otherPaths.length} 个文件`;
846
+ const prompt = buildFallbackPrompt({
847
+ kind: "media",
848
+ agentConfigured: agentOk,
849
+ userId: userid,
850
+ filename,
851
+ chatType,
852
+ });
853
+
854
+ streamStore.updateStream(streamId, (s) => {
855
+ s.fallbackMode = "media";
856
+ s.finished = true;
857
+ s.content = prompt;
858
+ s.fallbackPromptSentAt = s.fallbackPromptSentAt ?? Date.now();
859
+ });
860
+
861
+ try {
862
+ await sendBotFallbackPromptNow({ streamId, text: prompt });
863
+ logVerbose(target, `local-path: 文件兜底提示已推送`);
864
+ } catch (err) {
865
+ target.runtime.error?.(`local-path: 文件兜底提示推送失败: ${String(err)}`);
866
+ }
867
+
868
+ if (!agentCfg) {
869
+ streamStore.onStreamFinished(streamId);
870
+ return;
871
+ }
872
+ if (!userid || userid === "unknown") {
873
+ target.runtime.error?.(`local-path: 无法识别触发者 userId,无法 Agent 私信发送文件`);
874
+ streamStore.onStreamFinished(streamId);
875
+ return;
876
+ }
877
+
878
+ for (const p of otherPaths) {
879
+ const alreadySent = streamStore.getStream(streamId)?.agentMediaKeys?.includes(p);
880
+ if (alreadySent) continue;
881
+ try {
882
+ await sendAgentDmMedia({
883
+ agent: agentCfg,
884
+ userId: userid,
885
+ mediaUrlOrPath: p,
886
+ contentType: guessContentTypeFromPath(p),
887
+ filename: p.split("/").pop() || "file",
888
+ });
889
+ streamStore.updateStream(streamId, (s) => {
890
+ s.agentMediaKeys = Array.from(new Set([...(s.agentMediaKeys ?? []), p]));
891
+ });
892
+ logVerbose(target, `local-path: 文件已通过 Agent 私信发送 user=${userid} path=${p}`);
893
+ } catch (err) {
894
+ target.runtime.error?.(`local-path: Agent 私信发送文件失败 path=${p}: ${String(err)}`);
895
+ }
896
+ }
897
+ streamStore.onStreamFinished(streamId);
898
+ return;
899
+ }
900
+ }
901
+
902
+ // 2. Save media if present
903
+ let mediaPath: string | undefined;
904
+ let mediaType: string | undefined;
905
+ if (media) {
906
+ try {
907
+ const maxBytes = resolveWecomMediaMaxBytes(target.config);
908
+ const saved = await core.channel.media.saveMediaBuffer(
909
+ media.buffer,
910
+ media.contentType,
911
+ "inbound",
912
+ maxBytes,
913
+ media.filename
914
+ );
915
+ mediaPath = saved.path;
916
+ mediaType = saved.contentType;
917
+ logVerbose(target, `saved inbound media to ${mediaPath} (${mediaType})`);
918
+ } catch (err) {
919
+ target.runtime.error?.(`Failed to save inbound media: ${String(err)}`);
920
+ }
921
+ }
922
+
923
+ const route = core.channel.routing.resolveAgentRoute({
924
+ cfg: config,
925
+ channel: "wecom",
926
+ accountId: account.accountId,
927
+ peer: { kind: chatType === "group" ? "group" : "dm", id: chatId },
928
+ });
929
+
930
+ logVerbose(target, `starting agent processing (streamId=${streamId}, agentId=${route.agentId}, peerKind=${chatType}, peerId=${chatId})`);
931
+ logVerbose(target, `启动 Agent 处理: streamId=${streamId} 路由=${route.agentId} 类型=${chatType} ID=${chatId}`);
932
+
933
+ const fromLabel = chatType === "group" ? `group:${chatId}` : `user:${userid}`;
934
+ const storePath = core.channel.session.resolveStorePath(config.session?.store, {
935
+ agentId: route.agentId,
936
+ });
937
+ const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(config);
938
+ const previousTimestamp = core.channel.session.readSessionUpdatedAt({
939
+ storePath,
940
+ sessionKey: route.sessionKey,
941
+ });
942
+ const body = core.channel.reply.formatAgentEnvelope({
943
+ channel: "WeCom",
944
+ from: fromLabel,
945
+ previousTimestamp,
946
+ envelope: envelopeOptions,
947
+ body: rawBody,
948
+ });
949
+
950
+ const authz = await resolveWecomCommandAuthorization({
951
+ core,
952
+ cfg: config,
953
+ accountConfig: account.config,
954
+ rawBody,
955
+ senderUserId: userid,
956
+ });
957
+ const commandAuthorized = authz.commandAuthorized;
958
+ logVerbose(
959
+ target,
960
+ `authz: dmPolicy=${authz.dmPolicy} shouldCompute=${authz.shouldComputeAuth} sender=${userid.toLowerCase()} senderAllowed=${authz.senderAllowed} authorizerConfigured=${authz.authorizerConfigured} commandAuthorized=${String(authz.commandAuthorized)}`,
961
+ );
962
+
963
+ // 命令门禁:如果这是命令且未授权,必须给用户一个明确的中文回复(不能静默忽略)
964
+ if (authz.shouldComputeAuth && authz.commandAuthorized !== true) {
965
+ const prompt = buildWecomUnauthorizedCommandPrompt({ senderUserId: userid, dmPolicy: authz.dmPolicy, scope: "bot" });
966
+ streamStore.updateStream(streamId, (s) => {
967
+ s.finished = true;
968
+ s.content = prompt;
969
+ });
970
+ try {
971
+ await sendBotFallbackPromptNow({ streamId, text: prompt });
972
+ logInfo(target, `authz: 未授权命令已提示用户 streamId=${streamId}`);
973
+ } catch (err) {
974
+ target.runtime.error?.(`authz: 未授权命令提示推送失败 streamId=${streamId}: ${String(err)}`);
975
+ }
976
+ streamStore.onStreamFinished(streamId);
977
+ return;
978
+ }
979
+
980
+ const rawBodyNormalized = rawBody.trim();
981
+ const isResetCommand = /^\/(new|reset)(?:\s|$)/i.test(rawBodyNormalized);
982
+ const resetCommandKind = isResetCommand ? (rawBodyNormalized.match(/^\/(new|reset)/i)?.[1]?.toLowerCase() ?? "new") : null;
983
+
984
+ const attachments = mediaPath ? [{
985
+ name: media?.filename || "file",
986
+ mimeType: mediaType,
987
+ url: pathToFileURL(mediaPath).href
988
+ }] : undefined;
989
+
990
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
991
+ Body: body,
992
+ RawBody: rawBody,
993
+ CommandBody: rawBody,
994
+ Attachments: attachments,
995
+ From: chatType === "group" ? `wecom:group:${chatId}` : `wecom:${userid}`,
996
+ To: `wecom:${chatId}`,
997
+ SessionKey: route.sessionKey,
998
+ AccountId: route.accountId,
999
+ ChatType: chatType,
1000
+ ConversationLabel: fromLabel,
1001
+ SenderName: userid,
1002
+ SenderId: userid,
1003
+ Provider: "wecom",
1004
+ Surface: "wecom",
1005
+ MessageSid: msg.msgid,
1006
+ CommandAuthorized: commandAuthorized,
1007
+ OriginatingChannel: "wecom",
1008
+ OriginatingTo: `wecom:${chatId}`,
1009
+ MediaPath: mediaPath,
1010
+ MediaType: mediaType,
1011
+ MediaUrl: mediaPath, // Local path for now
1012
+ });
1013
+
1014
+ await core.channel.session.recordInboundSession({
1015
+ storePath,
1016
+ sessionKey: ctxPayload.SessionKey ?? route.sessionKey,
1017
+ ctx: ctxPayload,
1018
+ onRecordError: (err) => {
1019
+ target.runtime.error?.(`wecom: failed updating session meta: ${String(err)}`);
1020
+ },
1021
+ });
1022
+
1023
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
1024
+ cfg: config,
1025
+ channel: "wecom",
1026
+ accountId: account.accountId,
1027
+ });
1028
+
1029
+ // WeCom Bot 会话交付约束:
1030
+ // - 图片应尽量由 Bot 在原会话交付(流式最终帧 msg_item)。
1031
+ // - 非图片文件走 Agent 私信兜底(本文件中实现),并由 Bot 给出提示。
1032
+ //
1033
+ // 重要:message 工具不是 sandbox 工具,必须通过 cfg.tools.deny 禁用。
1034
+ // 否则 Agent 可能直接通过 message 工具私信/发群,绕过 Bot 交付链路,导致群里“没有任何提示”。
1035
+ const cfgForDispatch = (() => {
1036
+ const baseTools = (config as any)?.tools ?? {};
1037
+ const baseSandbox = (baseTools as any)?.sandbox ?? {};
1038
+ const baseSandboxTools = (baseSandbox as any)?.tools ?? {};
1039
+ const existingDeny = Array.isArray((baseSandboxTools as any).deny) ? ((baseSandboxTools as any).deny as string[]) : [];
1040
+ const deny = Array.from(new Set([...existingDeny, "message"]));
1041
+ return {
1042
+ ...(config as any),
1043
+ tools: {
1044
+ ...baseTools,
1045
+ sandbox: {
1046
+ ...baseSandbox,
1047
+ tools: {
1048
+ ...baseSandboxTools,
1049
+ deny,
1050
+ },
1051
+ },
1052
+ },
1053
+ } as OpenClawConfig;
1054
+ })();
1055
+ logVerbose(target, `tool-policy: WeCom Bot 会话已禁用 message 工具(tools.sandbox.tools.deny += message,防止绕过 Bot 交付)`);
1056
+
1057
+ // 调度 Agent 回复
1058
+ // 使用 dispatchReplyWithBufferedBlockDispatcher 可以处理流式输出 buffer
1059
+ await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
1060
+ ctx: ctxPayload,
1061
+ cfg: cfgForDispatch,
1062
+ dispatcherOptions: {
1063
+ deliver: async (payload) => {
1064
+ let text = payload.text ?? "";
1065
+
1066
+ // 保护 <think> 标签不被 markdown 表格转换破坏
1067
+ const thinkRegex = /<think>([\s\S]*?)<\/think>/g;
1068
+ const thinks: string[] = [];
1069
+ text = text.replace(thinkRegex, (match: string) => {
1070
+ thinks.push(match);
1071
+ return `__THINK_PLACEHOLDER_${thinks.length - 1}__`;
1072
+ });
1073
+
1074
+ // [A2UI] Detect template_card JSON output from Agent
1075
+ const trimmedText = text.trim();
1076
+ if (trimmedText.startsWith("{") && trimmedText.includes('"template_card"')) {
1077
+ try {
1078
+ const parsed = JSON.parse(trimmedText);
1079
+ if (parsed.template_card) {
1080
+ const isSingleChat = msg.chattype !== "group";
1081
+ const responseUrl = getActiveReplyUrl(streamId);
1082
+
1083
+ if (responseUrl && isSingleChat) {
1084
+ // 单聊且有 response_url:发送卡片
1085
+ await useActiveReplyOnce(streamId, async ({ responseUrl, proxyUrl }) => {
1086
+ const res = await wecomFetch(
1087
+ responseUrl,
1088
+ {
1089
+ method: "POST",
1090
+ headers: { "Content-Type": "application/json" },
1091
+ body: JSON.stringify({
1092
+ msgtype: "template_card",
1093
+ template_card: parsed.template_card,
1094
+ }),
1095
+ },
1096
+ { proxyUrl, timeoutMs: LIMITS.REQUEST_TIMEOUT_MS },
1097
+ );
1098
+ if (!res.ok) {
1099
+ throw new Error(`template_card send failed: ${res.status}`);
1100
+ }
1101
+ });
1102
+ logVerbose(target, `sent template_card: task_id=${parsed.template_card.task_id}`);
1103
+ streamStore.updateStream(streamId, (s) => {
1104
+ s.finished = true;
1105
+ s.content = "[已发送交互卡片]";
1106
+ });
1107
+ target.statusSink?.({ lastOutboundAt: Date.now() });
1108
+ return;
1109
+ } else {
1110
+ // 群聊 或 无 response_url:降级为文本描述
1111
+ logVerbose(target, `template_card fallback to text (group=${!isSingleChat}, hasUrl=${!!responseUrl})`);
1112
+ const cardTitle = parsed.template_card.main_title?.title || "交互卡片";
1113
+ const cardDesc = parsed.template_card.main_title?.desc || "";
1114
+ const buttons = parsed.template_card.button_list?.map((b: any) => b.text).join(" / ") || "";
1115
+ text = `📋 **${cardTitle}**${cardDesc ? `\n${cardDesc}` : ""}${buttons ? `\n\n选项: ${buttons}` : ""}`;
1116
+ }
1117
+ }
1118
+ } catch { /* parse fail, use normal text */ }
1119
+ }
1120
+
1121
+ text = core.channel.text.convertMarkdownTables(text, tableMode);
1122
+
1123
+ // Restore <think> tags
1124
+ thinks.forEach((think, i) => {
1125
+ text = text.replace(`__THINK_PLACEHOLDER_${i}__`, think);
1126
+ });
1127
+
1128
+ const current = streamStore.getStream(streamId);
1129
+ if (!current) return;
1130
+
1131
+ if (!current.images) current.images = [];
1132
+ if (!current.agentMediaKeys) current.agentMediaKeys = [];
1133
+
1134
+ logVerbose(
1135
+ target,
1136
+ `deliver: chatType=${current.chatType ?? chatType} user=${current.userId ?? userid} textLen=${text.length} mediaCount=${(payload.mediaUrls?.length ?? 0) + (payload.mediaUrl ? 1 : 0)}`,
1137
+ );
1138
+
1139
+ // If the model referenced a local image path in its reply but did not emit mediaUrl(s),
1140
+ // we can still deliver it via Bot *only* when that exact path appeared in the user's
1141
+ // original message (rawBody). This prevents the model from exfiltrating arbitrary files.
1142
+ if (!payload.mediaUrl && !(payload.mediaUrls?.length ?? 0) && text.includes("/")) {
1143
+ const candidates = extractLocalImagePathsFromText({ text, mustAlsoAppearIn: rawBody });
1144
+ if (candidates.length > 0) {
1145
+ logVerbose(target, `media: 从输出文本推断到本机图片路径(来自用户原消息)count=${candidates.length}`);
1146
+ for (const p of candidates) {
1147
+ try {
1148
+ const fs = await import("node:fs/promises");
1149
+ const pathModule = await import("node:path");
1150
+ const buf = await fs.readFile(p);
1151
+ const ext = pathModule.extname(p).slice(1).toLowerCase();
1152
+ const imageExts: Record<string, string> = {
1153
+ jpg: "image/jpeg",
1154
+ jpeg: "image/jpeg",
1155
+ png: "image/png",
1156
+ gif: "image/gif",
1157
+ webp: "image/webp",
1158
+ bmp: "image/bmp",
1159
+ };
1160
+ const contentType = imageExts[ext] ?? "application/octet-stream";
1161
+ if (!contentType.startsWith("image/")) {
1162
+ continue;
1163
+ }
1164
+ const base64 = buf.toString("base64");
1165
+ const md5 = crypto.createHash("md5").update(buf).digest("hex");
1166
+ current.images.push({ base64, md5 });
1167
+ logVerbose(target, `media: 已加载本机图片用于 Bot 交付 path=${p}`);
1168
+ } catch (err) {
1169
+ target.runtime.error?.(`media: 读取本机图片失败 path=${p}: ${String(err)}`);
1170
+ }
1171
+ }
1172
+ }
1173
+ }
1174
+
1175
+ // Always accumulate content for potential Agent DM fallback (not limited by STREAM_MAX_BYTES).
1176
+ if (text.trim()) {
1177
+ streamStore.updateStream(streamId, (s) => {
1178
+ appendDmContent(s, text);
1179
+ });
1180
+ }
1181
+
1182
+ // Timeout fallback (group only): near 6min window, stop bot stream and switch to Agent DM.
1183
+ const now = Date.now();
1184
+ const deadline = current.createdAt + BOT_WINDOW_MS;
1185
+ const switchAt = deadline - BOT_SWITCH_MARGIN_MS;
1186
+ const nearTimeout = !current.fallbackMode && !current.finished && now >= switchAt;
1187
+ if (nearTimeout) {
1188
+ const agentCfg = resolveAgentAccountOrUndefined(config);
1189
+ const agentOk = Boolean(agentCfg);
1190
+ const prompt = buildFallbackPrompt({
1191
+ kind: "timeout",
1192
+ agentConfigured: agentOk,
1193
+ userId: current.userId,
1194
+ chatType: current.chatType,
1195
+ });
1196
+ logVerbose(
1197
+ target,
1198
+ `fallback(timeout): 触发切换(接近 6 分钟)chatType=${current.chatType} agentConfigured=${agentOk} hasResponseUrl=${Boolean(getActiveReplyUrl(streamId))}`,
1199
+ );
1200
+ streamStore.updateStream(streamId, (s) => {
1201
+ s.fallbackMode = "timeout";
1202
+ s.finished = true;
1203
+ s.content = prompt;
1204
+ s.fallbackPromptSentAt = s.fallbackPromptSentAt ?? Date.now();
1205
+ });
1206
+ try {
1207
+ await sendBotFallbackPromptNow({ streamId, text: prompt });
1208
+ logVerbose(target, `fallback(timeout): 群内提示已推送`);
1209
+ } catch (err) {
1210
+ target.runtime.error?.(`wecom bot fallback prompt push failed (timeout) streamId=${streamId}: ${String(err)}`);
1211
+ }
1212
+ return;
1213
+ }
1214
+
1215
+ const mediaUrls = payload.mediaUrls || (payload.mediaUrl ? [payload.mediaUrl] : []);
1216
+ for (const mediaPath of mediaUrls) {
1217
+ try {
1218
+ let buf: Buffer;
1219
+ let contentType: string | undefined;
1220
+ let filename: string;
1221
+
1222
+ const looksLikeUrl = /^https?:\/\//i.test(mediaPath);
1223
+
1224
+ if (looksLikeUrl) {
1225
+ const loaded = await core.channel.media.fetchRemoteMedia({ url: mediaPath });
1226
+ buf = loaded.buffer;
1227
+ contentType = loaded.contentType;
1228
+ filename = loaded.fileName ?? "attachment";
1229
+ } else {
1230
+ const fs = await import("node:fs/promises");
1231
+ const pathModule = await import("node:path");
1232
+ buf = await fs.readFile(mediaPath);
1233
+ filename = pathModule.basename(mediaPath);
1234
+ const ext = pathModule.extname(mediaPath).slice(1).toLowerCase();
1235
+ const imageExts: Record<string, string> = { jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", gif: "image/gif", webp: "image/webp", bmp: "image/bmp" };
1236
+ contentType = imageExts[ext] ?? "application/octet-stream";
1237
+ }
1238
+
1239
+ if (contentType?.startsWith("image/")) {
1240
+ const base64 = buf.toString("base64");
1241
+ const md5 = crypto.createHash("md5").update(buf).digest("hex");
1242
+ current.images.push({ base64, md5 });
1243
+ logVerbose(target, `media: 识别为图片 contentType=${contentType} filename=${filename}`);
1244
+ } else {
1245
+ // Non-image media: Bot 不支持原样发送(尤其群聊),统一切换到 Agent 私信兜底,并在 Bot 会话里提示用户。
1246
+ const agentCfg = resolveAgentAccountOrUndefined(config);
1247
+ const agentOk = Boolean(agentCfg);
1248
+ const alreadySent = current.agentMediaKeys.includes(mediaPath);
1249
+ logVerbose(
1250
+ target,
1251
+ `fallback(media): 检测到非图片文件 chatType=${current.chatType} contentType=${contentType ?? "unknown"} filename=${filename} agentConfigured=${agentOk} alreadySent=${alreadySent} hasResponseUrl=${Boolean(getActiveReplyUrl(streamId))}`,
1252
+ );
1253
+
1254
+ if (agentCfg && !alreadySent && current.userId) {
1255
+ try {
1256
+ await sendAgentDmMedia({
1257
+ agent: agentCfg,
1258
+ userId: current.userId,
1259
+ mediaUrlOrPath: mediaPath,
1260
+ contentType,
1261
+ filename,
1262
+ });
1263
+ logVerbose(target, `fallback(media): 文件已通过 Agent 私信发送 user=${current.userId}`);
1264
+ streamStore.updateStream(streamId, (s) => {
1265
+ s.agentMediaKeys = Array.from(new Set([...(s.agentMediaKeys ?? []), mediaPath]));
1266
+ });
1267
+ } catch (err) {
1268
+ target.runtime.error?.(`wecom agent dm media failed: ${String(err)}`);
1269
+ }
1270
+ }
1271
+
1272
+ if (!current.fallbackMode) {
1273
+ const prompt = buildFallbackPrompt({
1274
+ kind: "media",
1275
+ agentConfigured: agentOk,
1276
+ userId: current.userId,
1277
+ filename,
1278
+ chatType: current.chatType,
1279
+ });
1280
+ streamStore.updateStream(streamId, (s) => {
1281
+ s.fallbackMode = "media";
1282
+ s.finished = true;
1283
+ s.content = prompt;
1284
+ s.fallbackPromptSentAt = s.fallbackPromptSentAt ?? Date.now();
1285
+ });
1286
+ try {
1287
+ await sendBotFallbackPromptNow({ streamId, text: prompt });
1288
+ logVerbose(target, `fallback(media): 群内提示已推送`);
1289
+ } catch (err) {
1290
+ target.runtime.error?.(`wecom bot fallback prompt push failed (media) streamId=${streamId}: ${String(err)}`);
1291
+ }
1292
+ }
1293
+ return;
1294
+ }
1295
+ } catch (err) {
1296
+ target.runtime.error?.(`Failed to process outbound media: ${mediaPath}: ${String(err)}`);
1297
+ }
1298
+ }
1299
+
1300
+ // If we are in fallback mode, do not continue updating the bot stream content.
1301
+ const mode = streamStore.getStream(streamId)?.fallbackMode;
1302
+ if (mode) return;
1303
+
1304
+ const nextText = current.content
1305
+ ? `${current.content}\n\n${text}`.trim()
1306
+ : text.trim();
1307
+
1308
+ streamStore.updateStream(streamId, (s) => {
1309
+ s.content = truncateUtf8Bytes(nextText, STREAM_MAX_BYTES);
1310
+ if (current.images?.length) s.images = current.images; // ensure images are saved
1311
+ });
1312
+ target.statusSink?.({ lastOutboundAt: Date.now() });
1313
+ },
1314
+ onError: (err, info) => {
1315
+ target.runtime.error?.(`[${account.accountId}] wecom ${info.kind} reply failed: ${String(err)}`);
1316
+ },
1317
+ },
1318
+ });
1319
+
1320
+ // /new /reset:OpenClaw 核心会通过 routeReply 发送英文回执(✅ New session started...),
1321
+ // 但 WeCom 双模式下这条回执可能会走 Agent 私信,导致“从 Bot 发,却在 Agent 再回一条”。
1322
+ // 该英文回执已在 wecom outbound 层做抑制/改写;这里补一个“同会话中文回执”,保证用户可理解。
1323
+ if (isResetCommand) {
1324
+ const current = streamStore.getStream(streamId);
1325
+ const hasAnyContent = Boolean(current?.content?.trim());
1326
+ if (current && !hasAnyContent) {
1327
+ const ackText = resetCommandKind === "reset" ? "✅ 已重置会话。" : "✅ 已开启新会话。";
1328
+ streamStore.updateStream(streamId, (s) => {
1329
+ s.content = ackText;
1330
+ s.finished = true;
1331
+ });
1332
+ }
1333
+ }
1334
+
1335
+ streamStore.markFinished(streamId);
1336
+
1337
+ // Timeout fallback final delivery (Agent DM): send once after the agent run completes.
1338
+ const finishedState = streamStore.getStream(streamId);
1339
+ if (finishedState?.fallbackMode === "timeout" && !finishedState.finalDeliveredAt) {
1340
+ const agentCfg = resolveAgentAccountOrUndefined(config);
1341
+ if (!agentCfg) {
1342
+ // Agent not configured - group prompt already explains the situation.
1343
+ streamStore.updateStream(streamId, (s) => { s.finalDeliveredAt = Date.now(); });
1344
+ } else if (finishedState.userId) {
1345
+ const dmText = (finishedState.dmContent ?? "").trim();
1346
+ if (dmText) {
1347
+ try {
1348
+ logVerbose(target, `fallback(timeout): 开始通过 Agent 私信发送剩余内容 user=${finishedState.userId} len=${dmText.length}`);
1349
+ await sendAgentDmText({ agent: agentCfg, userId: finishedState.userId, text: dmText, core });
1350
+ logVerbose(target, `fallback(timeout): Agent 私信发送完成 user=${finishedState.userId}`);
1351
+ } catch (err) {
1352
+ target.runtime.error?.(`wecom agent dm text failed (timeout): ${String(err)}`);
1353
+ }
1354
+ }
1355
+ streamStore.updateStream(streamId, (s) => { s.finalDeliveredAt = Date.now(); });
1356
+ }
1357
+ }
1358
+
1359
+ // Bot 群聊图片兜底:
1360
+ // 依赖企业微信的“流式消息刷新”回调来拉取最终消息有时会出现客户端未能及时拉取到最后一帧的情况,
1361
+ // 导致最终的图片(msg_item)没有展示。若存在 response_url,则在流结束后主动推送一次最终 stream 回复。
1362
+ // 注:该行为以 response_url 是否可用为准;失败则仅记录日志,不影响原有刷新链路。
1363
+ if (chatType === "group") {
1364
+ const state = streamStore.getStream(streamId);
1365
+ const hasImages = Boolean(state?.images?.length);
1366
+ const responseUrl = getActiveReplyUrl(streamId);
1367
+ if (state && hasImages && responseUrl) {
1368
+ const finalReply = buildStreamReplyFromState(state) as unknown as Record<string, unknown>;
1369
+ try {
1370
+ await useActiveReplyOnce(streamId, async ({ responseUrl, proxyUrl }) => {
1371
+ const res = await wecomFetch(
1372
+ responseUrl,
1373
+ {
1374
+ method: "POST",
1375
+ headers: { "Content-Type": "application/json" },
1376
+ body: JSON.stringify(finalReply),
1377
+ },
1378
+ { proxyUrl, timeoutMs: LIMITS.REQUEST_TIMEOUT_MS },
1379
+ );
1380
+ if (!res.ok) {
1381
+ throw new Error(`final stream push failed: ${res.status}`);
1382
+ }
1383
+ });
1384
+ logVerbose(target, `final stream pushed via response_url (group) streamId=${streamId}, images=${state.images?.length ?? 0}`);
1385
+ } catch (err) {
1386
+ target.runtime.error?.(`final stream push via response_url failed (group) streamId=${streamId}: ${String(err)}`);
1387
+ }
1388
+ }
1389
+ }
1390
+
1391
+ // 推进会话队列:如果 2/3 已排队,当前批次结束后自动开始下一批次
1392
+ logInfo(target, `queue: 当前批次结束,尝试推进下一批 streamId=${streamId}`);
1393
+
1394
+ // 体验优化:如果本批次中有“回执流”(ack stream)(例如 3 被合并到 2),则在批次结束时更新这些回执流,
1395
+ // 避免它们永久停留在“已合并排队处理中…”。
1396
+ const ackStreamIds = streamStore.drainAckStreamsForBatch(streamId);
1397
+ if (ackStreamIds.length > 0) {
1398
+ const mergedDoneHint = "✅ 已合并处理完成,请查看上一条回复。";
1399
+ for (const ackId of ackStreamIds) {
1400
+ streamStore.updateStream(ackId, (s) => {
1401
+ s.content = mergedDoneHint;
1402
+ s.finished = true;
1403
+ });
1404
+ }
1405
+ logInfo(target, `queue: 已更新回执流 count=${ackStreamIds.length} batchStreamId=${streamId}`);
1406
+ }
1407
+
1408
+ streamStore.onStreamFinished(streamId);
1409
+ }
1410
+
1411
+ function formatQuote(quote: WecomInboundQuote): string {
1412
+ const type = quote.msgtype ?? "";
1413
+ if (type === "text") return quote.text?.content || "";
1414
+ if (type === "image") return `[引用: 图片] ${quote.image?.url || ""}`;
1415
+ if (type === "mixed" && quote.mixed?.msg_item) {
1416
+ const items = quote.mixed.msg_item.map((item) => {
1417
+ if (item.msgtype === "text") return item.text?.content;
1418
+ if (item.msgtype === "image") return `[图片] ${item.image?.url || ""}`;
1419
+ return "";
1420
+ }).filter(Boolean).join(" ");
1421
+ return `[引用: 图文] ${items}`;
1422
+ }
1423
+ if (type === "voice") return `[引用: 语音] ${quote.voice?.content || ""}`;
1424
+ if (type === "file") return `[引用: 文件] ${quote.file?.url || ""}`;
1425
+ return "";
1426
+ }
1427
+
1428
+ function buildInboundBody(msg: WecomInboundMessage): string {
1429
+ let body = "";
1430
+ const msgtype = String(msg.msgtype ?? "").toLowerCase();
1431
+
1432
+ if (msgtype === "text") body = (msg as any).text?.content || "";
1433
+ else if (msgtype === "voice") body = (msg as any).voice?.content || "[voice]";
1434
+ else if (msgtype === "mixed") {
1435
+ const items = (msg as any).mixed?.msg_item;
1436
+ if (Array.isArray(items)) {
1437
+ body = items.map((item: any) => {
1438
+ const t = String(item?.msgtype ?? "").toLowerCase();
1439
+ if (t === "text") return item?.text?.content || "";
1440
+ if (t === "image") return `[image] ${item?.image?.url || ""}`;
1441
+ return `[${t || "item"}]`;
1442
+ }).filter(Boolean).join("\n");
1443
+ } else body = "[mixed]";
1444
+ } else if (msgtype === "image") body = `[image] ${(msg as any).image?.url || ""}`;
1445
+ else if (msgtype === "file") body = `[file] ${(msg as any).file?.url || ""}`;
1446
+ else if (msgtype === "event") body = `[event] ${(msg as any).event?.eventtype || ""}`;
1447
+ else if (msgtype === "stream") body = `[stream_refresh] ${(msg as any).stream?.id || ""}`;
1448
+ else body = msgtype ? `[${msgtype}]` : "";
1449
+
1450
+ const quote = (msg as any).quote;
1451
+ if (quote) {
1452
+ const quoteText = formatQuote(quote).trim();
1453
+ if (quoteText) body += `\n\n> ${quoteText}`;
1454
+ }
1455
+ return body;
1456
+ }
1457
+
1458
+ /**
1459
+ * **registerWecomWebhookTarget (注册 Webhook 目标)**
1460
+ *
1461
+ * 注册一个 Bot 模式的接收端点。
1462
+ * 同时会触发清理定时器的检查(如果有新注册,确保定时器运行)。
1463
+ * 返回一个注销函数。
1464
+ */
1465
+ export function registerWecomWebhookTarget(target: WecomWebhookTarget): () => void {
1466
+ const key = normalizeWebhookPath(target.path);
1467
+ const normalizedTarget = { ...target, path: key };
1468
+ const existing = webhookTargets.get(key) ?? [];
1469
+ webhookTargets.set(key, [...existing, normalizedTarget]);
1470
+ ensurePruneTimer();
1471
+ return () => {
1472
+ const updated = (webhookTargets.get(key) ?? []).filter((entry) => entry !== normalizedTarget);
1473
+ if (updated.length > 0) webhookTargets.set(key, updated);
1474
+ else webhookTargets.delete(key);
1475
+ checkPruneTimer();
1476
+ };
1477
+ }
1478
+
1479
+ /**
1480
+ * 注册 Agent 模式 Webhook Target
1481
+ */
1482
+ export function registerAgentWebhookTarget(target: AgentWebhookTarget): () => void {
1483
+ const key = WEBHOOK_PATHS.AGENT;
1484
+ agentTargets.set(key, target);
1485
+ ensurePruneTimer();
1486
+ return () => {
1487
+ agentTargets.delete(key);
1488
+ checkPruneTimer();
1489
+ };
1490
+ }
1491
+
1492
+ /**
1493
+ * **handleWecomWebhookRequest (HTTP 请求入口)**
1494
+ *
1495
+ * 处理来自企业微信的所有 Webhook 请求。
1496
+ * 职责:
1497
+ * 1. 路由分发:区分 Agent 模式 (`/wecom/agent`) 和 Bot 模式 (其他路径)。
1498
+ * 2. 安全校验:验证企业微信签名 (Signature)。
1499
+ * 3. 消息解密:处理企业微信的加密包。
1500
+ * 4. 响应处理:
1501
+ * - GET 请求:处理 EchoStr 验证。
1502
+ * - POST 请求:接收消息,放入 StreamStore,返回流式 First Chunk。
1503
+ */
1504
+ export async function handleWecomWebhookRequest(req: IncomingMessage, res: ServerResponse): Promise<boolean> {
1505
+ const path = resolvePath(req);
1506
+ const reqId = crypto.randomUUID().slice(0, 8);
1507
+ const remote = req.socket?.remoteAddress ?? "unknown";
1508
+ const ua = String(req.headers["user-agent"] ?? "");
1509
+ const cl = String(req.headers["content-length"] ?? "");
1510
+ // 不输出敏感参数内容,仅输出是否存在(排查“有没有打到网关/有没有带签名参数”)
1511
+ const q = resolveQueryParams(req);
1512
+ const hasTimestamp = Boolean(q.get("timestamp"));
1513
+ const hasNonce = Boolean(q.get("nonce"));
1514
+ const hasEchostr = Boolean(q.get("echostr"));
1515
+ const hasMsgSig = Boolean(q.get("msg_signature"));
1516
+ const hasSignature = Boolean(q.get("signature"));
1517
+ console.log(
1518
+ `[wecom] inbound(http): reqId=${reqId} path=${path} method=${req.method ?? "UNKNOWN"} remote=${remote} ua=${ua ? `"${ua}"` : "N/A"} contentLength=${cl || "N/A"} query={timestamp:${hasTimestamp},nonce:${hasNonce},echostr:${hasEchostr},msg_signature:${hasMsgSig},signature:${hasSignature}}`,
1519
+ );
1520
+
1521
+ // Agent 模式路由: /wecom/agent
1522
+ if (path === WEBHOOK_PATHS.AGENT) {
1523
+ const agentTarget = agentTargets.get(WEBHOOK_PATHS.AGENT);
1524
+ if (agentTarget) {
1525
+ const core = getWecomRuntime();
1526
+ const query = resolveQueryParams(req);
1527
+ const timestamp = query.get("timestamp") ?? "";
1528
+ const nonce = query.get("nonce") ?? "";
1529
+ const hasSig = Boolean(query.get("msg_signature"));
1530
+ const remote = req.socket?.remoteAddress ?? "unknown";
1531
+ agentTarget.runtime.log?.(
1532
+ `[wecom] inbound(agent): reqId=${reqId} method=${req.method ?? "UNKNOWN"} remote=${remote} timestamp=${timestamp ? "yes" : "no"} nonce=${nonce ? "yes" : "no"} msg_signature=${hasSig ? "yes" : "no"}`,
1533
+ );
1534
+ return handleAgentWebhook({
1535
+ req,
1536
+ res,
1537
+ agent: agentTarget.agent,
1538
+ config: agentTarget.config,
1539
+ core,
1540
+ log: agentTarget.runtime.log,
1541
+ error: agentTarget.runtime.error,
1542
+ });
1543
+ }
1544
+ // 未注册 Agent,返回 404
1545
+ res.statusCode = 404;
1546
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
1547
+ res.end(`agent not configured - Agent 模式未配置,请运行 openclaw onboarding${ERROR_HELP}`);
1548
+ return true;
1549
+ }
1550
+
1551
+ // Bot 模式路由: /wecom, /wecom/bot
1552
+ const targets = webhookTargets.get(path);
1553
+ if (!targets || targets.length === 0) return false;
1554
+
1555
+ const query = resolveQueryParams(req);
1556
+ const timestamp = query.get("timestamp") ?? "";
1557
+ const nonce = query.get("nonce") ?? "";
1558
+ const signature = resolveSignatureParam(query);
1559
+
1560
+ if (req.method === "GET") {
1561
+ const echostr = query.get("echostr") ?? "";
1562
+ const target = targets.find(c => c.account.token && verifyWecomSignature({ token: c.account.token, timestamp, nonce, encrypt: echostr, signature }));
1563
+ if (!target || !target.account.encodingAESKey) {
1564
+ res.statusCode = 401;
1565
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
1566
+ res.end(`unauthorized - Bot 签名验证失败,请检查 Token 配置${ERROR_HELP}`);
1567
+ return true;
1568
+ }
1569
+ try {
1570
+ const plain = decryptWecomEncrypted({ encodingAESKey: target.account.encodingAESKey, receiveId: target.account.receiveId, encrypt: echostr });
1571
+ res.statusCode = 200;
1572
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
1573
+ res.end(plain);
1574
+ return true;
1575
+ } catch (err) {
1576
+ res.statusCode = 400;
1577
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
1578
+ res.end(`decrypt failed - 解密失败,请检查 EncodingAESKey${ERROR_HELP}`);
1579
+ return true;
1580
+ }
1581
+ }
1582
+
1583
+ if (req.method !== "POST") return false;
1584
+
1585
+ const body = await readJsonBody(req, 1024 * 1024);
1586
+ if (!body.ok) {
1587
+ res.statusCode = 400;
1588
+ res.end(body.error || "invalid payload");
1589
+ return true;
1590
+ }
1591
+ const record = body.value as any;
1592
+ const encrypt = String(record?.encrypt ?? record?.Encrypt ?? "");
1593
+ // Bot POST 回调体积/字段诊断(不输出 encrypt 内容)
1594
+ console.log(
1595
+ `[wecom] inbound(bot): reqId=${reqId} rawJsonBytes=${Buffer.byteLength(JSON.stringify(record), "utf8")} hasEncrypt=${Boolean(encrypt)} encryptLen=${encrypt.length}`,
1596
+ );
1597
+ const target = targets.find(c => c.account.token && verifyWecomSignature({ token: c.account.token, timestamp, nonce, encrypt, signature }));
1598
+ if (!target || !target.account.configured || !target.account.encodingAESKey) {
1599
+ res.statusCode = 401;
1600
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
1601
+ res.end(`unauthorized - Bot 签名验证失败${ERROR_HELP}`);
1602
+ return true;
1603
+ }
1604
+
1605
+ // 选定 target 后,把 reqId 带入结构化日志,方便串联排查
1606
+ logInfo(target, `inbound(bot): reqId=${reqId} selectedAccount=${target.account.accountId} path=${path}`);
1607
+
1608
+ let plain: string;
1609
+ try {
1610
+ plain = decryptWecomEncrypted({ encodingAESKey: target.account.encodingAESKey, receiveId: target.account.receiveId, encrypt });
1611
+ } catch (err) {
1612
+ res.statusCode = 400;
1613
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
1614
+ res.end(`decrypt failed - 解密失败${ERROR_HELP}`);
1615
+ return true;
1616
+ }
1617
+
1618
+ const msg = parseWecomPlainMessage(plain);
1619
+ const msgtype = String(msg.msgtype ?? "").toLowerCase();
1620
+ const proxyUrl = resolveWecomEgressProxyUrl(target.config);
1621
+
1622
+ // Handle Event
1623
+ if (msgtype === "event") {
1624
+ const eventtype = String((msg as any).event?.eventtype ?? "").toLowerCase();
1625
+
1626
+ if (eventtype === "template_card_event") {
1627
+ const msgid = msg.msgid ? String(msg.msgid) : undefined;
1628
+
1629
+ // Dedupe: skip if already processed this event
1630
+ if (msgid && streamStore.getStreamByMsgId(msgid)) {
1631
+ logVerbose(target, `template_card_event: already processed msgid=${msgid}, skipping`);
1632
+ jsonOk(res, buildEncryptedJsonReply({ account: target.account, plaintextJson: {}, nonce, timestamp }));
1633
+ return true;
1634
+ }
1635
+
1636
+ const cardEvent = (msg as any).event?.template_card_event;
1637
+ let interactionDesc = `[卡片交互] 按钮: ${cardEvent?.event_key || "unknown"}`;
1638
+ if (cardEvent?.selected_items?.selected_item?.length) {
1639
+ const selects = cardEvent.selected_items.selected_item.map((i: any) => `${i.question_key}=${i.option_ids?.option_id?.join(",")}`);
1640
+ interactionDesc += ` 选择: ${selects.join("; ")}`;
1641
+ }
1642
+ if (cardEvent?.task_id) interactionDesc += ` (任务ID: ${cardEvent.task_id})`;
1643
+
1644
+ jsonOk(res, buildEncryptedJsonReply({ account: target.account, plaintextJson: {}, nonce, timestamp }));
1645
+
1646
+ const streamId = streamStore.createStream({ msgid });
1647
+ streamStore.markStarted(streamId);
1648
+ storeActiveReply(streamId, msg.response_url);
1649
+ const core = getWecomRuntime();
1650
+ startAgentForStream({
1651
+ target: { ...target, core },
1652
+ accountId: target.account.accountId,
1653
+ msg: { ...msg, msgtype: "text", text: { content: interactionDesc } } as any,
1654
+ streamId,
1655
+ }).catch(err => target.runtime.error?.(`interaction failed: ${String(err)}`));
1656
+ return true;
1657
+ }
1658
+
1659
+ if (eventtype === "enter_chat") {
1660
+ const welcome = target.account.config.welcomeText?.trim();
1661
+ jsonOk(res, buildEncryptedJsonReply({ account: target.account, plaintextJson: welcome ? { msgtype: "text", text: { content: welcome } } : {}, nonce, timestamp }));
1662
+ return true;
1663
+ }
1664
+
1665
+ jsonOk(res, buildEncryptedJsonReply({ account: target.account, plaintextJson: {}, nonce, timestamp }));
1666
+ return true;
1667
+ }
1668
+
1669
+ // Handle Stream Refresh
1670
+ if (msgtype === "stream") {
1671
+ const streamId = String((msg as any).stream?.id ?? "").trim();
1672
+ const state = streamStore.getStream(streamId);
1673
+ const reply = state ? buildStreamReplyFromState(state) : buildStreamReplyFromState({ streamId: streamId || "unknown", createdAt: Date.now(), updatedAt: Date.now(), started: true, finished: true, content: "" });
1674
+ jsonOk(res, buildEncryptedJsonReply({ account: target.account, plaintextJson: reply, nonce, timestamp }));
1675
+ return true;
1676
+ }
1677
+
1678
+ // Handle Message (with Debounce)
1679
+ try {
1680
+ const userid = resolveWecomSenderUserId(msg) || "unknown";
1681
+ const chatId = msg.chattype === "group" ? (msg.chatid?.trim() || "unknown") : userid;
1682
+ const conversationKey = `wecom:${target.account.accountId}:${userid}:${chatId}`;
1683
+ const msgContent = buildInboundBody(msg);
1684
+
1685
+ logInfo(
1686
+ target,
1687
+ `inbound: msgtype=${msgtype} chattype=${String(msg.chattype ?? "")} chatid=${String(msg.chatid ?? "")} from=${userid} msgid=${String(msg.msgid ?? "")} hasResponseUrl=${Boolean((msg as any).response_url)}`,
1688
+ );
1689
+
1690
+ // 去重: 若 msgid 已存在于 StreamStore,说明是重试请求,直接返回占位符
1691
+ if (msg.msgid) {
1692
+ const existingStreamId = streamStore.getStreamByMsgId(String(msg.msgid));
1693
+ if (existingStreamId) {
1694
+ logInfo(target, `message: 重复的 msgid=${msg.msgid},跳过处理并返回占位符 streamId=${existingStreamId}`);
1695
+ jsonOk(res, buildEncryptedJsonReply({
1696
+ account: target.account,
1697
+ plaintextJson: buildStreamPlaceholderReply({
1698
+ streamId: existingStreamId,
1699
+ placeholderContent: target.account.config.streamPlaceholderContent
1700
+ }),
1701
+ nonce,
1702
+ timestamp
1703
+ }));
1704
+ return true;
1705
+ }
1706
+ }
1707
+
1708
+ // 加入 Pending 队列 (防抖/聚合)
1709
+ // 消息不会立即处理,而是等待防抖计时器结束(flushPending)后统一触发
1710
+ const { streamId, status } = streamStore.addPendingMessage({
1711
+ conversationKey,
1712
+ target,
1713
+ msg,
1714
+ msgContent,
1715
+ nonce,
1716
+ timestamp,
1717
+ debounceMs: (target.account.config as any).debounceMs
1718
+ });
1719
+
1720
+ // 无论是否新建,都尽量保存 response_url(用于兜底提示/最终帧推送)
1721
+ if (msg.response_url) {
1722
+ storeActiveReply(streamId, msg.response_url, proxyUrl);
1723
+ }
1724
+
1725
+ const defaultPlaceholder = target.account.config.streamPlaceholderContent;
1726
+ const queuedPlaceholder = "已收到,已排队处理中...";
1727
+ const mergedQueuedPlaceholder = "已收到,已合并排队处理中...";
1728
+
1729
+ if (status === "active_new") {
1730
+ jsonOk(res, buildEncryptedJsonReply({
1731
+ account: target.account,
1732
+ plaintextJson: buildStreamPlaceholderReply({
1733
+ streamId,
1734
+ placeholderContent: defaultPlaceholder
1735
+ }),
1736
+ nonce,
1737
+ timestamp
1738
+ }));
1739
+ return true;
1740
+ }
1741
+
1742
+ if (status === "queued_new") {
1743
+ logInfo(target, `queue: 已进入下一批次 streamId=${streamId} msgid=${String(msg.msgid ?? "")}`);
1744
+ jsonOk(res, buildEncryptedJsonReply({
1745
+ account: target.account,
1746
+ plaintextJson: buildStreamPlaceholderReply({
1747
+ streamId,
1748
+ placeholderContent: queuedPlaceholder
1749
+ }),
1750
+ nonce,
1751
+ timestamp
1752
+ }));
1753
+ return true;
1754
+ }
1755
+
1756
+ // active_merged / queued_merged:合并进某个批次,但本条消息不应该刷出“完整答案”,否则用户会看到重复内容。
1757
+ // 做法:为本条 msgid 创建一个“回执 stream”,先显示“已合并排队”,并在批次结束时自动更新为“已合并处理完成”。
1758
+ const ackStreamId = streamStore.createStream({ msgid: String(msg.msgid ?? "") || undefined });
1759
+ streamStore.updateStream(ackStreamId, (s) => {
1760
+ s.finished = false;
1761
+ s.started = true;
1762
+ s.content = mergedQueuedPlaceholder;
1763
+ });
1764
+ if (msg.msgid) streamStore.setStreamIdForMsgId(String(msg.msgid), ackStreamId);
1765
+ streamStore.addAckStreamForBatch({ batchStreamId: streamId, ackStreamId });
1766
+ logInfo(target, `queue: 已合并排队(回执流) ackStreamId=${ackStreamId} mergedIntoStreamId=${streamId} msgid=${String(msg.msgid ?? "")}`);
1767
+ jsonOk(res, buildEncryptedJsonReply({
1768
+ account: target.account,
1769
+ plaintextJson: buildStreamTextPlaceholderReply({ streamId: ackStreamId, content: mergedQueuedPlaceholder }),
1770
+ nonce,
1771
+ timestamp
1772
+ }));
1773
+ return true;
1774
+ } catch (err) {
1775
+ target.runtime.error?.(`[wecom] Bot message handler crashed: ${String(err)}`);
1776
+ // 尽量返回 200,避免企微重试风暴;同时给一个可见的错误文本
1777
+ jsonOk(res, buildEncryptedJsonReply({
1778
+ account: target.account,
1779
+ plaintextJson: { msgtype: "text", text: { content: "服务内部错误:Bot 处理异常,请稍后重试。" } },
1780
+ nonce,
1781
+ timestamp
1782
+ }));
1783
+ return true;
1784
+ }
1785
+ }
1786
+
1787
+ export async function sendActiveMessage(streamId: string, content: string): Promise<void> {
1788
+ await useActiveReplyOnce(streamId, async ({ responseUrl, proxyUrl }) => {
1789
+ const res = await wecomFetch(
1790
+ responseUrl,
1791
+ {
1792
+ method: "POST",
1793
+ headers: { "Content-Type": "application/json" },
1794
+ body: JSON.stringify({ msgtype: "text", text: { content } }),
1795
+ },
1796
+ { proxyUrl, timeoutMs: LIMITS.REQUEST_TIMEOUT_MS },
1797
+ );
1798
+ if (!res.ok) {
1799
+ throw new Error(`active send failed: ${res.status}`);
1800
+ }
1801
+ });
1802
+ }