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

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.esm.js CHANGED
@@ -486,6 +486,17 @@ const CMD_ENTER_EVENT_REPLY = "ww_ai_robot_enter_event";
486
486
  // ============================================================================
487
487
  /** WSClient scene 参数:企微 OpenClaw 场景 */
488
488
  const SCENE_WECOM_OPENCLAW = 1;
489
+ // ============================================================================
490
+ // 模板卡片配置
491
+ // ============================================================================
492
+ /** 合法的模板卡片 card_type 列表 */
493
+ const VALID_CARD_TYPES = [
494
+ "text_notice",
495
+ "news_notice",
496
+ "button_interaction",
497
+ "vote_interaction",
498
+ "multiple_interaction",
499
+ ];
489
500
 
490
501
  /**
491
502
  * 企业微信消息内容解析模块
@@ -496,7 +507,47 @@ const SCENE_WECOM_OPENCLAW = 1;
496
507
  // 解析函数
497
508
  // ============================================================================
498
509
  /**
499
- * 解析消息内容(支持单条消息、图文混排和引用消息)
510
+ * 将模板卡片事件回调格式化为可继续路由给大模型的文本。
511
+ *
512
+ * 这样后续 Agent 可以直接从 question_key / option_id 中理解用户的真实选择。
513
+ */
514
+ function buildTemplateCardEventText(body) {
515
+ const templateCardEvent = body.event?.template_card_event;
516
+ if (body.msgtype !== "event" ||
517
+ body.event?.eventtype !== "template_card_event" ||
518
+ !templateCardEvent) {
519
+ return undefined;
520
+ }
521
+ const selectedItems = templateCardEvent.selected_items?.selected_item ?? [];
522
+ const selectedLines = selectedItems.map((item) => {
523
+ const questionKey = item.question_key?.trim() || "unknown_question";
524
+ const optionIds = item.option_ids?.option_id?.filter(Boolean) ?? [];
525
+ return `- ${questionKey}: ${optionIds.length > 0 ? optionIds.join(", ") : "(未选择)"}`;
526
+ });
527
+ const senderUserId = body.from?.userid || "";
528
+ const senderCorpId = body.from?.corpid || "";
529
+ const chatId = body.chatid || senderUserId;
530
+ return [
531
+ "[企业微信模板卡片回调]",
532
+ `event_type(事件类型): template_card_event`,
533
+ body.msgid ? `msgid(消息 id): ${body.msgid}` : undefined,
534
+ body.aibotid ? `aibotid(机器人 id): ${body.aibotid}` : undefined,
535
+ body.chattype ? `chat_type(会话类型): ${body.chattype}` : undefined,
536
+ chatId ? `chat_id(会话 id): ${chatId}` : undefined,
537
+ senderCorpId ? `from.corpid(企业 id): ${senderCorpId}` : undefined,
538
+ senderUserId ? `from.userid(发送人 id): ${senderUserId}` : undefined,
539
+ senderUserId ? `sender_userid(发送人 id): ${senderUserId}` : undefined,
540
+ templateCardEvent.card_type ? `card_type(卡片类型): ${templateCardEvent.card_type}` : undefined,
541
+ templateCardEvent.event_key ? `event_key(事件 key): ${templateCardEvent.event_key}` : undefined,
542
+ templateCardEvent.task_id ? `task_id(任务 id): ${templateCardEvent.task_id}` : undefined,
543
+ selectedLines.length > 0 ? "selected_items(选择项):" : "selected_items(选择项): []",
544
+ ...selectedLines,
545
+ ]
546
+ .filter((line) => Boolean(line))
547
+ .join("\n");
548
+ }
549
+ /**
550
+ * 解析消息内容(支持单条消息、图文混排、事件回调和引用消息)
500
551
  * @returns 提取的文本数组、图片URL数组和引用消息内容
501
552
  */
