@wecom/wecom-openclaw-plugin 2026.3.25-beta.0 → 2026.3.25-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -447,8 +447,6 @@ const IMAGE_DOWNLOAD_TIMEOUT_MS = 30000;
447
447
  const FILE_DOWNLOAD_TIMEOUT_MS = 60000;
448
448
  /** 消息发送超时时间(毫秒) */
449
449
  const REPLY_SEND_TIMEOUT_MS = 15000;
450
- /** 消息处理总超时时间(毫秒) */
451
- const MESSAGE_PROCESS_TIMEOUT_MS = 5 * 60 * 1000;
452
450
  /** WebSocket 心跳间隔(毫秒) */
453
451
  const WS_HEARTBEAT_INTERVAL_MS = 30000;
454
452
  /** WebSocket 连接断开时的最大重连次数 */
@@ -515,6 +513,17 @@ const CMD_ENTER_EVENT_REPLY = "ww_ai_robot_enter_event";
515
513
  // ============================================================================
516
514
  /** WSClient scene 参数:企微 OpenClaw 场景 */
517
515
  const SCENE_WECOM_OPENCLAW = 1;
516
+ // ============================================================================
517
+ // 模板卡片配置
518
+ // ============================================================================
519
+ /** 合法的模板卡片 card_type 列表 */
520
+ const VALID_CARD_TYPES = [
521
+ "text_notice",
522
+ "news_notice",
523
+ "button_interaction",
524
+ "vote_interaction",
525
+ "multiple_interaction",
526
+ ];
518
527
 
519
528
  /**
520
529
  * 企业微信消息内容解析模块
@@ -525,7 +534,47 @@ const SCENE_WECOM_OPENCLAW = 1;
525
534
  // 解析函数
526
535
  // ============================================================================
527
536
  /**
528
- * 解析消息内容(支持单条消息、图文混排和引用消息)
537
+ * 将模板卡片事件回调格式化为可继续路由给大模型的文本。
538
+ *
539
+ * 这样后续 Agent 可以直接从 question_key / option_id 中理解用户的真实选择。
540
+ */
541
+ function buildTemplateCardEventText(body) {
542
+ const templateCardEvent = body.event?.template_card_event;
543
+ if (body.msgtype !== "event" ||
544
+ body.event?.eventtype !== "template_card_event" ||
545
+ !templateCardEvent) {
546
+ return undefined;
547
+ }
548
+ const selectedItems = templateCardEvent.selected_items?.selected_item ?? [];
549
+ const selectedLines = selectedItems.map((item) => {
550
+ const questionKey = item.question_key?.trim() || "unknown_question";
551
+ const optionIds = item.option_ids?.option_id?.filter(Boolean) ?? [];
552
+ return `- ${questionKey}: ${optionIds.length > 0 ? optionIds.join(", ") : "(未选择)"}`;
553
+ });
554
+ const senderUserId = body.from?.userid || "";
555
+ const senderCorpId = body.from?.corpid || "";
556
+ const chatId = body.chatid || senderUserId;
557
+ return [
558
+ "[企业微信模板卡片回调]",
559
+ `event_type(事件类型): template_card_event`,
560
+ body.msgid ? `msgid(消息 id): ${body.msgid}` : undefined,
561
+ body.aibotid ? `aibotid(机器人 id): ${body.aibotid}` : undefined,
562
+ body.chattype ? `chat_type(会话类型): ${body.chattype}` : undefined,
563
+ chatId ? `chat_id(会话 id): ${chatId}` : undefined,
564
+ senderCorpId ? `from.corpid(企业 id): ${senderCorpId}` : undefined,
565
+ senderUserId ? `from.userid(发送人 id): ${senderUserId}` : undefined,
566
+ senderUserId ? `sender_userid(发送人 id): ${senderUserId}` : undefined,
567
+ templateCardEvent.card_type ? `card_type(卡片类型): ${templateCardEvent.card_type}` : undefined,
568
+ templateCardEvent.event_key ? `event_key(事件 key): ${templateCardEvent.event_key}` : undefined,
569
+ templateCardEvent.task_id ? `task_id(任务 id): ${templateCardEvent.task_id}` : undefined,
570
+ selectedLines.length > 0 ? "selected_items(选择项):" : "selected_items(选择项): []",
571
+ ...selectedLines,
572
+ ]
573
+ .filter((line) => Boolean(line))
574
+ .join("\n");
575
+ }
576
+ /**
577
+ * 解析消息内容(支持单条消息、图文混排、事件回调和引用消息)
529
578
  * @returns 提取的文本数组、图片URL数组和引用消息内容
530
579
  */
