@sunnoy/wecom 1.4.1 → 1.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sunnoy/wecom",
3
- "version": "1.4.1",
3
+ "version": "1.5.0",
4
4
  "description": "Enterprise WeChat AI Bot channel plugin for OpenClaw",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -8,11 +8,18 @@ import { listAccountIds, resolveAccount, detectAccountConflicts } from "./accoun
8
8
  import { DEFAULT_ACCOUNT_ID, THINKING_PLACEHOLDER } from "./constants.js";
9
9
  import { parseResponseUrlResult } from "./response-url.js";
10
10
  import { messageBuffers, resolveAgentConfig, resolveWebhookUrl, responseUrls, streamContext } from "./state.js";
11
- import { resolveActiveStream } from "./stream-utils.js";
11
+ import { resolveRecoverableStream, unregisterActiveStream } from "./stream-utils.js";
12
12
  import { resolveWecomTarget } from "./target.js";
13
13
  import { webhookSendImage, webhookSendText, webhookUploadFile, webhookSendFile } from "./webhook-bot.js";
14
14
  import { registerWebhookTarget } from "./webhook-targets.js";
15
15
 
16
+ const AGENT_IMAGE_EXTS = new Set(["jpg", "jpeg", "png", "gif", "bmp"]);
17
+
18
+ export function resolveAgentMediaTypeFromFilename(filename) {
19
+ const ext = filename.split(".").pop()?.toLowerCase() || "";
20
+ return AGENT_IMAGE_EXTS.has(ext) ? "image" : "file";
21
+ }
22
+
16
23
  export const wecomChannelPlugin = {
17
24
  id: "wecom",
18
25
  meta: {
@@ -259,7 +266,7 @@ export const wecomChannelPlugin = {
259
266
 
260
267
  // Prefer stream from async context (correct for concurrent processing).
261
268
  const ctx = streamContext.getStore();
262
- const streamId = ctx?.streamId ?? resolveActiveStream(userId);
269
+ const streamId = ctx?.streamId ?? resolveRecoverableStream(userId);
263
270
 
264
271
  // Layer 1: Active stream (normal path)
265
272
  if (streamId && streamManager.hasStream(streamId) && !streamManager.getStream(streamId)?.finished) {
@@ -377,7 +384,7 @@ export const wecomChannelPlugin = {
377
384
 
378
385
  // Prefer stream from async context (correct for concurrent processing).
379
386
  const ctx = streamContext.getStore();
380
- const streamId = ctx?.streamId ?? resolveActiveStream(userId);
387
+ const streamId = ctx?.streamId ?? resolveRecoverableStream(userId);
381
388
 
382
389
  if (streamId && streamManager.hasStream(streamId)) {
383
390
  // Check if mediaUrl is a local path (sandbox: prefix or absolute path)
@@ -575,6 +582,7 @@ export const wecomChannelPlugin = {
575
582
  if (agentConfig) {
576
583
  try {
577
584
  const agentTarget = (target && !target.webhook) ? target : resolveWecomTarget(to) || { toUser: userId };
585
+ let deliveredFilename = "file";
578
586
 
579
587
  // Determine if mediaUrl is a local file path.
580
588
  let absolutePath = mediaUrl;
@@ -587,9 +595,11 @@ export const wecomChannelPlugin = {
587
595
  // Upload local file then send via Agent API.
588
596
  const buffer = await readFile(absolutePath);
589
597
  const filename = basename(absolutePath);
598
+ deliveredFilename = filename;
599
+ const uploadType = resolveAgentMediaTypeFromFilename(filename);
590
600
  const mediaId = await agentUploadMedia({
591
601
  agent: agentConfig,
592
- type: "image",
602
+ type: uploadType,
593
603
  buffer,
594
604
  filename,
595
605
  });
@@ -597,16 +607,25 @@ export const wecomChannelPlugin = {
597
607
  agent: agentConfig,
598
608
  ...agentTarget,
599
609
  mediaId,
600
- mediaType: "image",
610
+ mediaType: uploadType,
601
611
  });
602
612
  } else {
603
613
  // For external URLs, download first then upload.
604
614
  const res = await fetch(mediaUrl);
615
+ if (!res.ok) {
616
+ throw new Error(`download media failed: ${res.status}`);
617
+ }
605
618
  const buffer = Buffer.from(await res.arrayBuffer());
606
- const filename = basename(new URL(mediaUrl).pathname) || "image.png";
619
+ const filename = basename(new URL(mediaUrl).pathname) || "file";
620
+ deliveredFilename = filename;
621
+ let uploadType = resolveAgentMediaTypeFromFilename(filename);
622
+ const contentType = res.headers.get("content-type") || "";
623
+ if (uploadType === "file" && contentType.toLowerCase().startsWith("image/")) {
624
+ uploadType = "image";
625
+ }
607
626
  const mediaId = await agentUploadMedia({
608
627
  agent: agentConfig,
609
- type: "image",
628
+ type: uploadType,
610
629
  buffer,
611
630
  filename,
612
631
  });
@@ -614,7 +633,7 @@ export const wecomChannelPlugin = {
614
633
  agent: agentConfig,
615
634
  ...agentTarget,
616
635
  mediaId,
617
- mediaType: "image",
636
+ mediaType: uploadType,
618
637
  });
619
638
  }
620
639
 
@@ -623,6 +642,30 @@ export const wecomChannelPlugin = {
623
642
  await agentSendText({ agent: agentConfig, ...agentTarget, text });
624
643
  }
625
644
 
645
+ // Best-effort stream recovery: when async context is missing and the
646
+ // active stream mapping was already cleaned, still clear "thinking..."
647
+ // in the most recent stream for this user.
648
+ const recoverStreamId = resolveRecoverableStream(userId);
649
+ if (recoverStreamId && streamManager.hasStream(recoverStreamId)) {
650
+ const recoverStream = streamManager.getStream(recoverStreamId);
651
+ if (recoverStream && !recoverStream.finished) {
652
+ const deliveryHint = text
653
+ ? `${text}\n\nšŸ“Ž ę–‡ä»¶å·²é€ščæ‡ē§äæ”å‘é€ē»™ę‚Øļ¼š${deliveredFilename}`
654
+ : `šŸ“Ž ę–‡ä»¶å·²é€ščæ‡ē§äæ”å‘é€ē»™ę‚Øļ¼š${deliveredFilename}`;
655
+ streamManager.replaceIfPlaceholder(
656
+ recoverStreamId,
657
+ deliveryHint,
658
+ THINKING_PLACEHOLDER,
659
+ );
660
+ await streamManager.finishStream(recoverStreamId);
661
+ unregisterActiveStream(userId, recoverStreamId);
662
+ logger.info("WeCom: recovered and finished stream after media fallback", {
663
+ userId,
664
+ streamId: recoverStreamId,
665
+ });
666
+ }
667
+ }
668
+
626
669
  logger.info("WeCom: sent media via Agent API fallback (sendMedia)", {
627
670
  userId,
628
671
  to,
package/wecom/state.js CHANGED
@@ -14,6 +14,7 @@ export const messageBuffers = new Map();
14
14
  export const webhookTargets = new Map();
15
15
  export const activeStreams = new Map();
16
16
  export const activeStreamHistory = new Map();
17
+ export const lastStreamByKey = new Map();
17
18
  export const streamMeta = new Map();
18
19
  export const responseUrls = new Map();
19
20
  export const streamContext = new AsyncLocalStorage();
@@ -1,7 +1,7 @@
1
1
  import { logger } from "../logger.js";
2
2
  import { streamManager } from "../stream-manager.js";
3
3
  import { THINKING_PLACEHOLDER } from "./constants.js";
4
- import { activeStreamHistory, activeStreams, messageBuffers } from "./state.js";
4
+ import { activeStreamHistory, activeStreams, lastStreamByKey, messageBuffers } from "./state.js";
5
5
 
6
6
  export function getMessageStreamKey(message) {
7
7
  if (!message || typeof message !== "object") {
@@ -25,6 +25,7 @@ export function registerActiveStream(streamKey, streamId) {
25
25
  deduped.push(streamId);
26
26
  activeStreamHistory.set(streamKey, deduped);
27
27
  activeStreams.set(streamKey, streamId);
28
+ lastStreamByKey.set(streamKey, streamId);
28
29
  }
29
30
 
30
31
  export function unregisterActiveStream(streamKey, streamId) {
@@ -72,9 +73,33 @@ export function resolveActiveStream(streamKey) {
72
73
  activeStreamHistory.set(streamKey, remaining);
73
74
  const latest = remaining[remaining.length - 1];
74
75
  activeStreams.set(streamKey, latest);
76
+ lastStreamByKey.set(streamKey, latest);
75
77
  return latest;
76
78
  }
77
79
 
80
+ /**
81
+ * Resolve a usable stream id for a sender/group.
82
+ * Prefer active history; if that is temporarily empty, fall back to the latest
83
+ * known stream id for the same key (when it still exists).
84
+ */
85
+ export function resolveRecoverableStream(streamKey) {
86
+ const activeId = resolveActiveStream(streamKey);
87
+ if (activeId) {
88
+ return activeId;
89
+ }
90
+ if (!streamKey) {
91
+ return null;
92
+ }
93
+ const recentId = lastStreamByKey.get(streamKey);
94
+ if (!recentId) {
95
+ return null;
96
+ }
97
+ if (!streamManager.hasStream(recentId)) {
98
+ return null;
99
+ }
100
+ return recentId;
101
+ }
102
+
78
103
  export function clearBufferedMessagesForStream(streamKey, reason) {
79
104
  const buffer = messageBuffers.get(streamKey);
80
105
  if (!buffer) {