502
553
  function parseMessageContent(body) {
@@ -506,6 +557,14 @@ function parseMessageContent(body) {
506
557
  const fileUrls = [];
507
558
  const fileAesKeys = new Map();
508
559
  let quoteContent;
560
+ // 处理模板卡片事件回调
561
+ if (body.msgtype === "event") {
562
+ const eventText = buildTemplateCardEventText(body);
563
+ if (eventText) {
564
+ textParts.push(eventText);
565
+ }
566
+ return { textParts, imageUrls, imageAesKeys, fileUrls, fileAesKeys, quoteContent };
567
+ }
509
568
  // 处理图文混排消息
510
569
  if (body.msgtype === "mixed" && body.mixed?.msg_item) {
511
570
  for (const item of body.mixed.msg_item) {
@@ -647,6 +706,27 @@ async function sendWeComReply(params) {
647
706
  runtime.error?.(`[wecom] WSClient not connected, cannot send reply`);
648
707
  throw new Error("WSClient not connected");
649
708
  }
709
+ const body = frame.body;
710
+ // 事件回调(aibot_event_callback)没有可用于 replyStream 的有效 req_id,
711
+ // 对该场景改用主动发送 sendMessage,避免 846605 invalid req_id。
712
+ if (body.msgtype === "event") {
713
+ // 中间帧(thinking / 流式增量)直接跳过,仅在最终帧主动发一次文本。
714
+ if (!finish) {
715
+ runtime.log?.(`[plugin -> server] skip non-final stream for event callback, streamId=${streamId}`);
716
+ return streamId;
717
+ }
718
+ const chatId = body.chatid || body.from?.userid;
719
+ if (!chatId) {
720
+ throw new Error("Missing chatId for event callback reply");
721
+ }
722
+ await withTimeout(wsClient.sendMessage(chatId, {
723
+ msgtype: "markdown",
724
+ markdown: { content: text },
725
+ }), REPLY_SEND_TIMEOUT_MS, `Event reply send timed out (streamId=${streamId})`);
726
+ runtime.log?.(`[plugin -> server] event-active-send chatId=${chatId}, finish=${finish}`);
727
+ return streamId;
728
+ }
729
+ // 非事件消息,继续使用 replyStream(被动回复)
650
730
  // 使用 SDK 的 replyStream 方法发送消息,带超时保护
651
731
  try {
652
732
  await withTimeout(wsClient.replyStream(frame, streamId, text, finish), REPLY_SEND_TIMEOUT_MS, `Reply send timed out (streamId=${streamId})`);
@@ -1057,6 +1137,640 @@ async function uploadAndSendMedia(options) {
1057
1137
  }
1058
1138
  }
1059
1139
 
1140
+ /**
1141
+ * 模板卡片解析器
1142
+ *
1143
+ * 从 LLM 回复文本中提取 markdown JSON 代码块,验证其是否为合法的企业微信模板卡片,
1144
+ * 返回提取到的卡片列表和剩余文本。
1145
+ *
1146
+ * 同时提供 maskTemplateCardBlocks 函数,用于在流式中间帧中隐藏正在构建的卡片代码块,
1147
+ * 避免 JSON 源码暴露给终端用户。
1148
+ */
1149
+ // ============================================================================
1150
+ // LLM 输出字段类型修正
1151
+ // ============================================================================
1152
+ /**
1153
+ * 将 LLM 可能输出的字符串/非法值修正为企业微信 API 要求的整数。
1154
+ * 返回修正后的整数,若无法识别则返回 undefined(由调用方决定是否删除该字段)。
1155
+ */
1156
+ function coerceToInt(value) {
1157
+ if (typeof value === "number" && Number.isFinite(value)) {
1158
+ return Math.round(value);
1159
+ }
1160
+ if (typeof value === "string") {
1161
+ const trimmed = value.trim().toLowerCase();
1162
+ // 纯数字字符串
1163
+ const num = Number(trimmed);
1164
+ if (!Number.isNaN(num) && Number.isFinite(num)) {
1165
+ return Math.round(num);
1166
+ }
1167
+ }
1168
+ return undefined;
1169
+ }
1170
+ /** 将 LLM 可能输出的字符串/非法值修正为布尔值 */
1171
+ function coerceToBool(value) {
1172
+ if (typeof value === "boolean")
1173
+ return value;
1174
+ if (typeof value === "string") {
1175
+ const t = value.trim().toLowerCase();
1176
+ if (t === "true" || t === "1" || t === "yes")
1177
+ return true;
1178
+ if (t === "false" || t === "0" || t === "no")
1179
+ return false;
1180
+ }
1181
+ if (typeof value === "number")
1182
+ return value !== 0;
1183
+ return undefined;
1184
+ }
1185
+ /** checkbox.mode 的语义别名映射 */
1186
+ const MODE_ALIASES = {
1187
+ single: 0,
1188
+ radio: 0,
1189
+ "单选": 0,
1190
+ multi: 1,
1191
+ multiple: 1,
1192
+ "多选": 1,
1193
+ };
1194
+ /**
1195
+ * 修正 checkbox.mode:
1196
+ * - 0 → 单选,1 → 多选,仅允许这两个值
1197
+ * - 字符串数字 "0"/"1" → 整数
1198
+ * - 语义别名 "multi"/"single" 等 → 对应整数
1199
+ * - 其他正整数(如 2)→ clamp 到 1(多选)
1200
+ * - 无法识别 → 删除(让服务端使用默认值 0)
1201
+ */
1202
+ function coerceCheckboxMode(value) {
1203
+ let num;
1204
+ if (typeof value === "number" && Number.isFinite(value)) {
1205
+ num = Math.round(value);
1206
+ }
1207
+ else if (typeof value === "string") {
1208
+ const trimmed = value.trim().toLowerCase();
1209
+ if (trimmed in MODE_ALIASES)
1210
+ return MODE_ALIASES[trimmed];
1211
+ const parsed = Number(trimmed);
1212
+ if (!Number.isNaN(parsed))
1213
+ num = Math.round(parsed);
1214
+ }
1215
+ if (num === undefined)
1216
+ return undefined;
1217
+ // mode 只允许 0(单选)或 1(多选),超出范围 clamp
1218
+ if (num <= 0)
1219
+ return 0;
1220
+ return 1;
1221
+ }
1222
+ /**
1223
+ * 对 LLM 生成的模板卡片 JSON 做字段类型修正,确保符合企业微信 API 的类型要求。
1224
+ *
1225
+ * 修正范围:
1226
+ * - checkbox.mode: uint32(0=单选,1=多选)
1227
+ * - checkbox.disable: bool
1228
+ * - checkbox.option_list[].is_checked: bool
1229
+ * - source.desc_color: int
1230
+ * - quote_area.type: int
1231
+ * - card_action.type: int
1232
+ * - image_text_area.type: int
1233
+ * - horizontal_content_list[].type: int
1234
+ * - jump_list[].type: int
1235
+ * - button_list[].style: int
1236
+ * - button_selection.disable: bool
1237
+ * - select_list[].disable: bool
1238
+ *
1239
+ * 原则:能修就修,修不了就删(让服务端走默认值),绝不阻塞发送。
1240
+ */
1241
+ function normalizeTemplateCardFields(card, log) {
1242
+ const fixes = [];
1243
+ // ── checkbox ──────────────────────────────────────────────────────────
1244
+ const checkbox = card.checkbox;
1245
+ if (checkbox && typeof checkbox === "object") {
1246
+ // mode
1247
+ if ("mode" in checkbox) {
1248
+ const fixed = coerceCheckboxMode(checkbox.mode);
1249
+ if (fixed !== undefined) {
1250
+ if (checkbox.mode !== fixed) {
1251
+ fixes.push(`checkbox.mode: ${JSON.stringify(checkbox.mode)} → ${fixed}`);
1252
+ }
1253
+ checkbox.mode = fixed;
1254
+ }
1255
+ else {
1256
+ fixes.push(`checkbox.mode: ${JSON.stringify(checkbox.mode)} → (deleted, invalid)`);
1257
+ delete checkbox.mode;
1258
+ }
1259
+ }
1260
+ // disable
1261
+ if ("disable" in checkbox) {
1262
+ const fixed = coerceToBool(checkbox.disable);
1263
+ if (fixed !== undefined && checkbox.disable !== fixed) {
1264
+ fixes.push(`checkbox.disable: ${JSON.stringify(checkbox.disable)} → ${fixed}`);
1265
+ checkbox.disable = fixed;
1266
+ }
1267
+ }
1268
+ // option_list[].is_checked
1269
+ if (Array.isArray(checkbox.option_list)) {
1270
+ for (const opt of checkbox.option_list) {
1271
+ if (opt && typeof opt === "object" && "is_checked" in opt) {
1272
+ const fixed = coerceToBool(opt.is_checked);
1273
+ if (fixed !== undefined && opt.is_checked !== fixed) {
1274
+ fixes.push(`checkbox.option_list.is_checked: ${JSON.stringify(opt.is_checked)} → ${fixed}`);
1275
+ opt.is_checked = fixed;
1276
+ }
1277
+ }
1278
+ }
1279
+ }
1280
+ }
1281
+ // ── source.desc_color ────────────────────────────────────────────────
1282
+ const source = card.source;
1283
+ if (source && typeof source === "object" && "desc_color" in source) {
1284
+ const fixed = coerceToInt(source.desc_color);
1285
+ if (fixed !== undefined && source.desc_color !== fixed) {
1286
+ fixes.push(`source.desc_color: ${JSON.stringify(source.desc_color)} → ${fixed}`);
1287
+ source.desc_color = fixed;
1288
+ }
1289
+ }
1290
+ // ── card_action.type ─────────────────────────────────────────────────
1291
+ const cardAction = card.card_action;
1292
+ if (cardAction && typeof cardAction === "object" && "type" in cardAction) {
1293
+ const fixed = coerceToInt(cardAction.type);
1294
+ if (fixed !== undefined && cardAction.type !== fixed) {
1295
+ fixes.push(`card_action.type: ${JSON.stringify(cardAction.type)} → ${fixed}`);
1296
+ cardAction.type = fixed;
1297
+ }
1298
+ }
1299
+ // ── quote_area.type ──────────────────────────────────────────────────
1300
+ const quoteArea = card.quote_area;
1301
+ if (quoteArea && typeof quoteArea === "object" && "type" in quoteArea) {
1302
+ const fixed = coerceToInt(quoteArea.type);
1303
+ if (fixed !== undefined && quoteArea.type !== fixed) {
1304
+ fixes.push(`quote_area.type: ${JSON.stringify(quoteArea.type)} → ${fixed}`);
1305
+ quoteArea.type = fixed;
1306
+ }
1307
+ }
1308
+ // ── image_text_area.type ─────────────────────────────────────────────
1309
+ const imageTextArea = card.image_text_area;
1310
+ if (imageTextArea && typeof imageTextArea === "object" && "type" in imageTextArea) {
1311
+ const fixed = coerceToInt(imageTextArea.type);
1312
+ if (fixed !== undefined && imageTextArea.type !== fixed) {
1313
+ fixes.push(`image_text_area.type: ${JSON.stringify(imageTextArea.type)} → ${fixed}`);
1314
+ imageTextArea.type = fixed;
1315
+ }
1316
+ }
1317
+ // ── horizontal_content_list[].type ───────────────────────────────────
1318
+ if (Array.isArray(card.horizontal_content_list)) {
1319
+ for (const item of card.horizontal_content_list) {
1320
+ if (item && typeof item === "object" && "type" in item) {
1321
+ const fixed = coerceToInt(item.type);
1322
+ if (fixed !== undefined && item.type !== fixed) {
1323
+ fixes.push(`horizontal_content_list.type: ${JSON.stringify(item.type)} → ${fixed}`);
1324
+ item.type = fixed;
1325
+ }
1326
+ }
1327
+ }
1328
+ }
1329
+ // ── jump_list[].type ─────────────────────────────────────────────────
1330
+ if (Array.isArray(card.jump_list)) {
1331
+ for (const item of card.jump_list) {
1332
+ if (item && typeof item === "object" && "type" in item) {
1333
+ const fixed = coerceToInt(item.type);
1334
+ if (fixed !== undefined && item.type !== fixed) {
1335
+ fixes.push(`jump_list.type: ${JSON.stringify(item.type)} → ${fixed}`);
1336
+ item.type = fixed;
1337
+ }
1338
+ }
1339
+ }
1340
+ }
1341
+ // ── button_list[].style ──────────────────────────────────────────────
1342
+ if (Array.isArray(card.button_list)) {
1343
+ for (const btn of card.button_list) {
1344
+ if (btn && typeof btn === "object" && "style" in btn) {
1345
+ const fixed = coerceToInt(btn.style);
1346
+ if (fixed !== undefined && btn.style !== fixed) {
1347
+ fixes.push(`button_list.style: ${JSON.stringify(btn.style)} → ${fixed}`);
1348
+ btn.style = fixed;
1349
+ }
1350
+ }
1351
+ }
1352
+ }
1353
+ // ── button_selection.disable ─────────────────────────────────────────
1354
+ const buttonSelection = card.button_selection;
1355
+ if (buttonSelection && typeof buttonSelection === "object" && "disable" in buttonSelection) {
1356
+ const fixed = coerceToBool(buttonSelection.disable);
1357
+ if (fixed !== undefined && buttonSelection.disable !== fixed) {
1358
+ fixes.push(`button_selection.disable: ${JSON.stringify(buttonSelection.disable)} → ${fixed}`);
1359
+ buttonSelection.disable = fixed;
1360
+ }
1361
+ }
1362
+ // ── select_list[].disable ────────────────────────────────────────────
1363
+ if (Array.isArray(card.select_list)) {
1364
+ for (const sel of card.select_list) {
1365
+ if (sel && typeof sel === "object" && "disable" in sel) {
1366
+ const fixed = coerceToBool(sel.disable);
1367
+ if (fixed !== undefined && sel.disable !== fixed) {
1368
+ fixes.push(`select_list.disable: ${JSON.stringify(sel.disable)} → ${fixed}`);
1369
+ sel.disable = fixed;
1370
+ }
1371
+ }
1372
+ }
1373
+ }
1374
+ if (fixes.length > 0) {
1375
+ log?.(`[template-card-parser] normalizeTemplateCardFields: ${fixes.length} fix(es) applied: ${fixes.join("; ")}`);
1376
+ }
1377
+ return card;
1378
+ }
1379
+ /**
1380
+ * 校验并补全模板卡片的必填字段。
1381
+ *
1382
+ * 在 normalizeTemplateCardFields(类型修正)之后调用,确保卡片结构满足企业微信 API 的必填要求。
1383
+ *
1384
+ * 补全策略:
1385
+ * - task_id:所有卡片统一自动补全(交互型 API 必填,通知型插件也需要用于缓存回写)
1386
+ * - main_title:除 text_notice 外的 4 种卡片 API 必填,自动补 { title: "通知" }
1387
+ * text_notice 要求 main_title.title 与 sub_title_text 至少填一个,缺两个时补 sub_title_text
1388
+ * - card_action:text_notice / news_notice API 必填,自动补 { type: 1, url: "https://work.weixin.qq.com" }
1389
+ * - checkbox:vote_interaction API 必填,无法凭空补全,仅记告警
1390
+ * - submit_button:vote_interaction / multiple_interaction API 必填,自动补 { text: "提交", key: "submit_default" }
1391
+ * - button_list:button_interaction API 必填,无法凭空补全,仅记告警
1392
+ * - select_list:multiple_interaction API 必填,无法凭空补全,仅记告警
1393
+ */
1394
+ function validateAndFixRequiredFields(card, log) {
1395
+ const cardType = card.card_type;
1396
+ const fixes = [];
1397
+ const warnings = [];
1398
+ // ── task_id(所有卡片:始终确保唯一性) ─────────────────────────────
1399
+ // LLM 可能编造时间戳导致重复,因此无论是否提供了 task_id,
1400
+ // 都提取语义前缀 + 代码追加真实时间戳和随机后缀来保证唯一。
1401
+ const rawTid = (typeof card.task_id === "string" && card.task_id.trim()) ? card.task_id.trim() : "";
1402
+ const rand = Math.random().toString(36).slice(2, 6);
1403
+ const ts = Date.now();
1404
+ let finalTid;
1405
+ if (rawTid) {
1406
+ // 提取 LLM 的语义前缀:去掉尾部的数字串(LLM 编造的假时间戳)
1407
+ const prefix = rawTid.replace(/_\d{8,}$/, "").replace(/[^a-zA-Z0-9_\-@]/g, "_").slice(0, 80);
1408
+ finalTid = prefix ? `${prefix}_${ts}_${rand}` : `task_${cardType}_${ts}_${rand}`;
1409
+ }
1410
+ else {
1411
+ finalTid = `task_${cardType}_${ts}_${rand}`;
1412
+ }
1413
+ if (finalTid !== rawTid) {
1414
+ fixes.push(`task_id: "${rawTid || "(missing)"}" → "${finalTid}"`);
1415
+ }
1416
+ card.task_id = finalTid;
1417
+ // ── main_title ────────────────────────────────────────────────────────
1418
+ const mainTitle = card.main_title;
1419
+ const hasMainTitle = mainTitle && typeof mainTitle === "object" &&
1420
+ (typeof mainTitle.title === "string" && mainTitle.title.trim());
1421
+ const hasSubTitleText = typeof card.sub_title_text === "string" && card.sub_title_text.trim();
1422
+ switch (cardType) {
1423
+ case "text_notice":
1424
+ // text_notice: main_title.title 和 sub_title_text 至少一个
1425
+ if (!hasMainTitle && !hasSubTitleText) {
1426
+ card.sub_title_text = card.sub_title_text || "通知";
1427
+ fixes.push(`sub_title_text: (missing, no main_title either) → fallback "通知"`);
1428
+ }
1429
+ break;
1430
+ case "news_notice":
1431
+ case "button_interaction":
1432
+ case "vote_interaction":
1433
+ case "multiple_interaction":
1434
+ // 这四种 main_title 为必填
1435
+ if (!mainTitle || typeof mainTitle !== "object") {
1436
+ card.main_title = { title: "通知" };
1437
+ fixes.push(`main_title: (missing) → { title: "通知" }`);
1438
+ }
1439
+ else if (!hasMainTitle) {
1440
+ mainTitle.title = "通知";
1441
+ fixes.push(`main_title.title: (empty) → "通知"`);
1442
+ }
1443
+ break;
1444
+ }
1445
+ // ── card_action(text_notice / news_notice 必填) ──────────────────
1446
+ if (cardType === "text_notice" || cardType === "news_notice") {
1447
+ if (!card.card_action || typeof card.card_action !== "object") {
1448
+ card.card_action = { type: 1, url: "https://work.weixin.qq.com" };
1449
+ fixes.push(`card_action: (missing) → { type: 1, url: "https://work.weixin.qq.com" }`);
1450
+ }
1451
+ }
1452
+ // ── submit_button(vote_interaction / multiple_interaction 必填) ──
1453
+ if (cardType === "vote_interaction" || cardType === "multiple_interaction") {
1454
+ if (!card.submit_button || typeof card.submit_button !== "object") {
1455
+ card.submit_button = { text: "提交", key: `submit_${cardType}_${Date.now()}` };
1456
+ fixes.push(`submit_button: (missing) → auto-generated`);
1457
+ }
1458
+ }
1459
+ // ── 核心业务字段(无法凭空补全,仅告警) ────────────────────────────
1460
+ if (cardType === "button_interaction") {
1461
+ if (!Array.isArray(card.button_list) || card.button_list.length === 0) {
1462
+ warnings.push(`button_list is missing or empty (required for button_interaction)`);
1463
+ }
1464
+ }
1465
+ if (cardType === "vote_interaction") {
1466
+ if (!card.checkbox || typeof card.checkbox !== "object") {
1467
+ warnings.push(`checkbox is missing (required for vote_interaction)`);
1468
+ }
1469
+ }
1470
+ if (cardType === "multiple_interaction") {
1471
+ if (!Array.isArray(card.select_list) || card.select_list.length === 0) {
1472
+ warnings.push(`select_list is missing or empty (required for multiple_interaction)`);
1473
+ }
1474
+ }
1475
+ if (fixes.length > 0) {
1476
+ log?.(`[template-card-parser] validateAndFixRequiredFields: ${fixes.length} fix(es): ${fixes.join("; ")}`);
1477
+ }
1478
+ if (warnings.length > 0) {
1479
+ log?.(`[template-card-parser] validateAndFixRequiredFields: ${warnings.length} warning(s): ${warnings.join("; ")}`);
1480
+ }
1481
+ return card;
1482
+ }
1483
+ // ============================================================================
1484
+ // 简化格式 → 企微 API 格式转换(vote_interaction / multiple_interaction)
1485
+ // ============================================================================
1486
+ /**
1487
+ * 生成唯一的 question_key / submit_button.key。
1488
+ */
1489
+ function generateKey(prefix) {
1490
+ const rand = Math.random().toString(36).slice(2, 6);
1491
+ return `${prefix}_${Date.now()}_${rand}`;
1492
+ }
1493
+ /**
1494
+ * 将 vote_interaction 的简化格式转换为企微 API 格式。
1495
+ *
1496
+ * 简化格式字段:
1497
+ * title → main_title.title
1498
+ * description → main_title.desc
1499
+ * options → checkbox.option_list(每个 {id, text} 直接透传)
1500
+ * mode → checkbox.mode(0=单选 1=多选)
1501
+ * submit_text → submit_button.text
1502
+ *
1503
+ * 代码自动生成:checkbox.question_key, submit_button.key
1504
+ *
1505
+ * 如果 LLM 已输出了合法的 API 原始格式(有 checkbox.option_list),则跳过转换直接透传。
1506
+ */
1507
+ function transformVoteInteraction(card, log) {
1508
+ // 防御性:如果已经是合法 API 格式,跳过
1509
+ const existingCheckbox = card.checkbox;
1510
+ if (existingCheckbox && typeof existingCheckbox === "object" && Array.isArray(existingCheckbox.option_list)) {
1511
+ log?.(`[template-card-parser] transformVoteInteraction: already has checkbox.option_list, skipping transform`);
1512
+ return card;
1513
+ }
1514
+ // 提取 options(简化格式的核心字段)
1515
+ const options = card.options;
1516
+ if (!Array.isArray(options) || options.length === 0) {
1517
+ log?.(`[template-card-parser] transformVoteInteraction: no "options" array found, skipping transform`);
1518
+ return card;
1519
+ }
1520
+ log?.(`[template-card-parser] transformVoteInteraction: transforming simplified format → API format`);
1521
+ log?.(`[template-card-parser] transformVoteInteraction: input=${JSON.stringify(card)}`);
1522
+ // ── 构建 main_title ──
1523
+ const title = card.title;
1524
+ const description = card.description;
1525
+ if (title || description) {
1526
+ card.main_title = {
1527
+ ...(title ? { title } : {}),
1528
+ ...(description ? { desc: description } : {}),
1529
+ };
1530
+ delete card.title;
1531
+ delete card.description;
1532
+ }
1533
+ // ── 构建 checkbox(最多 20 个选项) ──
1534
+ const mode = coerceCheckboxMode(card.mode) ?? 0;
1535
+ const questionKey = generateKey("vote");
1536
+ const clampedOptions = options.slice(0, 20);
1537
+ if (options.length > 20) {
1538
+ log?.(`[template-card-parser] transformVoteInteraction: options count ${options.length} exceeds max 20, clamped to 20`);
1539
+ }
1540
+ card.checkbox = {
1541
+ question_key: questionKey,
1542
+ mode,
1543
+ option_list: clampedOptions.map((opt) => ({
1544
+ id: String(opt.id ?? opt.value ?? `opt_${Math.random().toString(36).slice(2, 6)}`),
1545
+ text: String(opt.text ?? opt.label ?? opt.name ?? ""),
1546
+ })),
1547
+ };
1548
+ delete card.options;
1549
+ delete card.mode;
1550
+ // ── 构建 submit_button ──
1551
+ const submitText = card.submit_text || "提交";
1552
+ card.submit_button = {
1553
+ text: submitText,
1554
+ key: generateKey("submit_vote"),
1555
+ };
1556
+ delete card.submit_text;
1557
+ // ── 清理 LLM 可能杜撰的无效字段 ──
1558
+ delete card.vote_question;
1559
+ delete card.vote_option;
1560
+ delete card.vote_options;
1561
+ log?.(`[template-card-parser] transformVoteInteraction: output=${JSON.stringify(card)}`);
1562
+ return card;
1563
+ }
1564
+ /**
1565
+ * 将 multiple_interaction 的简化格式转换为企微 API 格式。
1566
+ *
1567
+ * 简化格式字段:
1568
+ * title → main_title.title
1569
+ * description → main_title.desc
1570
+ * selectors → select_list(每个 {title, options: [{id, text}]} → {question_key, title, option_list})
1571
+ * submit_text → submit_button.text
1572
+ *
1573
+ * 代码自动生成:select_list[].question_key, submit_button.key
1574
+ *
1575
+ * 如果 LLM 已输出了合法的 API 原始格式(有 select_list[0].option_list),则跳过转换直接透传。
1576
+ */
1577
+ function transformMultipleInteraction(card, log) {
1578
+ // 防御性:如果已经是合法 API 格式,跳过
1579
+ const existingSelectList = card.select_list;
1580
+ if (Array.isArray(existingSelectList) &&
1581
+ existingSelectList.length > 0 &&
1582
+ Array.isArray(existingSelectList[0]?.option_list)) {
1583
+ log?.(`[template-card-parser] transformMultipleInteraction: already has select_list[].option_list, skipping transform`);
1584
+ return card;
1585
+ }
1586
+ // 提取 selectors(简化格式的核心字段)
1587
+ const selectors = card.selectors;
1588
+ if (!Array.isArray(selectors) || selectors.length === 0) {
1589
+ log?.(`[template-card-parser] transformMultipleInteraction: no "selectors" array found, skipping transform`);
1590
+ return card;
1591
+ }
1592
+ log?.(`[template-card-parser] transformMultipleInteraction: transforming simplified format → API format`);
1593
+ log?.(`[template-card-parser] transformMultipleInteraction: input=${JSON.stringify(card)}`);
1594
+ // ── 构建 main_title ──
1595
+ const title = card.title;
1596
+ const description = card.description;
1597
+ if (title || description) {
1598
+ card.main_title = {
1599
+ ...(title ? { title } : {}),
1600
+ ...(description ? { desc: description } : {}),
1601
+ };
1602
+ delete card.title;
1603
+ delete card.description;
1604
+ }
1605
+ // ── 构建 select_list(最多 3 个选择器,每个最多 10 个选项) ──
1606
+ const clampedSelectors = selectors.slice(0, 3);
1607
+ if (selectors.length > 3) {
1608
+ log?.(`[template-card-parser] transformMultipleInteraction: selectors count ${selectors.length} exceeds max 3, clamped to 3`);
1609
+ }
1610
+ card.select_list = clampedSelectors.map((sel, idx) => {
1611
+ const selectorOptions = (sel.options ?? []).slice(0, 10);
1612
+ return {
1613
+ question_key: generateKey(`sel_${idx}`),
1614
+ title: String(sel.title ?? sel.label ?? `选择${idx + 1}`),
1615
+ option_list: selectorOptions.map((opt) => ({
1616
+ id: String(opt.id ?? opt.value ?? `opt_${Math.random().toString(36).slice(2, 6)}`),
1617
+ text: String(opt.text ?? opt.label ?? opt.name ?? ""),
1618
+ })),
1619
+ };
1620
+ });
1621
+ delete card.selectors;
1622
+ // ── 构建 submit_button ──
1623
+ const submitText = card.submit_text || "提交";
1624
+ card.submit_button = {
1625
+ text: submitText,
1626
+ key: generateKey("submit_multi"),
1627
+ };
1628
+ delete card.submit_text;
1629
+ log?.(`[template-card-parser] transformMultipleInteraction: output=${JSON.stringify(card)}`);
1630
+ return card;
1631
+ }
1632
+ /**
1633
+ * 对 vote_interaction / multiple_interaction 执行简化格式转换。
1634
+ * 其他 card_type 直接跳过。
1635
+ */
1636
+ function transformSimplifiedCard(card, log) {
1637
+ const cardType = card.card_type;
1638
+ if (cardType === "vote_interaction") {
1639
+ return transformVoteInteraction(card, log);
1640
+ }
1641
+ if (cardType === "multiple_interaction") {
1642
+ return transformMultipleInteraction(card, log);
1643
+ }
1644
+ return card;
1645
+ }
1646
+ /**
1647
+ * 匹配 markdown 代码块的正则表达式
1648
+ * 支持 ```json ... ``` 和 ``` ... ``` 两种格式
1649
+ */
1650
+ const CODE_BLOCK_RE = /```(?:json)?\s*\n([\s\S]*?)\n```/g;
1651
+ /**
1652
+ * 匹配已闭合的代码块(含 card_type 关键词,用于中间帧遮罩)
1653
+ * 与 CODE_BLOCK_RE 相同,但用于 maskTemplateCardBlocks 中单独实例化
1654
+ */
1655
+ const CLOSED_BLOCK_RE = /```(?:json)?\s*\n([\s\S]*?)\n```/g;
1656
+ /**
1657
+ * 匹配未闭合的代码块尾部(LLM 正在输出中的代码块)
1658
+ * 以 ```json 或 ``` 开头,后面有内容但没有闭合的 ```
1659
+ */
1660
+ const UNCLOSED_BLOCK_RE = /```(?:json)?\s*\n[\s\S]*$/;
1661
+ /**
1662
+ * 从文本中提取模板卡片 JSON 代码块
1663
+ *
1664
+ * 匹配规则:
1665
+ * 1. 匹配所有 ```json ... ``` 或 ``` ... ``` 格式的代码块
1666
+ * 2. 尝试 JSON.parse 解析代码块内容
1667
+ * 3. 检查解析结果中是否包含合法的 card_type 字段
1668
+ * 4. 合法的卡片从原文中移除,不合法的保留
1669
+ *
1670
+ * @param text - LLM 回复的完整文本
1671
+ * @returns 提取结果,包含卡片列表和剩余文本
1672
+ */
1673
+ function extractTemplateCards(text, log) {
1674
+ const cards = [];
1675
+ /** 需要从原文中移除的代码块(记录完整匹配内容) */
1676
+ const blocksToRemove = [];
1677
+ log?.(`[template-card-parser] extractTemplateCards called, textLength=${text.length}`);
1678
+ let match;
1679
+ // 重置正则的 lastIndex,确保从头匹配
1680
+ CODE_BLOCK_RE.lastIndex = 0;
1681
+ let blockIndex = 0;
1682
+ while ((match = CODE_BLOCK_RE.exec(text)) !== null) {
1683
+ const fullMatch = match[0];
1684
+ const jsonContent = match[1].trim();
1685
+ blockIndex++;
1686
+ log?.(`[template-card-parser] Found code block #${blockIndex}, length=${fullMatch.length}, preview=${jsonContent.slice(0, 1000)}...`);
1687
+ // 尝试解析 JSON
1688
+ let parsed;
1689
+ try {
1690
+ parsed = JSON.parse(jsonContent);
1691
+ }
1692
+ catch (e) {
1693
+ // JSON 解析失败,保留在原文中
1694
+ log?.(`[template-card-parser] Code block #${blockIndex} JSON parse failed: ${String(e)}`);
1695
+ continue;
1696
+ }
1697
+ // 检查是否包含合法的 card_type
1698
+ const cardType = parsed.card_type;
1699
+ if (typeof cardType !== "string" || !VALID_CARD_TYPES.includes(cardType)) {
1700
+ // card_type 不合法,保留在原文中
1701
+ log?.(`[template-card-parser] Code block #${blockIndex} has invalid card_type="${String(cardType)}", skipping`);
1702
+ continue;
1703
+ }
1704
+ log?.(`[template-card-parser] Code block #${blockIndex} is valid template card, card_type="${cardType}"`);
1705
+ // vote_interaction / multiple_interaction:简化格式 → API 格式转换
1706
+ transformSimplifiedCard(parsed, log);
1707
+ // 修正 LLM 可能输出的错误字段类型(如 checkbox.mode: "multi" → 1)
1708
+ normalizeTemplateCardFields(parsed, log);
1709
+ // 校验并补全必填字段(如缺失的 task_id、main_title、card_action)
1710
+ validateAndFixRequiredFields(parsed, log);
1711
+ // 合法的模板卡片,收集并标记移除
1712
+ cards.push({
1713
+ cardJson: parsed,
1714
+ cardType,
1715
+ });
1716
+ blocksToRemove.push(fullMatch);
1717
+ }
1718
+ // 从原文中移除已提取的代码块,生成剩余文本
1719
+ let remainingText = text;
1720
+ for (const block of blocksToRemove) {
1721
+ remainingText = remainingText.replace(block, "");
1722
+ }
1723
+ // 清理多余空行(连续 3 个以上换行合并为 2 个)
1724
+ remainingText = remainingText.replace(/\n{3,}/g, "\n\n").trim();
1725
+ log?.(`[template-card-parser] Extraction done: ${cards.length} card(s) found, remainingTextLength=${remainingText.length}`);
1726
+ return { cards, remainingText };
1727
+ }
1728
+ /**
1729
+ * 遮罩文本中的模板卡片代码块(用于流式中间帧展示)
1730
+ *
1731
+ * 在 LLM 流式输出过程中,累积文本可能包含:
1732
+ * 1. 已闭合的模板卡片 JSON 代码块 → 替换为友好提示文本
1733
+ * 2. 正在构建中的未闭合代码块 → 截断隐藏,避免 JSON 源码暴露
1734
+ *
1735
+ * 此函数仅做文本替换,不做 JSON 解析验证(中间帧性能优先)。
1736
+ * 只要代码块内容中出现 "card_type" 关键词就认为是模板卡片并遮罩。
1737
+ *
1738
+ * @param text - 当前累积文本
1739
+ * @returns 遮罩后的展示文本
1740
+ */
1741
+ function maskTemplateCardBlocks(text, log) {
1742
+ let masked = text;
1743
+ let closedMaskCount = 0;
1744
+ let unclosedMasked = false;
1745
+ // 步骤一:处理已闭合的代码块
1746
+ CLOSED_BLOCK_RE.lastIndex = 0;
1747
+ masked = masked.replace(CLOSED_BLOCK_RE, (fullMatch, content) => {
1748
+ // 检查代码块内容是否包含 card_type 关键词
1749
+ if (/["']card_type["']/.test(content)) {
1750
+ closedMaskCount++;
1751
+ return "\n\n📋 *正在生成卡片消息...*\n\n";
1752
+ }
1753
+ // 非模板卡片代码块,保留原样
1754
+ return fullMatch;
1755
+ });
1756
+ // 步骤二:处理未闭合的代码块尾部(LLM 仍在输出中)
1757
+ // 检查是否有以 ``` 开头但没有闭合的代码块
1758
+ const unclosedMatch = UNCLOSED_BLOCK_RE.exec(masked);
1759
+ if (unclosedMatch) {
1760
+ const unclosedContent = unclosedMatch[0];
1761
+ // 如果未闭合部分包含 card_type 关键词,说明正在构建模板卡片 → 截断
1762
+ if (/["']card_type["']/.test(unclosedContent)) {
1763
+ unclosedMasked = true;
1764
+ masked = masked.slice(0, unclosedMatch.index) + "\n\n📋 *正在生成卡片消息...*";
1765
+ }
1766
+ }
1767
+ // 有遮罩行为时才打日志,避免每帧都刷屏
1768
+ if (closedMaskCount > 0 || unclosedMasked) {
1769
+ log?.(`[template-card-parser] maskTemplateCardBlocks: closedMasked=${closedMaskCount}, unclosedMasked=${unclosedMasked}, textLength=${text.length}, maskedLength=${masked.length}`);
1770
+ }
1771
+ return masked;
1772
+ }
1773
+
1060
1774
  /**
1061
1775
  * 企业微信群组访问控制模块
1062
1776
  *
@@ -1524,6 +2238,144 @@ const PLUGIN_VERSION = getVersion();
1524
2238
  * - state-manager.ts : 全局状态管理(带 TTL 清理)
1525
2239
  * - timeout.ts : 超时工具
1526
2240
  */
2241
+ /**
2242
+ * 去除文本中的 `<think>...</think>` 标签(支持跨行),返回剩余可见文本。
2243
+ * 用于判断大模型回复中是否包含实际用户可见内容(而非仅有 thinking 推理过程)。
2244
+ */
2245
+ function stripThinkTags(text) {
2246
+ return text;
2247
+ // return text.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
2248
+ }
2249
+ const sentTemplateCardByTaskId = new Map();
2250
+ const TEMPLATE_CARD_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
2251
+ const TEMPLATE_CARD_CACHE_MAX_SIZE = 300;
2252
+ function getTemplateCardCacheKey(accountId, taskId) {
2253
+ return `${accountId}:${taskId}`;
2254
+ }
2255
+ function pruneTemplateCardCache() {
2256
+ const now = Date.now();
2257
+ for (const [key, entry] of sentTemplateCardByTaskId) {
2258
+ if (now - entry.createdAt >= TEMPLATE_CARD_CACHE_TTL_MS) {
2259
+ sentTemplateCardByTaskId.delete(key);
2260
+ }
2261
+ }
2262
+ if (sentTemplateCardByTaskId.size <= TEMPLATE_CARD_CACHE_MAX_SIZE) {
2263
+ return;
2264
+ }
2265
+ const sortedEntries = [...sentTemplateCardByTaskId.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt);
2266
+ const removeCount = sentTemplateCardByTaskId.size - TEMPLATE_CARD_CACHE_MAX_SIZE;
2267
+ for (const [key] of sortedEntries.slice(0, removeCount)) {
2268
+ sentTemplateCardByTaskId.delete(key);
2269
+ }
2270
+ }
2271
+ function cloneTemplateCard(card) {
2272
+ return JSON.parse(JSON.stringify(card));
2273
+ }
2274
+ function saveTemplateCardToCache(params) {
2275
+ const { accountId, templateCard, runtime } = params;
2276
+ const taskId = templateCard.task_id;
2277
+ if (!taskId) {
2278
+ runtime.log?.("[wecom][template-card] Skip cache: template card has no task_id");
2279
+ return;
2280
+ }
2281
+ sentTemplateCardByTaskId.set(getTemplateCardCacheKey(accountId, taskId), {
2282
+ templateCard: cloneTemplateCard(templateCard),
2283
+ createdAt: Date.now(),
2284
+ });
2285
+ pruneTemplateCardCache();
2286
+ }
2287
+ function getTemplateCardFromCache(accountId, taskId) {
2288
+ pruneTemplateCardCache();
2289
+ const cached = sentTemplateCardByTaskId.get(getTemplateCardCacheKey(accountId, taskId));
2290
+ if (!cached) {
2291
+ return undefined;
2292
+ }
2293
+ return cloneTemplateCard(cached.templateCard);
2294
+ }
2295
+ function buildSelectedOptionMap(templateCardEvent) {
2296
+ const selectedMap = new Map();
2297
+ const selectedItems = templateCardEvent?.selected_items?.selected_item ?? [];
2298
+ for (const item of selectedItems) {
2299
+ const questionKey = item.question_key?.trim();
2300
+ if (!questionKey) {
2301
+ continue;
2302
+ }
2303
+ const optionIds = item.option_ids?.option_id?.filter(Boolean) ?? [];
2304
+ selectedMap.set(questionKey, optionIds);
2305
+ }
2306
+ return selectedMap;
2307
+ }
2308
+ function applySelectedStateToTemplateCard(params) {
2309
+ const { templateCard, selectedMap, templateCardEvent } = params;
2310
+ const nextCard = cloneTemplateCard(templateCard);
2311
+ if (templateCardEvent?.task_id) {
2312
+ nextCard.task_id = templateCardEvent.task_id;
2313
+ }
2314
+ if (templateCardEvent?.card_type) {
2315
+ nextCard.card_type = templateCardEvent.card_type;
2316
+ }
2317
+ // 交互完成后将提交按钮文案更新为已提交,提升用户感知
2318
+ if (nextCard.submit_button?.text) {
2319
+ nextCard.submit_button.text = "已提交";
2320
+ }
2321
+ if (nextCard.checkbox?.question_key) {
2322
+ const selectedIds = selectedMap.get(nextCard.checkbox.question_key) ?? [];
2323
+ nextCard.checkbox.disable = true;
2324
+ if (Array.isArray(nextCard.checkbox.option_list)) {
2325
+ nextCard.checkbox.option_list = nextCard.checkbox.option_list.map((option) => ({
2326
+ ...option,
2327
+ is_checked: selectedIds.includes(option.id),
2328
+ }));
2329
+ }
2330
+ }
2331
+ if (Array.isArray(nextCard.select_list)) {
2332
+ nextCard.select_list = nextCard.select_list.map((selection) => {
2333
+ const selectedIds = selectedMap.get(selection.question_key) ?? [];
2334
+ return {
2335
+ ...selection,
2336
+ disable: true,
2337
+ selected_id: selectedIds[0] ?? selection.selected_id,
2338
+ };
2339
+ });
2340
+ }
2341
+ if (nextCard.button_selection?.question_key) {
2342
+ const selectedIds = selectedMap.get(nextCard.button_selection.question_key) ?? [];
2343
+ nextCard.button_selection.disable = true;
2344
+ if (selectedIds[0]) {
2345
+ nextCard.button_selection.selected_id = selectedIds[0];
2346
+ }
2347
+ }
2348
+ return nextCard;
2349
+ }
2350
+ async function updateTemplateCardOnEvent(params) {
2351
+ const { frame, accountId, runtime, wsClient } = params;
2352
+ const body = frame.body;
2353
+ const templateCardEvent = body.event?.template_card_event;
2354
+ const taskId = templateCardEvent?.task_id;
2355
+ if (!taskId) {
2356
+ runtime.log?.(`[${accountId}] [template-card-update] Skip update: missing task_id in callback`);
2357
+ return;
2358
+ }
2359
+ const cachedCard = getTemplateCardFromCache(accountId, taskId);
2360
+ if (!cachedCard) {
2361
+ runtime.log?.(`[${accountId}] [template-card-update] Skip update: task_id=${taskId} not found in cache`);
2362
+ return;
2363
+ }
2364
+ const selectedMap = buildSelectedOptionMap(templateCardEvent);
2365
+ const updatedCard = applySelectedStateToTemplateCard({
2366
+ templateCard: cachedCard,
2367
+ selectedMap,
2368
+ templateCardEvent,
2369
+ });
2370
+ await wsClient.updateTemplateCard(frame, updatedCard, [body.from.userid]);
2371
+ runtime.log?.(`[${accountId}] [template-card-update] Updated card by task_id=${taskId}`);
2372
+ // 将更新后的卡片写回缓存,后续多次点击时状态保持一致
2373
+ saveTemplateCardToCache({
2374
+ accountId,
2375
+ templateCard: updatedCard,
2376
+ runtime,
2377
+ });
2378
+ }
1527
2379
  // ============================================================================
1528
2380
  // 媒体本地路径白名单扩展
1529
2381
  // ============================================================================
@@ -1720,6 +2572,7 @@ async function sendMediaBatch(ctx, mediaUrls) {
1720
2572
  * 替换掉 thinking 动画,否则 thinking 会一直残留。
1721
2573
  *
1722
2574
  * 关闭策略(按优先级):
2575
+ * 0. [新增] 有模板卡片代码块 → 提取卡片并主动发送,用剩余文本关闭流
1723
2576
  * 1. 有可见文本 → 用完整文本关闭
1724
2577
  * 2. 有媒体成功发送(通过 deliver 回调) → 用友好提示"文件已发送"
1725
2578
  * 3. 媒体发送失败 → 直接用错误摘要替换 thinking
@@ -1736,8 +2589,40 @@ async function finishThinkingStream(ctx) {
1736
2589
  const { wsClient, frame, state, runtime } = ctx;
1737
2590
  const body = frame.body;
1738
2591
  const chatId = body.chatid || body.from.userid;
2592
+ const visibleText = stripThinkTags(state.accumulatedText);
2593
+ // ── 模板卡片检测与发送 ──────────────────────────────────────────────
2594
+ // 在确定 finishText 之前,先检查累积文本中是否包含模板卡片 JSON 代码块。
2595
+ // 若检测到合法卡片,通过 sendMessage 主动发送后,用剩余文本关闭流。
2596
+ if (visibleText) {
2597
+ runtime.log?.(`[wecom][template-card] finishThinkingStream: visibleText exists, length=${visibleText.length}, running extractTemplateCards...`);
2598
+ const logFn = (...args) => {
2599
+ runtime.log?.(...args);
2600
+ };
2601
+ const { cards, remainingText } = extractTemplateCards(state.accumulatedText, logFn);
2602
+ runtime.log?.(`[wecom][template-card] finishThinkingStream: extractTemplateCards result — cards=${cards.length}, remainingTextLength=${remainingText.length}`);
2603
+ if (cards.length > 0) {
2604
+ runtime.log?.(`[wecom][template-card] finishThinkingStream: ${cards.length} card(s) detected, card_types=[${cards.map(c => c.cardType).join(", ")}]`);
2605
+ await sendTemplateCards(ctx, cards);
2606
+ // 用剩余文本关闭流(可能为空)
2607
+ const trimmedRemaining = stripThinkTags(remainingText);
2608
+ const finishText = trimmedRemaining
2609
+ ? remainingText
2610
+ : (state.hasTemplateCard ? "📋 卡片消息已发送。" : "");
2611
+ runtime.log?.(`[wecom][template-card] finishThinkingStream: closing stream with finishText="${finishText.slice(0, 100)}...", hasTemplateCard=${state.hasTemplateCard}`);
2612
+ await sendWeComReply({ wsClient, frame, text: finishText, runtime, finish: true, streamId: state.streamId });
2613
+ return;
2614
+ }
2615
+ }
2616
+ else {
2617
+ runtime.log?.(`[wecom][template-card] finishThinkingStream: no visibleText, skipping template card extraction`);
2618
+ }
2619
+ // ── 模板卡片检测结束 ────────────────────────────────────────────────
1739
2620
  let finishText = state.accumulatedText;
1740
- if (state.hasMedia) {
2621
+ if (visibleText) {
2622
+ // 有可见文本:用完整文本关闭流(覆盖 thinking 为真实内容)
2623
+ finishText = state.accumulatedText;
2624
+ }
2625
+ else if (state.hasMedia) {
1741
2626
  if (state.hasMediaFailed && state.mediaErrorSummary) {
1742
2627
  // 媒体成功发送:用友好提示告知用户
1743
2628
  finishText = finishText ? `${finishText}\n\n${state.mediaErrorSummary}` : state.mediaErrorSummary;
@@ -1774,6 +2659,41 @@ async function finishThinkingStream(ctx) {
1774
2659
  }
1775
2660
  }
1776
2661
  }
2662
+ /**
2663
+ * 逐个发送已提取的模板卡片(通过 wsClient.sendMessage 主动推送)
2664
+ *
2665
+ * 发送失败不阻塞流程,仅记录错误日志。
2666
+ */
2667
+ async function sendTemplateCards(ctx, cards) {
2668
+ const { wsClient, frame, state, runtime, account } = ctx;
2669
+ const body = frame.body;
2670
+ const chatId = body.chatid || body.from.userid;
2671
+ for (const card of cards) {
2672
+ try {
2673
+ runtime.log?.(`[wecom][template-card] Sending card_type=${card.cardType} to chatId=${chatId}`);
2674
+ const rawTemplateCard = card.cardJson;
2675
+ if (typeof rawTemplateCard.card_type !== "string") {
2676
+ runtime.error?.("[wecom][template-card] Skip sending invalid card: missing card_type");
2677
+ continue;
2678
+ }
2679
+ const templateCard = rawTemplateCard;
2680
+ await wsClient.sendMessage(chatId, {
2681
+ msgtype: "template_card",
2682
+ template_card: templateCard,
2683
+ });
2684
+ state.hasTemplateCard = true;
2685
+ saveTemplateCardToCache({
2686
+ accountId: account.accountId,
2687
+ templateCard,
2688
+ runtime,
2689
+ });
2690
+ runtime.log?.(`[wecom][template-card] Card sent successfully: card_type=${card.cardType}`);
2691
+ }
2692
+ catch (err) {
2693
+ runtime.error?.(`[wecom][template-card] Failed to send card: card_type=${card.cardType}, error=${JSON.stringify(err)}`);
2694
+ }
2695
+ }
2696
+ }
1777
2697
  /**
1778
2698
  * 路由消息到核心处理流程并处理回复
1779
2699
  */
@@ -1846,9 +2766,15 @@ async function routeAndDispatchMessage(params) {
1846
2766
  }
1847
2767
  }
1848
2768
  // 中间帧:有可见文本时流式更新(流式过期后跳过,等 deliver 完成后主动发送)
2769
+ // 使用 maskTemplateCardBlocks 遮罩正在构建中的模板卡片代码块,
2770
+ // 避免 JSON 源码在流式输出过程中暴露给终端用户
1849
2771
  if (info.kind !== "final" && state.accumulatedText && !state.streamExpired) {
1850
2772
  try {
1851
- await sendWeComReply({ wsClient, frame, text: state.accumulatedText, runtime, finish: false, streamId: state.streamId });
2773
+ const displayText = maskTemplateCardBlocks(state.accumulatedText, (...args) => runtime.log?.(...args));
2774
+ if (displayText !== state.accumulatedText) {
2775
+ runtime.log?.(`[wecom][template-card] Mid-frame masked: original=${state.accumulatedText.length}chars, masked=${displayText.length}chars`);
2776
+ }
2777
+ await sendWeComReply({ wsClient, frame, text: displayText, runtime, finish: false, streamId: state.streamId });
1852
2778
  }
1853
2779
  catch (err) {
1854
2780
  if (err instanceof StreamExpiredError) {
@@ -2031,6 +2957,7 @@ function createSdkLogger(runtime, accountId) {
2031
2957
  async function monitorWeComProvider(options) {
2032
2958
  const { account, config, runtime, abortSignal, setStatus } = options;
2033
2959
  runtime.log?.(`[${account.accountId}] [${PLUGIN_VERSION}] Initializing WSClient with SDK...`);
2960
+ runtime.error?.(`[${account.accountId}] [diag] monitor boot marker: build=20260325-event-debug-1`);
2034
2961
  // 启动消息状态定期清理
2035
2962
  startMessageStateCleanup();
2036
2963
  return new Promise((resolve, reject) => {
@@ -2169,7 +3096,7 @@ async function monitorWeComProvider(options) {
2169
3096
  // runtime.error?.(`[${account.accountId}] Failed to reply enter_check_update: ${String(err)}`);
2170
3097
  }
2171
3098
  });
2172
- // 监听所有消息
3099
+ // 监听普通消息
2173
3100
  wsClient.on("message", async (frame) => {
2174
3101
  try {
2175
3102
  await processWeComMessage({
@@ -2184,6 +3111,44 @@ async function monitorWeComProvider(options) {
2184
3111
  runtime.error?.(`[${account.accountId}] Failed to process message: ${String(err)}`);
2185
3112
  }
2186
3113
  });
3114
+ // 监听所有事件回调(aibot_event_callback)。
3115
+ // 这里使用通用 event 监听,再按 eventtype 分发,兼容不同 SDK 版本在细分事件名上的差异。
3116
+ wsClient.on("event", async (frame) => {
3117
+ try {
3118
+ const eventBody = frame.body;
3119
+ const eventType = eventBody.event?.eventtype;
3120
+ runtime.log?.(`[${account.accountId}] Received event callback: eventtype=${eventType ?? ""}, msgid=${eventBody.msgid ?? ""}`);
3121
+ runtime.error?.(`[${account.accountId}] [diag] event-listener fired: eventtype=${eventType ?? ""}, msgid=${eventBody.msgid ?? ""}`);
3122
+ if (eventType !== "template_card_event") {
3123
+ return;
3124
+ }
3125
+ const templateCardEvent = eventBody.event?.template_card_event;
3126
+ runtime.log?.(`[${account.accountId}] Received template_card_event: event_key=${templateCardEvent?.event_key ?? ""}, task_id=${templateCardEvent?.task_id ?? ""}`);
3127
+ try {
3128
+ await updateTemplateCardOnEvent({
3129
+ frame,
3130
+ accountId: account.accountId,
3131
+ runtime,
3132
+ wsClient,
3133
+ });
3134
+ }
3135
+ catch (updateErr) {
3136
+ runtime.error?.(`[${account.accountId}] [template-card-update] Failed to update template card: ${String(updateErr)}`);
3137
+ }
3138
+ await processWeComMessage({
3139
+ frame,
3140
+ account,
3141
+ config,
3142
+ runtime,
3143
+ wsClient,
3144
+ });
3145
+ }
3146
+ catch (err) {
3147
+ runtime.error?.(`[${account.accountId}] Failed to process template_card_event: ${String(err)}`);
3148
+ }
3149
+ });
3150
+ runtime.log?.(`[${account.accountId}] Event listeners attached: message + event(template_card_event)`);
3151
+ runtime.error?.(`[${account.accountId}] [diag] listeners-ready marker`);
2187
3152
  // 启动前预热 reqId 缓存,确保完成后再建立连接,避免 getSync 在预热完成前返回 undefined
2188
3153
  warmupReqIdStore(account.accountId, (...args) => runtime.log?.(...args))
2189
3154
  .then((count) => {
@@ -3252,59 +4217,16 @@ function cleanWithDefs(schema, defs, refStack) {
3252
4217
  }
3253
4218
 
3254
4219
  /**
3255
- * wecom_mcp — 模拟 MCP 调用的 Agent Tool
3256
- *
3257
- * 通过 MCP Streamable HTTP 传输协议调用企业微信 MCP Server,
3258
- * 提供 list(列出所有工具)和 call(调用工具)两个操作。
4220
+ * 业务错误码检查拦截器
3259
4221
  *
3260
- * 在 skills 中的使用方式:
3261
- * wecom_mcp list <category>
3262
- * wecom_mcp call <category> <method> '<jsonArgs>'
4222
+ * 检查 tools/call 返回结果中是否包含需要清理缓存的业务错误码。
4223
+ * MCP Server 可能在正常的 JSON-RPC 响应中返回业务层错误,
4224
+ * 这些错误被包裹在 result.content[].text 中,需要解析后判断。
3263
4225
  *
3264
- * 示例:
3265
- * wecom_mcp list contact
3266
- * wecom_mcp call contact getContact '{}'
4226
+ * 此拦截器对所有 call 调用生效。
3267
4227
  */
3268
4228
  // ============================================================================
3269
- // 响应构造辅助
3270
- // ============================================================================
3271
- /** 构造统一的文本响应结构 */
3272
- const textResult = (data) => ({
3273
- content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
3274
- });
3275
- /** 构造错误响应 */
3276
- const errorResult = (err) => {
3277
- // 适配企业微信 API 返回的 { errcode, errmsg } 结构
3278
- if (err && typeof err === "object" && "errcode" in err) {
3279
- const { errcode, errmsg } = err;
3280
- return textResult({ error: errmsg ?? `错误码: ${errcode}`, errcode });
3281
- }
3282
- const message = err instanceof Error ? err.message : String(err);
3283
- return textResult({ error: message });
3284
- };
3285
- // ============================================================================
3286
- // list 操作:列出某品类的所有 MCP 工具
3287
- // ============================================================================
3288
- const handleList = async (category) => {
3289
- const result = await sendJsonRpc(category, "tools/list");
3290
- const tools = result?.tools ?? [];
3291
- if (tools.length === 0) {
3292
- return { message: `品类 "${category}" 下暂无可用工具`, tools: [] };
3293
- }
3294
- return {
3295
- category,
3296
- count: tools.length,
3297
- tools: tools.map((t) => ({
3298
- name: t.name,
3299
- description: t.description ?? "",
3300
- // 清洗 inputSchema,内联 $ref/$defs 引用并移除 Gemini 不支持的关键词,
3301
- // 避免 Gemini 模型解析 function response 时报 400 错误
3302
- inputSchema: t.inputSchema ? cleanSchemaForGemini(t.inputSchema) : undefined,
3303
- })),
3304
- };
3305
- };
3306
- // ============================================================================
3307
- // call 操作:调用某品类的某个 MCP 工具
4229
+ // 常量
3308
4230
  // ============================================================================
3309
4231
  /**
3310
4232
  * 需要触发缓存清理的业务错误码集合
@@ -3315,13 +4237,27 @@ const handleList = async (category) => {
3315
4237
  * - 850002: 机器人未被授权使用对应能力,需清理缓存以便下次重新拉取配置
3316
4238
  */
3317
4239
  const BIZ_CACHE_CLEAR_ERROR_CODES = new Set([850002]);
4240
+ // ============================================================================
4241
+ // 拦截器实现
4242
+ // ============================================================================
4243
+ const bizErrorInterceptor = {
4244
+ name: "biz-error",
4245
+ /** 对所有 call 调用生效 */
4246
+ match: () => true,
4247
+ /** 检查返回结果中的业务错误码,必要时清理缓存 */
4248
+ afterCall(ctx, result) {
4249
+ checkBizErrorAndClearCache(result, ctx.category);
4250
+ // 不修改 result,透传给下一个拦截器
4251
+ return result;
4252
+ },
4253
+ };
4254
+ // ============================================================================
4255
+ // 内部实现
4256
+ // ============================================================================
3318
4257
  /**
3319
4258
  * 检查 tools/call 的返回结果中是否包含需要清理缓存的业务错误码
3320
- *
3321
- * MCP Server 可能在正常的 JSON-RPC 响应中返回业务层错误,
3322
- * 这些错误被包裹在 result.content[].text 中,需要解析后判断。
3323
4259
  */
3324
- const checkBizErrorAndClearCache = (result, category) => {
4260
+ function checkBizErrorAndClearCache(result, category) {
3325
4261
  if (!result || typeof result !== "object")
3326
4262
  return;
3327
4263
  const { content } = result;
@@ -3342,14 +4278,39 @@ const checkBizErrorAndClearCache = (result, category) => {
3342
4278
  // text 不是 JSON 格式,跳过
3343
4279
  }
3344
4280
  }
4281
+ }
4282
+
4283
+ /**
4284
+ * get_msg_media 响应拦截器
4285
+ *
4286
+ * 核心逻辑:
4287
+ * 1. beforeCall: 设置延长的超时时间(120s),因为 base64 数据可达 ~27MB
4288
+ * 2. afterCall: 从 MCP result 的 content[].text 中提取 base64_data,
4289
+ * 解码为 Buffer 并通过 saveMediaBuffer 保存到本地媒体目录,
4290
+ * 替换响应中的 base64_data 为 local_path,避免大模型被 base64 数据消耗 token
4291
+ */
4292
+ // ============================================================================
4293
+ // 拦截器实现
4294
+ // ============================================================================
4295
+ const mediaInterceptor = {
4296
+ name: "media",
4297
+ /** 仅对 get_msg_media 方法生效 */
4298
+ match: (ctx) => ctx.method === "get_msg_media",
4299
+ /** 设置延长的超时时间 */
4300
+ beforeCall() {
4301
+ return { timeoutMs: MEDIA_DOWNLOAD_TIMEOUT_MS };
4302
+ },
4303
+ /** 拦截响应:base64 → 本地文件 */
4304
+ async afterCall(ctx, result) {
4305
+ return interceptMediaResponse(result);
4306
+ },
3345
4307
  };
3346
4308
  // ============================================================================
3347
- // get_msg_media 响应拦截:base64 → 本地文件
4309
+ // 内部实现
3348
4310
  // ============================================================================
3349
4311
  /**
3350
4312
  * 拦截 get_msg_media 的 MCP 响应
3351
4313
  *
3352
- * 核心逻辑:
3353
4314
  * 1. 从 MCP result 的 content[].text 中提取业务 JSON
3354
4315
  * 2. 提取 media_item.base64_data,解码为 Buffer
3355
4316
  * 3. 通过 openclaw SDK 的 saveMediaBuffer 保存到本地媒体目录
@@ -3447,31 +4408,384 @@ async function interceptMediaResponse(result) {
3447
4408
  }],
3448
4409
  };
3449
4410
  }
4411
+
4412
+ /**
4413
+ * smartpage_create 请求拦截器
4414
+ *
4415
+ * 核心逻辑:
4416
+ * smartpage_create 的 pages 数组中,每个 page 可能包含 page_filepath 字段
4417
+ * (指向本地 markdown 文件),用于避免在命令行传递大段文本内容。
4418
+ * 本拦截器在 beforeCall 阶段遍历 pages 数组,逐个读取 page_filepath
4419
+ * 指向的本地文件内容,填入 page_content 字段,并移除 page_filepath。
4420
+ *
4421
+ * 入参约定:
4422
+ * wecom_mcp call doc smartpage_create '{
4423
+ * "title": "主页标题",
4424
+ * "pages": [
4425
+ * {"page_title": "页面1", "page_filepath": "/tmp/page1.md", "content_type": "markdown"},
4426
+ * {"page_title": "页面2", "page_filepath": "/tmp/page2.md", "content_type": "markdown"}
4427
+ * ]
4428
+ * }'
4429
+ *
4430
+ * 拦截器行为:
4431
+ * 1. 检测 args.pages 数组
4432
+ * 2. 校验文件大小:单文件不超过 10MB,所有文件总计不超过 20MB
4433
+ * 3. 遍历每个 page,若存在 page_filepath 则读取本地文件内容
4434
+ * 4. 将文件内容填入 page_content 字段,移除 page_filepath
4435
+ * 5. 返回修改后的完整 args
4436
+ *
4437
+ * 传给 MCP Server 的格式:
4438
+ * { "title": "...", "pages": [{"page_title": "...", "page_content": "...", "content_type": "..."}] }
4439
+ */
4440
+ // ============================================================================
4441
+ // 常量
4442
+ // ============================================================================
4443
+ /** 单个 page_filepath 文件大小上限:10MB */
4444
+ const MAX_SINGLE_FILE_SIZE = 10 * 1024 * 1024;
4445
+ /** 所有 page_filepath 文件总大小上限:20MB */
4446
+ const MAX_TOTAL_FILE_SIZE = 20 * 1024 * 1024;
4447
+ // ============================================================================
4448
+ // 内部辅助函数
4449
+ // ============================================================================
4450
+ /**
4451
+ * 校验所有 page_filepath 的文件大小
4452
+ *
4453
+ * 使用 fs.stat 在读取文件内容之前检查大小,避免超大文件被加载到内存。
4454
+ * - 单文件 > 10MB → 报错
4455
+ * - 所有文件累计 > 20MB → 报错
4456
+ */
4457
+ async function validateFileSize(pages) {
4458
+ let totalSize = 0;
4459
+ for (let i = 0; i < pages.length; i++) {
4460
+ const filePath = pages[i].page_filepath;
4461
+ if (typeof filePath !== "string" || !filePath)
4462
+ continue;
4463
+ let stat;
4464
+ try {
4465
+ stat = await fs.stat(filePath);
4466
+ }
4467
+ catch (err) {
4468
+ // stat 失败不在这里处理,留给后续 readFile 阶段抛出更详细的错误
4469
+ continue;
4470
+ }
4471
+ if (stat.size > MAX_SINGLE_FILE_SIZE) {
4472
+ console.error(`[mcp] smartpage_create: pages[${i}] 文件 "${filePath}" ` +
4473
+ `大小 ${(stat.size / 1024 / 1024).toFixed(1)}MB 超过单文件上限 10MB`);
4474
+ throw new Error("内容大小超出限制,无法创建");
4475
+ }
4476
+ totalSize += stat.size;
4477
+ if (totalSize > MAX_TOTAL_FILE_SIZE) {
4478
+ console.error(`[mcp] smartpage_create: 累计文件大小 ${(totalSize / 1024 / 1024).toFixed(1)}MB ` +
4479
+ `超过总上限 20MB(在 pages[${i}] "${filePath}" 处超出)`);
4480
+ throw new Error("内容大小超出限制,无法创建");
4481
+ }
4482
+ }
4483
+ if (totalSize > 0) {
4484
+ console.log(`[mcp] smartpage_create: 文件大小校验通过,总计 ${(totalSize / 1024 / 1024).toFixed(2)}MB`);
4485
+ }
4486
+ }
4487
+ /** 异步解析 pages 中的 page_filepath,返回 BeforeCallOptions */
4488
+ async function resolvePages(ctx, pages) {
4489
+ console.log(`[mcp] smartpage_create: 开始解析 ${pages.length} 个 page 的 page_filepath`);
4490
+ // 阶段 1:文件大小校验(stat 阶段,不读内容)
4491
+ await validateFileSize(pages);
4492
+ // 阶段 2:读取文件内容
4493
+ const resolvedPages = await Promise.all(pages.map(async (page, index) => {
4494
+ const filePath = page.page_filepath;
4495
+ if (typeof filePath !== "string" || !filePath) {
4496
+ // 该 page 没有 page_filepath,保留原样(可能已有 page_content)
4497
+ return page;
4498
+ }
4499
+ let fileContent;
4500
+ try {
4501
+ fileContent = await fs.readFile(filePath, "utf-8");
4502
+ }
4503
+ catch (err) {
4504
+ throw new Error(`smartpage_create: pages[${index}] 无法读取文件 "${filePath}": ${err instanceof Error ? err.message : String(err)}`);
4505
+ }
4506
+ console.log(`[mcp] smartpage_create: pages[${index}] 读取成功 "${filePath}" (${fileContent.length} chars)`);
4507
+ // 构造新的 page 对象:填入 page_content,移除 page_filepath
4508
+ const { page_filepath: _, ...rest } = page;
4509
+ return { ...rest, page_content: fileContent };
4510
+ }));
4511
+ console.log(`[mcp] smartpage_create: 所有 page_filepath 解析完成`);
4512
+ // 返回修改后的完整 args
4513
+ return {
4514
+ args: {
4515
+ ...ctx.args,
4516
+ pages: resolvedPages,
4517
+ },
4518
+ };
4519
+ }
4520
+ // ============================================================================
4521
+ // 拦截器实现
4522
+ // ============================================================================
4523
+ const smartpageCreateInterceptor = {
4524
+ name: "smartpage-create",
4525
+ /** 仅对 doc 品类的 smartpage_create 方法生效 */
4526
+ match: (ctx) => ctx.category === "doc" && ctx.method === "smartpage_create",
4527
+ /** 遍历 pages 数组,逐个读取 page_filepath 填入 page_content */
4528
+ beforeCall(ctx) {
4529
+ const pages = ctx.args.pages;
4530
+ if (!Array.isArray(pages) || pages.length === 0) {
4531
+ // 没有 pages 数组,不做拦截
4532
+ return undefined;
4533
+ }
4534
+ // 检查是否有任何 page 包含 page_filepath
4535
+ const hasFilePath = pages.some((p) => typeof p.page_filepath === "string" && p.page_filepath);
4536
+ if (!hasFilePath) {
4537
+ // 所有 page 都没有 page_filepath(可能直接传了 page_content),不做拦截
4538
+ return undefined;
4539
+ }
4540
+ return resolvePages(ctx, pages);
4541
+ },
4542
+ };
4543
+
4544
+ /**
4545
+ * smartpage_get_export_result 响应拦截器
4546
+ *
4547
+ * 核心逻辑:
4548
+ * MCP Server 返回的 smartpage_get_export_result 响应中,当 task_done=true 时
4549
+ * 会包含 content 字段(markdown 文本内容)。该内容可能很大,直接返回给 LLM
4550
+ * 会消耗大量 token。
4551
+ *
4552
+ * 本拦截器在 afterCall 阶段:
4553
+ * 1. 检测 task_done=true 且存在 content 字段
4554
+ * 2. 将 content 保存到本地文件(使用与 msg-media 一致的媒体目录)
4555
+ * 3. 用 content_path(文件路径)替换 content 字段
4556
+ *
4557
+ * 这样 LLM 只看到轻量的文件路径信息,Skill 可通过文件路径读取完整内容。
4558
+ */
4559
+ // ============================================================================
4560
+ // 拦截器实现
4561
+ // ============================================================================
4562
+ const smartpageExportInterceptor = {
4563
+ name: "smartpage-export",
4564
+ /** 仅对 doc 品类的 smartpage_get_export_result 方法生效 */
4565
+ match: (ctx) => ctx.category === "doc" && ctx.method === "smartpage_get_export_result",
4566
+ /** 拦截响应:将 markdown content 保存为本地文件 */
4567
+ async afterCall(_ctx, result) {
4568
+ return interceptExportResponse(result);
4569
+ },
4570
+ };
4571
+ // ============================================================================
4572
+ // 内部实现
4573
+ // ============================================================================
4574
+ /**
4575
+ * 拦截 smartpage_get_export_result 的 MCP 响应
4576
+ *
4577
+ * 1. 从 MCP result 的 content[].text 中提取业务 JSON
4578
+ * 2. 检测 task_done=true 且存在 content 字段
4579
+ * 3. 将 content(markdown 文本)通过 saveMediaBuffer 保存到本地媒体目录
4580
+ * 4. 构造新响应:移除 content,添加 content_path
4581
+ */
4582
+ async function interceptExportResponse(result) {
4583
+ // 1. 提取 MCP result 中的 content 数组
4584
+ const content = result?.content;
4585
+ if (!Array.isArray(content))
4586
+ return result;
4587
+ const textItem = content.find((c) => c.type === "text" && typeof c.text === "string");
4588
+ if (!textItem)
4589
+ return result;
4590
+ // 2. 解析业务 JSON
4591
+ let bizData;
4592
+ try {
4593
+ bizData = JSON.parse(textItem.text);
4594
+ }
4595
+ catch {
4596
+ // 非 JSON 格式,原样返回
4597
+ return result;
4598
+ }
4599
+ // 3. 校验:errcode !== 0 或 task_done 不为 true 或无 content 时原样返回
4600
+ if (bizData.errcode !== 0)
4601
+ return result;
4602
+ if (bizData.task_done !== true)
4603
+ return result;
4604
+ if (typeof bizData.content !== "string")
4605
+ return result;
4606
+ const markdownContent = bizData.content;
4607
+ console.log(`[mcp] smartpage_get_export_result: 拦截 content (${markdownContent.length} chars),保存到本地文件`);
4608
+ // 4. 将 markdown 内容通过 saveMediaBuffer 保存到本地媒体目录
4609
+ // 使用 text/markdown 类型,与 msg-media 拦截器保持一致的路径管理
4610
+ const buffer = Buffer.from(markdownContent, "utf-8");
4611
+ const core = getWeComRuntime();
4612
+ const saved = await core.channel.media.saveMediaBuffer(buffer, "text/markdown", "inbound", undefined, // maxBytes: markdown 文本通常不大,使用默认限制
4613
+ "smartpage_export.md");
4614
+ console.log(`[mcp] smartpage_get_export_result: 已保存到 ${saved.path}`);
4615
+ // 5. 构造新响应:移除 content,添加 content_path
4616
+ const newBizData = {
4617
+ errcode: bizData.errcode,
4618
+ errmsg: bizData.errmsg ?? "ok",
4619
+ task_done: true,
4620
+ content_path: saved.path,
4621
+ };
4622
+ // 6. 返回修改后的 MCP result 结构
4623
+ return {
4624
+ content: [{
4625
+ type: "text",
4626
+ text: JSON.stringify(newBizData),
4627
+ }],
4628
+ };
4629
+ }
4630
+
4631
+ /**
4632
+ * MCP call 拦截器注册表与调度入口
4633
+ *
4634
+ * 所有 call 拦截器在此注册,按注册顺序执行。
4635
+ * 新增拦截器只需:
4636
+ * 1. 在 interceptors/ 目录下新建文件,实现 CallInterceptor 接口
4637
+ * 2. 在下方 interceptors 数组中注册
4638
+ *
4639
+ * tool.ts 的 handleCall 无需任何改动。
4640
+ */
4641
+ // ============================================================================
4642
+ // 拦截器注册表(按注册顺序执行)
4643
+ // ============================================================================
4644
+ const interceptors = [
4645
+ bizErrorInterceptor, // 业务错误码检查(所有 call 生效)
4646
+ mediaInterceptor, // get_msg_media base64 拦截
4647
+ smartpageCreateInterceptor, // smartpage_create 本地文件读取
4648
+ smartpageExportInterceptor, // smartpage_get_export_result content → 本地文件
4649
+ ];
4650
+ /**
4651
+ * 收集匹配的 beforeCall 配置,合并后返回
4652
+ *
4653
+ * 合并策略:
4654
+ * - timeoutMs: 取所有拦截器返回值中的最大值
4655
+ * - args: 后注册的拦截器覆盖前者(一般同一调用只有一个拦截器会返回 args)
4656
+ */
4657
+ async function resolveBeforeCall(ctx) {
4658
+ let mergedTimeoutMs;
4659
+ let mergedArgs;
4660
+ for (const interceptor of interceptors) {
4661
+ if (!interceptor.match(ctx) || !interceptor.beforeCall)
4662
+ continue;
4663
+ const opts = await interceptor.beforeCall(ctx);
4664
+ if (opts?.timeoutMs !== undefined) {
4665
+ mergedTimeoutMs = mergedTimeoutMs === undefined
4666
+ ? opts.timeoutMs
4667
+ : Math.max(mergedTimeoutMs, opts.timeoutMs);
4668
+ }
4669
+ if (opts?.args !== undefined) {
4670
+ mergedArgs = opts.args;
4671
+ }
4672
+ }
4673
+ return {
4674
+ options: mergedTimeoutMs !== undefined ? { timeoutMs: mergedTimeoutMs } : undefined,
4675
+ args: mergedArgs,
4676
+ };
4677
+ }
4678
+ /**
4679
+ * 依次执行匹配的 afterCall 拦截器,管道式传递 result
4680
+ *
4681
+ * 前一个拦截器的返回值作为下一个拦截器的输入。
4682
+ * 拦截器若不需要修改 result,应原样返回。
4683
+ */
4684
+ async function runAfterCall(ctx, result) {
4685
+ let current = result;
4686
+ for (const interceptor of interceptors) {
4687
+ if (!interceptor.match(ctx) || !interceptor.afterCall)
4688
+ continue;
4689
+ current = await interceptor.afterCall(ctx, current);
4690
+ }
4691
+ return current;
4692
+ }
4693
+
4694
+ /**
4695
+ * wecom_mcp — 模拟 MCP 调用的 Agent Tool
4696
+ *
4697
+ * 通过 MCP Streamable HTTP 传输协议调用企业微信 MCP Server,
4698
+ * 提供 list(列出所有工具)和 call(调用工具)两个操作。
4699
+ *
4700
+ * 在 skills 中的使用方式:
4701
+ * wecom_mcp list <category>
4702
+ * wecom_mcp call <category> <method> '<jsonArgs>'
4703
+ *
4704
+ * 示例:
4705
+ * wecom_mcp list contact
4706
+ * wecom_mcp call contact getContact '{}'
4707
+ */
4708
+ // ============================================================================
4709
+ // 响应构造辅助
4710
+ // ============================================================================
4711
+ /** 构造统一的文本响应结构 */
4712
+ const textResult = (data) => ({
4713
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
4714
+ });
4715
+ /** 构造错误响应 */
4716
+ const errorResult = (err) => {
4717
+ // 适配企业微信 API 返回的 { errcode, errmsg } 结构
4718
+ if (err && typeof err === "object" && "errcode" in err) {
4719
+ const { errcode, errmsg } = err;
4720
+ return textResult({ error: errmsg ?? `错误码: ${errcode}`, errcode });
4721
+ }
4722
+ const message = err instanceof Error ? err.message : String(err);
4723
+ return textResult({ error: message });
4724
+ };
4725
+ // ============================================================================
4726
+ // list 操作:列出某品类的所有 MCP 工具
4727
+ // ============================================================================
4728
+ const handleList = async (category) => {
4729
+ const result = await sendJsonRpc(category, "tools/list");
4730
+ const tools = result?.tools ?? [];
4731
+ if (tools.length === 0) {
4732
+ return { message: `品类 "${category}" 下暂无可用工具`, tools: [] };
4733
+ }
4734
+ return {
4735
+ category,
4736
+ count: tools.length,
4737
+ tools: tools.map((t) => ({
4738
+ name: t.name,
4739
+ description: t.description ?? "",
4740
+ // 清洗 inputSchema,内联 $ref/$defs 引用并移除 Gemini 不支持的关键词,
4741
+ // 避免 Gemini 模型解析 function response 时报 400 错误
4742
+ inputSchema: t.inputSchema ? cleanSchemaForGemini(t.inputSchema) : undefined,
4743
+ })),
4744
+ };
4745
+ };
3450
4746
  // ============================================================================
3451
4747
  // call 操作:调用某品类的某个 MCP 工具
3452
4748
  // ============================================================================
3453
4749
  const handleCall = async (category, method, args) => {
4750
+ const ctx = { category, method, args };
3454
4751
  const callStart = performance.now();
3455
- // get_msg_media 使用延长的超时时间(120s),因为返回的 base64 数据可达 ~27MB
3456
- const options = method === "get_msg_media" ? { timeoutMs: MEDIA_DOWNLOAD_TIMEOUT_MS } : undefined;
4752
+ console.log(`[mcp] handleCall ${category}/${method} 入参: ${JSON.stringify(args)}`);
4753
+ // 1. 收集拦截器的 beforeCall 配置(如超时时间、替换 args)
4754
+ const { options, args: resolvedArgs } = await resolveBeforeCall(ctx);
4755
+ const finalArgs = resolvedArgs ?? args;
4756
+ if (resolvedArgs) {
4757
+ console.log(`[mcp] handleCall ${category}/${method} 拦截器替换 args: ${JSON.stringify(resolvedArgs).slice(0, 500)}` +
4758
+ (JSON.stringify(resolvedArgs).length > 500 ? "...(truncated)" : ""));
4759
+ }
4760
+ if (options) {
4761
+ console.log(`[mcp] handleCall ${category}/${method} 拦截器选项: ${JSON.stringify(options)}`);
4762
+ }
4763
+ // 2. 执行 MCP 调用
3457
4764
  const result = await sendJsonRpc(category, "tools/call", {
3458
4765
  name: method,
3459
- arguments: args,
4766
+ arguments: finalArgs,
3460
4767
  }, options);
3461
4768
  const rpcDone = performance.now();
3462
4769
  const rpcMs = (rpcDone - callStart).toFixed(1);
3463
- // 检查业务层错误码,必要时清理缓存
3464
- checkBizErrorAndClearCache(result, category);
3465
- // 对 get_msg_media 响应进行 base64 拦截:解码存本地,只返回路径给大模型
3466
- if (method === "get_msg_media") {
3467
- const intercepted = await interceptMediaResponse(result);
3468
- const totalMs = (performance.now() - callStart).toFixed(1);
4770
+ const resultStr = JSON.stringify(result);
4771
+ console.log(`[mcp] handleCall ${category}/${method} MCP 响应 (${rpcMs}ms): ${resultStr.slice(0, 800)}` +
4772
+ (resultStr.length > 800 ? "...(truncated)" : ""));
4773
+ // 3. 管道式执行 afterCall 拦截器(业务错误码检查、响应变换等)
4774
+ const finalResult = await runAfterCall(ctx, result);
4775
+ const totalMs = (performance.now() - callStart).toFixed(1);
4776
+ const interceptMs = (performance.now() - rpcDone).toFixed(1);
4777
+ // 有拦截器处理时打印详细耗时,否则只打印 RPC 耗时
4778
+ if (finalResult !== result) {
4779
+ const finalStr = JSON.stringify(finalResult);
4780
+ console.log(`[mcp] handleCall ${category}/${method} afterCall 变换后 (${interceptMs}ms): ${finalStr.slice(0, 500)}` +
4781
+ (finalStr.length > 500 ? "...(truncated)" : ""));
3469
4782
  console.log(`[mcp] handleCall ${category}/${method} 总耗时: ${totalMs}ms` +
3470
- ` (MCP请求: ${rpcMs}ms, 拦截处理: ${(performance.now() - rpcDone).toFixed(1)}ms)`);
3471
- return intercepted;
4783
+ ` (MCP请求: ${rpcMs}ms, 拦截处理: ${interceptMs}ms)`);
4784
+ }
4785
+ else {
4786
+ console.log(`[mcp] handleCall ${category}/${method} 耗时: ${rpcMs}ms`);
3472
4787
  }
3473
- console.log(`[mcp] handleCall ${category}/${method} 耗时: ${rpcMs}ms`);
3474
- return result;
4788
+ return finalResult;
3475
4789
  };
3476
4790
  // ============================================================================
3477
4791
  // 参数解析
@@ -3541,22 +4855,36 @@ function createWeComMcpTool() {
3541
4855
  },
3542
4856
  async execute(_toolCallId, params) {
3543
4857
  const p = params;
4858
+ console.log(`[mcp] execute: action=${p.action}, category=${p.category}` +
4859
+ (p.method ? `, method=${p.method}` : "") +
4860
+ (p.args ? `, args=${typeof p.args === "string" ? p.args : JSON.stringify(p.args)}` : ""));
3544
4861
  try {
4862
+ let result;
3545
4863
  switch (p.action) {
3546
4864
  case "list":
3547
- return textResult(await handleList(p.category));
4865
+ result = textResult(await handleList(p.category));
4866
+ break;
3548
4867
  case "call": {
3549
4868
  if (!p.method) {
3550
- return textResult({ error: "action 为 call 时必须提供 method 参数" });
4869
+ result = textResult({ error: "action 为 call 时必须提供 method 参数" });
4870
+ break;
3551
4871
  }
3552
4872
  const args = parseArgs(p.args);
3553
- return textResult(await handleCall(p.category, p.method, args));
4873
+ result = textResult(await handleCall(p.category, p.method, args));
4874
+ break;
3554
4875
  }
3555
4876
  default:
3556
- return textResult({ error: `未知操作类型: ${String(p.action)},支持 list 和 call` });
4877
+ result = textResult({ error: `未知操作类型: ${String(p.action)},支持 list 和 call` });
3557
4878
  }
4879
+ console.log(`[mcp] execute: action=${p.action}, category=${p.category}` +
4880
+ (p.method ? `, method=${p.method}` : "") +
4881
+ ` → 响应长度=${result.content[0].text.length} chars`);
4882
+ return result;
3558
4883
  }
3559
4884
  catch (err) {
4885
+ console.error(`[mcp] execute: action=${p.action}, category=${p.category}` +
4886
+ (p.method ? `, method=${p.method}` : "") +
4887
+ ` → 异常: ${err instanceof Error ? err.message : String(err)}`);
3560
4888
  return errorResult(err);
3561
4889
  }
3562
4890
  },
@@ -3586,7 +4914,8 @@ const plugin = {
3586
4914
  }
3587
4915
  return {
3588
4916
  appendSystemContext: [
3589
- "重要:涉及发送图片/视频/语音/文件给用户时,请务必使用 `MEDIA:` 指令。详见 wecom-send-media 这个 skill(技能)。"
4917
+ "重要:涉及发送图片/视频/语音/文件给用户时,请务必使用 `MEDIA:` 指令。详见 wecom-send-media 这个 skill(技能)。",
4918
+ "重要:当需要向用户发送结构化卡片消息(如通知、投票、按钮选择等)时,请在回复中直接输出 JSON 代码块(```json ... ```),其中 card_type 字段标明卡片类型。详见 wecom-send-template-card 技能。"
3590
4919
  ].join("\n"),
3591
4920
  };
3592
4921
  });