531
580
  function parseMessageContent(body) {
@@ -535,6 +584,14 @@ function parseMessageContent(body) {
535
584
  const fileUrls = [];
536
585
  const fileAesKeys = new Map();
537
586
  let quoteContent;
587
+ // 处理模板卡片事件回调
588
+ if (body.msgtype === "event") {
589
+ const eventText = buildTemplateCardEventText(body);
590
+ if (eventText) {
591
+ textParts.push(eventText);
592
+ }
593
+ return { textParts, imageUrls, imageAesKeys, fileUrls, fileAesKeys, quoteContent };
594
+ }
538
595
  // 处理图文混排消息
539
596
  if (body.msgtype === "mixed" && body.mixed?.msg_item) {
540
597
  for (const item of body.mixed.msg_item) {
@@ -641,6 +698,23 @@ class TimeoutError extends Error {
641
698
  * 负责通过 WSClient 发送回复消息,包含超时保护
642
699
  */
643
700
  // ============================================================================
701
+ // 流式过期错误(errcode 846608)
702
+ // ============================================================================
703
+ /** 流式回复超时错误码(>6分钟未更新,服务端拒绝继续流式更新) */
704
+ const STREAM_EXPIRED_ERRCODE = 846608;
705
+ /**
706
+ * 流式回复过期错误
707
+ * 当服务端返回 errcode=846608 时抛出,表示流式消息已超过6分钟无法更新,
708
+ * 调用方需降级为主动发送(sendMessage)方式回复。
709
+ */
710
+ class StreamExpiredError extends Error {
711
+ constructor(message) {
712
+ super(message ?? `Stream message update expired (errcode=${STREAM_EXPIRED_ERRCODE})`);
713
+ this.errcode = STREAM_EXPIRED_ERRCODE;
714
+ this.name = "StreamExpiredError";
715
+ }
716
+ }
717
+ // ============================================================================
644
718
  // 消息发送
645
719
  // ============================================================================
646
720
  /**
@@ -659,8 +733,40 @@ async function sendWeComReply(params) {
659
733
  runtime.error?.(`[wecom] WSClient not connected, cannot send reply`);
660
734
  throw new Error("WSClient not connected");
661
735
  }
736
+ const body = frame.body;
737
+ // 事件回调(aibot_event_callback)没有可用于 replyStream 的有效 req_id,
738
+ // 对该场景改用主动发送 sendMessage,避免 846605 invalid req_id。
739
+ if (body.msgtype === "event") {
740
+ // 中间帧(thinking / 流式增量)直接跳过,仅在最终帧主动发一次文本。
741
+ if (!finish) {
742
+ runtime.log?.(`[plugin -> server] skip non-final stream for event callback, streamId=${streamId}`);
743
+ return streamId;
744
+ }
745
+ const chatId = body.chatid || body.from?.userid;
746
+ if (!chatId) {
747
+ throw new Error("Missing chatId for event callback reply");
748
+ }
749
+ await withTimeout(wsClient.sendMessage(chatId, {
750
+ msgtype: "markdown",
751
+ markdown: { content: text },
752
+ }), REPLY_SEND_TIMEOUT_MS, `Event reply send timed out (streamId=${streamId})`);
753
+ runtime.log?.(`[plugin -> server] event-active-send chatId=${chatId}, finish=${finish}`);
754
+ return streamId;
755
+ }
756
+ // 非事件消息,继续使用 replyStream(被动回复)
662
757
  // 使用 SDK 的 replyStream 方法发送消息,带超时保护
663
- await withTimeout(wsClient.replyStream(frame, streamId, text, finish), REPLY_SEND_TIMEOUT_MS, `Reply send timed out (streamId=${streamId})`);
758
+ try {
759
+ await withTimeout(wsClient.replyStream(frame, streamId, text, finish), REPLY_SEND_TIMEOUT_MS, `Reply send timed out (streamId=${streamId})`);
760
+ }
761
+ catch (err) {
762
+ // 服务端返回 846608:流式消息超过6分钟无法更新,需降级为主动发送
763
+ const errMsg = err?.errmsg || err?.message || String(err);
764
+ if (err?.errcode === STREAM_EXPIRED_ERRCODE ||
765
+ errMsg.includes(String(STREAM_EXPIRED_ERRCODE))) {
766
+ throw new StreamExpiredError(errMsg);
767
+ }
768
+ throw err;
769
+ }
664
770
  runtime.log?.(`[plugin -> server] streamId=${streamId}, finish=${finish}`);
665
771
  return streamId;
666
772
  }
@@ -1058,6 +1164,362 @@ async function uploadAndSendMedia(options) {
1058
1164
  }
1059
1165
  }
1060
1166
 
1167
+ /**
1168
+ * 模板卡片解析器
1169
+ *
1170
+ * 从 LLM 回复文本中提取 markdown JSON 代码块,验证其是否为合法的企业微信模板卡片,
1171
+ * 返回提取到的卡片列表和剩余文本。
1172
+ *
1173
+ * 同时提供 maskTemplateCardBlocks 函数,用于在流式中间帧中隐藏正在构建的卡片代码块,
1174
+ * 避免 JSON 源码暴露给终端用户。
1175
+ */
1176
+ // ============================================================================
1177
+ // LLM 输出字段类型修正
1178
+ // ============================================================================
1179
+ /**
1180
+ * 将 LLM 可能输出的字符串/非法值修正为企业微信 API 要求的整数。
1181
+ * 返回修正后的整数,若无法识别则返回 undefined(由调用方决定是否删除该字段)。
1182
+ */
1183
+ function coerceToInt(value) {
1184
+ if (typeof value === "number" && Number.isFinite(value)) {
1185
+ return Math.round(value);
1186
+ }
1187
+ if (typeof value === "string") {
1188
+ const trimmed = value.trim().toLowerCase();
1189
+ // 纯数字字符串
1190
+ const num = Number(trimmed);
1191
+ if (!Number.isNaN(num) && Number.isFinite(num)) {
1192
+ return Math.round(num);
1193
+ }
1194
+ }
1195
+ return undefined;
1196
+ }
1197
+ /** 将 LLM 可能输出的字符串/非法值修正为布尔值 */
1198
+ function coerceToBool(value) {
1199
+ if (typeof value === "boolean")
1200
+ return value;
1201
+ if (typeof value === "string") {
1202
+ const t = value.trim().toLowerCase();
1203
+ if (t === "true" || t === "1" || t === "yes")
1204
+ return true;
1205
+ if (t === "false" || t === "0" || t === "no")
1206
+ return false;
1207
+ }
1208
+ if (typeof value === "number")
1209
+ return value !== 0;
1210
+ return undefined;
1211
+ }
1212
+ /** checkbox.mode 的语义别名映射 */
1213
+ const MODE_ALIASES = {
1214
+ single: 0,
1215
+ radio: 0,
1216
+ "单选": 0,
1217
+ multi: 1,
1218
+ multiple: 1,
1219
+ "多选": 1,
1220
+ };
1221
+ /**
1222
+ * 修正 checkbox.mode:
1223
+ * - 整数 → 原样
1224
+ * - 字符串数字 "0"/"1" → 整数
1225
+ * - 语义别名 "multi"/"single" 等 → 对应整数
1226
+ * - 无法识别 → 删除(让服务端使用默认值 0)
1227
+ */
1228
+ function coerceCheckboxMode(value) {
1229
+ if (typeof value === "number" && Number.isFinite(value)) {
1230
+ return Math.round(value);
1231
+ }
1232
+ if (typeof value === "string") {
1233
+ const trimmed = value.trim().toLowerCase();
1234
+ if (trimmed in MODE_ALIASES)
1235
+ return MODE_ALIASES[trimmed];
1236
+ const num = Number(trimmed);
1237
+ if (!Number.isNaN(num))
1238
+ return Math.round(num);
1239
+ }
1240
+ return undefined;
1241
+ }
1242
+ /**
1243
+ * 对 LLM 生成的模板卡片 JSON 做字段类型修正,确保符合企业微信 API 的类型要求。
1244
+ *
1245
+ * 修正范围:
1246
+ * - checkbox.mode: uint32(0=单选,1=多选)
1247
+ * - checkbox.disable: bool
1248
+ * - checkbox.option_list[].is_checked: bool
1249
+ * - source.desc_color: int
1250
+ * - quote_area.type: int
1251
+ * - card_action.type: int
1252
+ * - image_text_area.type: int
1253
+ * - horizontal_content_list[].type: int
1254
+ * - jump_list[].type: int
1255
+ * - button_list[].style: int
1256
+ * - button_selection.disable: bool
1257
+ * - select_list[].disable: bool
1258
+ *
1259
+ * 原则:能修就修,修不了就删(让服务端走默认值),绝不阻塞发送。
1260
+ */
1261
+ function normalizeTemplateCardFields(card, log) {
1262
+ const fixes = [];
1263
+ // ── checkbox ──────────────────────────────────────────────────────────
1264
+ const checkbox = card.checkbox;
1265
+ if (checkbox && typeof checkbox === "object") {
1266
+ // mode
1267
+ if ("mode" in checkbox) {
1268
+ const fixed = coerceCheckboxMode(checkbox.mode);
1269
+ if (fixed !== undefined) {
1270
+ if (checkbox.mode !== fixed) {
1271
+ fixes.push(`checkbox.mode: ${JSON.stringify(checkbox.mode)} → ${fixed}`);
1272
+ }
1273
+ checkbox.mode = fixed;
1274
+ }
1275
+ else {
1276
+ fixes.push(`checkbox.mode: ${JSON.stringify(checkbox.mode)} → (deleted, invalid)`);
1277
+ delete checkbox.mode;
1278
+ }
1279
+ }
1280
+ // disable
1281
+ if ("disable" in checkbox) {
1282
+ const fixed = coerceToBool(checkbox.disable);
1283
+ if (fixed !== undefined && checkbox.disable !== fixed) {
1284
+ fixes.push(`checkbox.disable: ${JSON.stringify(checkbox.disable)} → ${fixed}`);
1285
+ checkbox.disable = fixed;
1286
+ }
1287
+ }
1288
+ // option_list[].is_checked
1289
+ if (Array.isArray(checkbox.option_list)) {
1290
+ for (const opt of checkbox.option_list) {
1291
+ if (opt && typeof opt === "object" && "is_checked" in opt) {
1292
+ const fixed = coerceToBool(opt.is_checked);
1293
+ if (fixed !== undefined && opt.is_checked !== fixed) {
1294
+ fixes.push(`checkbox.option_list.is_checked: ${JSON.stringify(opt.is_checked)} → ${fixed}`);
1295
+ opt.is_checked = fixed;
1296
+ }
1297
+ }
1298
+ }
1299
+ }
1300
+ }
1301
+ // ── source.desc_color ────────────────────────────────────────────────
1302
+ const source = card.source;
1303
+ if (source && typeof source === "object" && "desc_color" in source) {
1304
+ const fixed = coerceToInt(source.desc_color);
1305
+ if (fixed !== undefined && source.desc_color !== fixed) {
1306
+ fixes.push(`source.desc_color: ${JSON.stringify(source.desc_color)} → ${fixed}`);
1307
+ source.desc_color = fixed;
1308
+ }
1309
+ }
1310
+ // ── card_action.type ─────────────────────────────────────────────────
1311
+ const cardAction = card.card_action;
1312
+ if (cardAction && typeof cardAction === "object" && "type" in cardAction) {
1313
+ const fixed = coerceToInt(cardAction.type);
1314
+ if (fixed !== undefined && cardAction.type !== fixed) {
1315
+ fixes.push(`card_action.type: ${JSON.stringify(cardAction.type)} → ${fixed}`);
1316
+ cardAction.type = fixed;
1317
+ }
1318
+ }
1319
+ // ── quote_area.type ──────────────────────────────────────────────────
1320
+ const quoteArea = card.quote_area;
1321
+ if (quoteArea && typeof quoteArea === "object" && "type" in quoteArea) {
1322
+ const fixed = coerceToInt(quoteArea.type);
1323
+ if (fixed !== undefined && quoteArea.type !== fixed) {
1324
+ fixes.push(`quote_area.type: ${JSON.stringify(quoteArea.type)} → ${fixed}`);
1325
+ quoteArea.type = fixed;
1326
+ }
1327
+ }
1328
+ // ── image_text_area.type ─────────────────────────────────────────────
1329
+ const imageTextArea = card.image_text_area;
1330
+ if (imageTextArea && typeof imageTextArea === "object" && "type" in imageTextArea) {
1331
+ const fixed = coerceToInt(imageTextArea.type);
1332
+ if (fixed !== undefined && imageTextArea.type !== fixed) {
1333
+ fixes.push(`image_text_area.type: ${JSON.stringify(imageTextArea.type)} → ${fixed}`);
1334
+ imageTextArea.type = fixed;
1335
+ }
1336
+ }
1337
+ // ── horizontal_content_list[].type ───────────────────────────────────
1338
+ if (Array.isArray(card.horizontal_content_list)) {
1339
+ for (const item of card.horizontal_content_list) {
1340
+ if (item && typeof item === "object" && "type" in item) {
1341
+ const fixed = coerceToInt(item.type);
1342
+ if (fixed !== undefined && item.type !== fixed) {
1343
+ fixes.push(`horizontal_content_list.type: ${JSON.stringify(item.type)} → ${fixed}`);
1344
+ item.type = fixed;
1345
+ }
1346
+ }
1347
+ }
1348
+ }
1349
+ // ── jump_list[].type ─────────────────────────────────────────────────
1350
+ if (Array.isArray(card.jump_list)) {
1351
+ for (const item of card.jump_list) {
1352
+ if (item && typeof item === "object" && "type" in item) {
1353
+ const fixed = coerceToInt(item.type);
1354
+ if (fixed !== undefined && item.type !== fixed) {
1355
+ fixes.push(`jump_list.type: ${JSON.stringify(item.type)} → ${fixed}`);
1356
+ item.type = fixed;
1357
+ }
1358
+ }
1359
+ }
1360
+ }
1361
+ // ── button_list[].style ──────────────────────────────────────────────
1362
+ if (Array.isArray(card.button_list)) {
1363
+ for (const btn of card.button_list) {
1364
+ if (btn && typeof btn === "object" && "style" in btn) {
1365
+ const fixed = coerceToInt(btn.style);
1366
+ if (fixed !== undefined && btn.style !== fixed) {
1367
+ fixes.push(`button_list.style: ${JSON.stringify(btn.style)} → ${fixed}`);
1368
+ btn.style = fixed;
1369
+ }
1370
+ }
1371
+ }
1372
+ }
1373
+ // ── button_selection.disable ─────────────────────────────────────────
1374
+ const buttonSelection = card.button_selection;
1375
+ if (buttonSelection && typeof buttonSelection === "object" && "disable" in buttonSelection) {
1376
+ const fixed = coerceToBool(buttonSelection.disable);
1377
+ if (fixed !== undefined && buttonSelection.disable !== fixed) {
1378
+ fixes.push(`button_selection.disable: ${JSON.stringify(buttonSelection.disable)} → ${fixed}`);
1379
+ buttonSelection.disable = fixed;
1380
+ }
1381
+ }
1382
+ // ── select_list[].disable ────────────────────────────────────────────
1383
+ if (Array.isArray(card.select_list)) {
1384
+ for (const sel of card.select_list) {
1385
+ if (sel && typeof sel === "object" && "disable" in sel) {
1386
+ const fixed = coerceToBool(sel.disable);
1387
+ if (fixed !== undefined && sel.disable !== fixed) {
1388
+ fixes.push(`select_list.disable: ${JSON.stringify(sel.disable)} → ${fixed}`);
1389
+ sel.disable = fixed;
1390
+ }
1391
+ }
1392
+ }
1393
+ }
1394
+ if (fixes.length > 0) {
1395
+ log?.(`[template-card-parser] normalizeTemplateCardFields: ${fixes.length} fix(es) applied: ${fixes.join("; ")}`);
1396
+ }
1397
+ return card;
1398
+ }
1399
+ /**
1400
+ * 匹配 markdown 代码块的正则表达式
1401
+ * 支持 ```json ... ``` 和 ``` ... ``` 两种格式
1402
+ */
1403
+ const CODE_BLOCK_RE = /```(?:json)?\s*\n([\s\S]*?)\n```/g;
1404
+ /**
1405
+ * 匹配已闭合的代码块(含 card_type 关键词,用于中间帧遮罩)
1406
+ * 与 CODE_BLOCK_RE 相同,但用于 maskTemplateCardBlocks 中单独实例化
1407
+ */
1408
+ const CLOSED_BLOCK_RE = /```(?:json)?\s*\n([\s\S]*?)\n```/g;
1409
+ /**
1410
+ * 匹配未闭合的代码块尾部(LLM 正在输出中的代码块)
1411
+ * 以 ```json 或 ``` 开头,后面有内容但没有闭合的 ```
1412
+ */
1413
+ const UNCLOSED_BLOCK_RE = /```(?:json)?\s*\n[\s\S]*$/;
1414
+ /**
1415
+ * 从文本中提取模板卡片 JSON 代码块
1416
+ *
1417
+ * 匹配规则:
1418
+ * 1. 匹配所有 ```json ... ``` 或 ``` ... ``` 格式的代码块
1419
+ * 2. 尝试 JSON.parse 解析代码块内容
1420
+ * 3. 检查解析结果中是否包含合法的 card_type 字段
1421
+ * 4. 合法的卡片从原文中移除,不合法的保留
1422
+ *
1423
+ * @param text - LLM 回复的完整文本
1424
+ * @returns 提取结果,包含卡片列表和剩余文本
1425
+ */
1426
+ function extractTemplateCards(text, log) {
1427
+ const cards = [];
1428
+ /** 需要从原文中移除的代码块(记录完整匹配内容) */
1429
+ const blocksToRemove = [];
1430
+ log?.(`[template-card-parser] extractTemplateCards called, textLength=${text.length}`);
1431
+ let match;
1432
+ // 重置正则的 lastIndex,确保从头匹配
1433
+ CODE_BLOCK_RE.lastIndex = 0;
1434
+ let blockIndex = 0;
1435
+ while ((match = CODE_BLOCK_RE.exec(text)) !== null) {
1436
+ const fullMatch = match[0];
1437
+ const jsonContent = match[1].trim();
1438
+ blockIndex++;
1439
+ log?.(`[template-card-parser] Found code block #${blockIndex}, length=${fullMatch.length}, preview=${jsonContent.slice(0, 1000)}...`);
1440
+ // 尝试解析 JSON
1441
+ let parsed;
1442
+ try {
1443
+ parsed = JSON.parse(jsonContent);
1444
+ }
1445
+ catch (e) {
1446
+ // JSON 解析失败,保留在原文中
1447
+ log?.(`[template-card-parser] Code block #${blockIndex} JSON parse failed: ${String(e)}`);
1448
+ continue;
1449
+ }
1450
+ // 检查是否包含合法的 card_type
1451
+ const cardType = parsed.card_type;
1452
+ if (typeof cardType !== "string" || !VALID_CARD_TYPES.includes(cardType)) {
1453
+ // card_type 不合法,保留在原文中
1454
+ log?.(`[template-card-parser] Code block #${blockIndex} has invalid card_type="${String(cardType)}", skipping`);
1455
+ continue;
1456
+ }
1457
+ log?.(`[template-card-parser] Code block #${blockIndex} is valid template card, card_type="${cardType}"`);
1458
+ // 修正 LLM 可能输出的错误字段类型(如 checkbox.mode: "multi" → 1)
1459
+ normalizeTemplateCardFields(parsed, log);
1460
+ // 合法的模板卡片,收集并标记移除
1461
+ cards.push({
1462
+ cardJson: parsed,
1463
+ cardType,
1464
+ });
1465
+ blocksToRemove.push(fullMatch);
1466
+ }
1467
+ // 从原文中移除已提取的代码块,生成剩余文本
1468
+ let remainingText = text;
1469
+ for (const block of blocksToRemove) {
1470
+ remainingText = remainingText.replace(block, "");
1471
+ }
1472
+ // 清理多余空行(连续 3 个以上换行合并为 2 个)
1473
+ remainingText = remainingText.replace(/\n{3,}/g, "\n\n").trim();
1474
+ log?.(`[template-card-parser] Extraction done: ${cards.length} card(s) found, remainingTextLength=${remainingText.length}`);
1475
+ return { cards, remainingText };
1476
+ }
1477
+ /**
1478
+ * 遮罩文本中的模板卡片代码块(用于流式中间帧展示)
1479
+ *
1480
+ * 在 LLM 流式输出过程中,累积文本可能包含:
1481
+ * 1. 已闭合的模板卡片 JSON 代码块 → 替换为友好提示文本
1482
+ * 2. 正在构建中的未闭合代码块 → 截断隐藏,避免 JSON 源码暴露
1483
+ *
1484
+ * 此函数仅做文本替换,不做 JSON 解析验证(中间帧性能优先)。
1485
+ * 只要代码块内容中出现 "card_type" 关键词就认为是模板卡片并遮罩。
1486
+ *
1487
+ * @param text - 当前累积文本
1488
+ * @returns 遮罩后的展示文本
1489
+ */
1490
+ function maskTemplateCardBlocks(text, log) {
1491
+ let masked = text;
1492
+ let closedMaskCount = 0;
1493
+ let unclosedMasked = false;
1494
+ // 步骤一:处理已闭合的代码块
1495
+ CLOSED_BLOCK_RE.lastIndex = 0;
1496
+ masked = masked.replace(CLOSED_BLOCK_RE, (fullMatch, content) => {
1497
+ // 检查代码块内容是否包含 card_type 关键词
1498
+ if (/["']card_type["']/.test(content)) {
1499
+ closedMaskCount++;
1500
+ return "\n\n📋 *正在生成卡片消息...*\n\n";
1501
+ }
1502
+ // 非模板卡片代码块,保留原样
1503
+ return fullMatch;
1504
+ });
1505
+ // 步骤二:处理未闭合的代码块尾部(LLM 仍在输出中)
1506
+ // 检查是否有以 ``` 开头但没有闭合的代码块
1507
+ const unclosedMatch = UNCLOSED_BLOCK_RE.exec(masked);
1508
+ if (unclosedMatch) {
1509
+ const unclosedContent = unclosedMatch[0];
1510
+ // 如果未闭合部分包含 card_type 关键词,说明正在构建模板卡片 → 截断
1511
+ if (/["']card_type["']/.test(unclosedContent)) {
1512
+ unclosedMasked = true;
1513
+ masked = masked.slice(0, unclosedMatch.index) + "\n\n📋 *正在生成卡片消息...*";
1514
+ }
1515
+ }
1516
+ // 有遮罩行为时才打日志,避免每帧都刷屏
1517
+ if (closedMaskCount > 0 || unclosedMasked) {
1518
+ log?.(`[template-card-parser] maskTemplateCardBlocks: closedMasked=${closedMaskCount}, unclosedMasked=${unclosedMasked}, textLength=${text.length}, maskedLength=${masked.length}`);
1519
+ }
1520
+ return masked;
1521
+ }
1522
+
1061
1523
  /**
1062
1524
  * 企业微信群组访问控制模块
1063
1525
  *
@@ -1525,6 +1987,144 @@ const PLUGIN_VERSION = getVersion();
1525
1987
  * - state-manager.ts : 全局状态管理(带 TTL 清理)
1526
1988
  * - timeout.ts : 超时工具
1527
1989
  */
1990
+ /**
1991
+ * 去除文本中的 `<think>...</think>` 标签(支持跨行),返回剩余可见文本。
1992
+ * 用于判断大模型回复中是否包含实际用户可见内容(而非仅有 thinking 推理过程)。
1993
+ */
1994
+ function stripThinkTags(text) {
1995
+ return text;
1996
+ // return text.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
1997
+ }
1998
+ const sentTemplateCardByTaskId = new Map();
1999
+ const TEMPLATE_CARD_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
2000
+ const TEMPLATE_CARD_CACHE_MAX_SIZE = 300;
2001
+ function getTemplateCardCacheKey(accountId, taskId) {
2002
+ return `${accountId}:${taskId}`;
2003
+ }
2004
+ function pruneTemplateCardCache() {
2005
+ const now = Date.now();
2006
+ for (const [key, entry] of sentTemplateCardByTaskId) {
2007
+ if (now - entry.createdAt >= TEMPLATE_CARD_CACHE_TTL_MS) {
2008
+ sentTemplateCardByTaskId.delete(key);
2009
+ }
2010
+ }
2011
+ if (sentTemplateCardByTaskId.size <= TEMPLATE_CARD_CACHE_MAX_SIZE) {
2012
+ return;
2013
+ }
2014
+ const sortedEntries = [...sentTemplateCardByTaskId.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt);
2015
+ const removeCount = sentTemplateCardByTaskId.size - TEMPLATE_CARD_CACHE_MAX_SIZE;
2016
+ for (const [key] of sortedEntries.slice(0, removeCount)) {
2017
+ sentTemplateCardByTaskId.delete(key);
2018
+ }
2019
+ }
2020
+ function cloneTemplateCard(card) {
2021
+ return JSON.parse(JSON.stringify(card));
2022
+ }
2023
+ function saveTemplateCardToCache(params) {
2024
+ const { accountId, templateCard, runtime } = params;
2025
+ const taskId = templateCard.task_id;
2026
+ if (!taskId) {
2027
+ runtime.log?.("[wecom][template-card] Skip cache: template card has no task_id");
2028
+ return;
2029
+ }
2030
+ sentTemplateCardByTaskId.set(getTemplateCardCacheKey(accountId, taskId), {
2031
+ templateCard: cloneTemplateCard(templateCard),
2032
+ createdAt: Date.now(),
2033
+ });
2034
+ pruneTemplateCardCache();
2035
+ }
2036
+ function getTemplateCardFromCache(accountId, taskId) {
2037
+ pruneTemplateCardCache();
2038
+ const cached = sentTemplateCardByTaskId.get(getTemplateCardCacheKey(accountId, taskId));
2039
+ if (!cached) {
2040
+ return undefined;
2041
+ }
2042
+ return cloneTemplateCard(cached.templateCard);
2043
+ }
2044
+ function buildSelectedOptionMap(templateCardEvent) {
2045
+ const selectedMap = new Map();
2046
+ const selectedItems = templateCardEvent?.selected_items?.selected_item ?? [];
2047
+ for (const item of selectedItems) {
2048
+ const questionKey = item.question_key?.trim();
2049
+ if (!questionKey) {
2050
+ continue;
2051
+ }
2052
+ const optionIds = item.option_ids?.option_id?.filter(Boolean) ?? [];
2053
+ selectedMap.set(questionKey, optionIds);
2054
+ }
2055
+ return selectedMap;
2056
+ }
2057
+ function applySelectedStateToTemplateCard(params) {
2058
+ const { templateCard, selectedMap, templateCardEvent } = params;
2059
+ const nextCard = cloneTemplateCard(templateCard);
2060
+ if (templateCardEvent?.task_id) {
2061
+ nextCard.task_id = templateCardEvent.task_id;
2062
+ }
2063
+ if (templateCardEvent?.card_type) {
2064
+ nextCard.card_type = templateCardEvent.card_type;
2065
+ }
2066
+ // 交互完成后将提交按钮文案更新为已提交,提升用户感知
2067
+ if (nextCard.submit_button?.text) {
2068
+ nextCard.submit_button.text = "已提交";
2069
+ }
2070
+ if (nextCard.checkbox?.question_key) {
2071
+ const selectedIds = selectedMap.get(nextCard.checkbox.question_key) ?? [];
2072
+ nextCard.checkbox.disable = true;
2073
+ if (Array.isArray(nextCard.checkbox.option_list)) {
2074
+ nextCard.checkbox.option_list = nextCard.checkbox.option_list.map((option) => ({
2075
+ ...option,
2076
+ is_checked: selectedIds.includes(option.id),
2077
+ }));
2078
+ }
2079
+ }
2080
+ if (Array.isArray(nextCard.select_list)) {
2081
+ nextCard.select_list = nextCard.select_list.map((selection) => {
2082
+ const selectedIds = selectedMap.get(selection.question_key) ?? [];
2083
+ return {
2084
+ ...selection,
2085
+ disable: true,
2086
+ selected_id: selectedIds[0] ?? selection.selected_id,
2087
+ };
2088
+ });
2089
+ }
2090
+ if (nextCard.button_selection?.question_key) {
2091
+ const selectedIds = selectedMap.get(nextCard.button_selection.question_key) ?? [];
2092
+ nextCard.button_selection.disable = true;
2093
+ if (selectedIds[0]) {
2094
+ nextCard.button_selection.selected_id = selectedIds[0];
2095
+ }
2096
+ }
2097
+ return nextCard;
2098
+ }
2099
+ async function updateTemplateCardOnEvent(params) {
2100
+ const { frame, accountId, runtime, wsClient } = params;
2101
+ const body = frame.body;
2102
+ const templateCardEvent = body.event?.template_card_event;
2103
+ const taskId = templateCardEvent?.task_id;
2104
+ if (!taskId) {
2105
+ runtime.log?.(`[${accountId}] [template-card-update] Skip update: missing task_id in callback`);
2106
+ return;
2107
+ }
2108
+ const cachedCard = getTemplateCardFromCache(accountId, taskId);
2109
+ if (!cachedCard) {
2110
+ runtime.log?.(`[${accountId}] [template-card-update] Skip update: task_id=${taskId} not found in cache`);
2111
+ return;
2112
+ }
2113
+ const selectedMap = buildSelectedOptionMap(templateCardEvent);
2114
+ const updatedCard = applySelectedStateToTemplateCard({
2115
+ templateCard: cachedCard,
2116
+ selectedMap,
2117
+ templateCardEvent,
2118
+ });
2119
+ await wsClient.updateTemplateCard(frame, updatedCard, [body.from.userid]);
2120
+ runtime.log?.(`[${accountId}] [template-card-update] Updated card by task_id=${taskId}`);
2121
+ // 将更新后的卡片写回缓存,后续多次点击时状态保持一致
2122
+ saveTemplateCardToCache({
2123
+ accountId,
2124
+ templateCard: updatedCard,
2125
+ runtime,
2126
+ });
2127
+ }
1528
2128
  // ============================================================================
1529
2129
  // 媒体本地路径白名单扩展
1530
2130
  // ============================================================================
@@ -1655,7 +2255,7 @@ function buildMessageContext(frame, account, config, text, mediaList, quoteConte
1655
2255
  * 发送"思考中"消息
1656
2256
  */
1657
2257
  async function sendThinkingReply(params) {
1658
- const { wsClient, frame, streamId, runtime } = params;
2258
+ const { wsClient, frame, streamId, runtime, state } = params;
1659
2259
  try {
1660
2260
  await sendWeComReply({
1661
2261
  wsClient,
@@ -1667,7 +2267,13 @@ async function sendThinkingReply(params) {
1667
2267
  });
1668
2268
  }
1669
2269
  catch (err) {
1670
- runtime.error?.(`[wecom] Failed to send thinking message: ${String(err)}`);
2270
+ if (err instanceof StreamExpiredError && state) {
2271
+ state.streamExpired = true;
2272
+ runtime.log?.(`[wecom] Stream expired during thinking reply, will fallback to proactive send`);
2273
+ }
2274
+ else {
2275
+ runtime.error?.(`[wecom] Failed to send thinking message: ${String(err)}`);
2276
+ }
1671
2277
  }
1672
2278
  }
1673
2279
  /**
@@ -1681,7 +2287,7 @@ async function sendMediaBatch(ctx, mediaUrls) {
1681
2287
  const body = frame.body;
1682
2288
  const chatId = body.chatid || body.from.userid;
1683
2289
  const mediaLocalRoots = await getExtendedMediaLocalRoots(account.config);
1684
- runtime.log?.(`[wecom][debug] mediaLocalRoots=${JSON.stringify(mediaLocalRoots)}, mediaUrls=${JSON.stringify(mediaUrls)}, hasText=${!!state.hasText}`);
2290
+ runtime.log?.(`[wecom][debug] mediaLocalRoots=${JSON.stringify(mediaLocalRoots)}, mediaUrls=${JSON.stringify(mediaUrls)}`);
1685
2291
  for (const mediaUrl of mediaUrls) {
1686
2292
  const result = await uploadAndSendMedia({
1687
2293
  wsClient,
@@ -1715,6 +2321,7 @@ async function sendMediaBatch(ctx, mediaUrls) {
1715
2321
  * 替换掉 thinking 动画,否则 thinking 会一直残留。
1716
2322
  *
1717
2323
  * 关闭策略(按优先级):
2324
+ * 0. [新增] 有模板卡片代码块 → 提取卡片并主动发送,用剩余文本关闭流
1718
2325
  * 1. 有可见文本 → 用完整文本关闭
1719
2326
  * 2. 有媒体成功发送(通过 deliver 回调) → 用友好提示"文件已发送"
1720
2327
  * 3. 媒体发送失败 → 直接用错误摘要替换 thinking
@@ -1722,11 +2329,49 @@ async function sendMediaBatch(ctx, mediaUrls) {
1722
2329
  * (agent 可能已通过内置 message 工具直接发送了文件,
1723
2330
  * 该路径走 outbound.sendMedia 完全绕过 deliver 回调,
1724
2331
  * 所以 state 中无记录,但文件已实际送达)
2332
+ *
2333
+ * 降级策略:
2334
+ * - 当 streamExpired=true(errcode 846608)时,流式通道已不可用(>6分钟),
2335
+ * 改用 wsClient.sendMessage 主动发送完整文本。
1725
2336
  */
1726
2337
  async function finishThinkingStream(ctx) {
1727
2338
  const { wsClient, frame, state, runtime } = ctx;
2339
+ const body = frame.body;
2340
+ const chatId = body.chatid || body.from.userid;
2341
+ const visibleText = stripThinkTags(state.accumulatedText);
2342
+ // ── 模板卡片检测与发送 ──────────────────────────────────────────────
2343
+ // 在确定 finishText 之前,先检查累积文本中是否包含模板卡片 JSON 代码块。
2344
+ // 若检测到合法卡片,通过 sendMessage 主动发送后,用剩余文本关闭流。
2345
+ if (visibleText) {
2346
+ runtime.log?.(`[wecom][template-card] finishThinkingStream: visibleText exists, length=${visibleText.length}, running extractTemplateCards...`);
2347
+ const logFn = (...args) => {
2348
+ runtime.log?.(...args);
2349
+ };
2350
+ const { cards, remainingText } = extractTemplateCards(state.accumulatedText, logFn);
2351
+ runtime.log?.(`[wecom][template-card] finishThinkingStream: extractTemplateCards result — cards=${cards.length}, remainingTextLength=${remainingText.length}`);
2352
+ if (cards.length > 0) {
2353
+ runtime.log?.(`[wecom][template-card] finishThinkingStream: ${cards.length} card(s) detected, card_types=[${cards.map(c => c.cardType).join(", ")}]`);
2354
+ await sendTemplateCards(ctx, cards);
2355
+ // 用剩余文本关闭流(可能为空)
2356
+ const trimmedRemaining = stripThinkTags(remainingText);
2357
+ const finishText = trimmedRemaining
2358
+ ? remainingText
2359
+ : (state.hasTemplateCard ? "📋 卡片消息已发送。" : "✅ 处理完成。");
2360
+ runtime.log?.(`[wecom][template-card] finishThinkingStream: closing stream with finishText="${finishText.slice(0, 100)}...", hasTemplateCard=${state.hasTemplateCard}`);
2361
+ await sendWeComReply({ wsClient, frame, text: finishText, runtime, finish: true, streamId: state.streamId });
2362
+ return;
2363
+ }
2364
+ }
2365
+ else {
2366
+ runtime.log?.(`[wecom][template-card] finishThinkingStream: no visibleText, skipping template card extraction`);
2367
+ }
2368
+ // ── 模板卡片检测结束 ────────────────────────────────────────────────
1728
2369
  let finishText = state.accumulatedText;
1729
- if (state.hasMedia) {
2370
+ if (visibleText) {
2371
+ // 有可见文本:用完整文本关闭流(覆盖 thinking 为真实内容)
2372
+ finishText = state.accumulatedText;
2373
+ }
2374
+ else if (state.hasMedia) {
1730
2375
  if (state.hasMediaFailed && state.mediaErrorSummary) {
1731
2376
  // 媒体成功发送:用友好提示告知用户
1732
2377
  finishText = finishText ? `${finishText}\n\n${state.mediaErrorSummary}` : state.mediaErrorSummary;
@@ -1739,7 +2384,63 @@ async function finishThinkingStream(ctx) {
1739
2384
  // finishText = "✅ 处理完成。";
1740
2385
  // }
1741
2386
  if (finishText) {
1742
- await sendWeComReply({ wsClient, frame, text: finishText, runtime, finish: true, streamId: state.streamId });
2387
+ // 尝试流式发送;若已知过期或发送时发现过期,统一降级为主动发送
2388
+ let expired = state.streamExpired;
2389
+ if (!expired) {
2390
+ try {
2391
+ await sendWeComReply({ wsClient, frame, text: finishText, runtime, finish: true, streamId: state.streamId });
2392
+ }
2393
+ catch (err) {
2394
+ if (err instanceof StreamExpiredError) {
2395
+ expired = true;
2396
+ }
2397
+ else {
2398
+ throw err;
2399
+ }
2400
+ }
2401
+ }
2402
+ if (expired) {
2403
+ runtime.log?.(`[wecom] Stream expired, sending final text via sendMessage (proactive)`);
2404
+ await wsClient.sendMessage(chatId, {
2405
+ msgtype: "markdown",
2406
+ markdown: { content: finishText },
2407
+ });
2408
+ }
2409
+ }
2410
+ }
2411
+ /**
2412
+ * 逐个发送已提取的模板卡片(通过 wsClient.sendMessage 主动推送)
2413
+ *
2414
+ * 发送失败不阻塞流程,仅记录错误日志。
2415
+ */
2416
+ async function sendTemplateCards(ctx, cards) {
2417
+ const { wsClient, frame, state, runtime, account } = ctx;
2418
+ const body = frame.body;
2419
+ const chatId = body.chatid || body.from.userid;
2420
+ for (const card of cards) {
2421
+ try {
2422
+ runtime.log?.(`[wecom][template-card] Sending card_type=${card.cardType} to chatId=${chatId}`);
2423
+ const rawTemplateCard = card.cardJson;
2424
+ if (typeof rawTemplateCard.card_type !== "string") {
2425
+ runtime.error?.("[wecom][template-card] Skip sending invalid card: missing card_type");
2426
+ continue;
2427
+ }
2428
+ const templateCard = rawTemplateCard;
2429
+ await wsClient.sendMessage(chatId, {
2430
+ msgtype: "template_card",
2431
+ template_card: templateCard,
2432
+ });
2433
+ state.hasTemplateCard = true;
2434
+ saveTemplateCardToCache({
2435
+ accountId: account.accountId,
2436
+ templateCard,
2437
+ runtime,
2438
+ });
2439
+ runtime.log?.(`[wecom][template-card] Card sent successfully: card_type=${card.cardType}`);
2440
+ }
2441
+ catch (err) {
2442
+ runtime.error?.(`[wecom][template-card] Failed to send card: card_type=${card.cardType}, error=${JSON.stringify(err)}`);
2443
+ }
1743
2444
  }
1744
2445
  }
1745
2446
  /**
@@ -1762,11 +2463,25 @@ async function routeAndDispatchMessage(params) {
1762
2463
  await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
1763
2464
  ctx: ctxPayload,
1764
2465
  cfg: config,
2466
+ // replyResolver: async (ctx, opts) => {
2467
+ // const startTime = Date.now();
2468
+ // const TEN_MINUTES = 7 * 60 * 1000;
2469
+ //
2470
+ // console.log('开始输出内容');
2471
+ //
2472
+ // while (Date.now() - startTime < TEN_MINUTES) {
2473
+ // // 每隔一段时间发送一个 block reply
2474
+ // await opts?.onBlockReply?.({ text: `输出内容 ${new Date().toISOString()}` });
2475
+ // await new Promise(resolve => setTimeout(resolve, 30 * 1000)); // 每5秒输出一次
2476
+ // }
2477
+ //
2478
+ // return { text: "10分钟输出完成" }; // 最终回复
2479
+ // },
1765
2480
  dispatcherOptions: {
1766
2481
  onReplyStart: async () => {
1767
2482
  if (!isShowThink && state.streamId && !state.accumulatedText) {
1768
2483
  try {
1769
- await sendThinkingReply({ wsClient, frame, streamId: state.streamId, runtime });
2484
+ await sendThinkingReply({ wsClient, frame, streamId: state.streamId, runtime, state });
1770
2485
  }
1771
2486
  catch (e) {
1772
2487
  runtime.error?.(`[wecom] sendThinkingReply threw err: ${String(e)}`);
@@ -1799,9 +2514,26 @@ async function routeAndDispatchMessage(params) {
1799
2514
  runtime.error?.(`[wecom] sendMediaBatch threw: ${errMsg}`);
1800
2515
  }
1801
2516
  }
1802
- // 中间帧:有可见文本时流式更新
1803
- if (info.kind !== "final" && state.hasText && state.accumulatedText) {
1804
- await sendWeComReply({ wsClient, frame, text: state.accumulatedText, runtime, finish: false, streamId: state.streamId });
2517
+ // 中间帧:有可见文本时流式更新(流式过期后跳过,等 deliver 完成后主动发送)
2518
+ // 使用 maskTemplateCardBlocks 遮罩正在构建中的模板卡片代码块,
2519
+ // 避免 JSON 源码在流式输出过程中暴露给终端用户
2520
+ if (info.kind !== "final" && state.accumulatedText && !state.streamExpired) {
2521
+ try {
2522
+ const displayText = maskTemplateCardBlocks(state.accumulatedText, (...args) => runtime.log?.(...args));
2523
+ if (displayText !== state.accumulatedText) {
2524
+ runtime.log?.(`[wecom][template-card] Mid-frame masked: original=${state.accumulatedText.length}chars, masked=${displayText.length}chars`);
2525
+ }
2526
+ await sendWeComReply({ wsClient, frame, text: displayText, runtime, finish: false, streamId: state.streamId });
2527
+ }
2528
+ catch (err) {
2529
+ if (err instanceof StreamExpiredError) {
2530
+ state.streamExpired = true;
2531
+ runtime.log?.(`[wecom] Stream expired during intermediate reply, will fallback to proactive send`);
2532
+ }
2533
+ else {
2534
+ throw err;
2535
+ }
2536
+ }
1805
2537
  }
1806
2538
  },
1807
2539
  onError: (err, info) => {
@@ -1926,7 +2658,7 @@ async function processWeComMessage(params) {
1926
2658
  const ctxPayload = buildMessageContext(frame, account, config, text, mediaList, quoteContent);
1927
2659
  // runtime.log?.(`[plugin -> openclaw] body=${text}, mediaPaths=${JSON.stringify(mediaList.map(m => m.path))}${quoteContent ? `, quote=${quoteContent}` : ''}`);
1928
2660
  try {
1929
- await withTimeout(routeAndDispatchMessage({
2661
+ await routeAndDispatchMessage({
1930
2662
  ctxPayload,
1931
2663
  config,
1932
2664
  account,
@@ -1935,10 +2667,10 @@ async function processWeComMessage(params) {
1935
2667
  state,
1936
2668
  runtime,
1937
2669
  onCleanup: cleanupState,
1938
- }), MESSAGE_PROCESS_TIMEOUT_MS, `Message processing timed out (msgId=${messageId})`);
2670
+ });
1939
2671
  }
1940
2672
  catch (err) {
1941
- runtime.error?.(`[wecom][plugin] Message processing failed or timed out: ${String(err)}`);
2673
+ runtime.error?.(`[wecom][plugin] Message processing failed: ${String(err)}`);
1942
2674
  cleanupState();
1943
2675
  }
1944
2676
  }
@@ -1974,6 +2706,7 @@ function createSdkLogger(runtime, accountId) {
1974
2706
  async function monitorWeComProvider(options) {
1975
2707
  const { account, config, runtime, abortSignal, setStatus } = options;
1976
2708
  runtime.log?.(`[${account.accountId}] [${PLUGIN_VERSION}] Initializing WSClient with SDK...`);
2709
+ runtime.error?.(`[${account.accountId}] [diag] monitor boot marker: build=20260325-event-debug-1`);
1977
2710
  // 启动消息状态定期清理
1978
2711
  startMessageStateCleanup();
1979
2712
  return new Promise((resolve, reject) => {
@@ -2112,7 +2845,7 @@ async function monitorWeComProvider(options) {
2112
2845
  // runtime.error?.(`[${account.accountId}] Failed to reply enter_check_update: ${String(err)}`);
2113
2846
  }
2114
2847
  });
2115
- // 监听所有消息
2848
+ // 监听普通消息
2116
2849
  wsClient.on("message", async (frame) => {
2117
2850
  try {
2118
2851
  await processWeComMessage({
@@ -2127,6 +2860,44 @@ async function monitorWeComProvider(options) {
2127
2860
  runtime.error?.(`[${account.accountId}] Failed to process message: ${String(err)}`);
2128
2861
  }
2129
2862
  });
2863
+ // 监听所有事件回调(aibot_event_callback)。
2864
+ // 这里使用通用 event 监听,再按 eventtype 分发,兼容不同 SDK 版本在细分事件名上的差异。
2865
+ wsClient.on("event", async (frame) => {
2866
+ try {
2867
+ const eventBody = frame.body;
2868
+ const eventType = eventBody.event?.eventtype;
2869
+ runtime.log?.(`[${account.accountId}] Received event callback: eventtype=${eventType ?? ""}, msgid=${eventBody.msgid ?? ""}`);
2870
+ runtime.error?.(`[${account.accountId}] [diag] event-listener fired: eventtype=${eventType ?? ""}, msgid=${eventBody.msgid ?? ""}`);
2871
+ if (eventType !== "template_card_event") {
2872
+ return;
2873
+ }
2874
+ const templateCardEvent = eventBody.event?.template_card_event;
2875
+ runtime.log?.(`[${account.accountId}] Received template_card_event: event_key=${templateCardEvent?.event_key ?? ""}, task_id=${templateCardEvent?.task_id ?? ""}`);
2876
+ try {
2877
+ await updateTemplateCardOnEvent({
2878
+ frame,
2879
+ accountId: account.accountId,
2880
+ runtime,
2881
+ wsClient,
2882
+ });
2883
+ }
2884
+ catch (updateErr) {
2885
+ runtime.error?.(`[${account.accountId}] [template-card-update] Failed to update template card: ${String(updateErr)}`);
2886
+ }
2887
+ await processWeComMessage({
2888
+ frame,
2889
+ account,
2890
+ config,
2891
+ runtime,
2892
+ wsClient,
2893
+ });
2894
+ }
2895
+ catch (err) {
2896
+ runtime.error?.(`[${account.accountId}] Failed to process template_card_event: ${String(err)}`);
2897
+ }
2898
+ });
2899
+ runtime.log?.(`[${account.accountId}] Event listeners attached: message + event(template_card_event)`);
2900
+ runtime.error?.(`[${account.accountId}] [diag] listeners-ready marker`);
2130
2901
  // 启动前预热 reqId 缓存,确保完成后再建立连接,避免 getSync 在预热完成前返回 undefined
2131
2902
  warmupReqIdStore(account.accountId, (...args) => runtime.log?.(...args))
2132
2903
  .then((count) => {
@@ -3529,7 +4300,8 @@ const plugin = {
3529
4300
  }
3530
4301
  return {
3531
4302
  appendSystemContext: [
3532
- "重要:涉及发送图片/视频/语音/文件给用户时,请务必使用 `MEDIA:` 指令。详见 wecom-send-media 这个 skill(技能)。"
4303
+ "重要:涉及发送图片/视频/语音/文件给用户时,请务必使用 `MEDIA:` 指令。详见 wecom-send-media 这个 skill(技能)。",
4304
+ "重要:当需要向用户发送结构化卡片消息(如通知、投票、按钮选择等)时,请在回复中直接输出 JSON 代码块(```json ... ```),其中 card_type 字段标明卡片类型。详见 wecom-send-template-card 技能。"
3533
4305
  ].join("\n"),
3534
4306
  };
3535
4307
  });