@wecom/wecom-openclaw-plugin 2026.3.30 → 2026.3.31-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +251 -4
  2. package/dist/index.d.ts +2 -4
  3. package/dist/index.js +113 -0
  4. package/dist/src/accounts.d.ts +57 -0
  5. package/dist/src/accounts.js +222 -0
  6. package/dist/src/agent/api-client.d.ts +94 -0
  7. package/dist/src/agent/api-client.js +292 -0
  8. package/dist/src/agent/handler.d.ts +63 -0
  9. package/dist/src/agent/handler.js +562 -0
  10. package/dist/src/agent/index.d.ts +5 -0
  11. package/dist/src/agent/index.js +5 -0
  12. package/dist/src/agent/webhook.d.ts +23 -0
  13. package/dist/src/agent/webhook.js +226 -0
  14. package/dist/src/agent/xml.d.ts +21 -0
  15. package/dist/src/agent/xml.js +41 -0
  16. package/dist/src/channel.js +564 -0
  17. package/dist/src/chat-queue.d.ts +31 -0
  18. package/dist/src/chat-queue.js +45 -0
  19. package/dist/src/const.d.ts +46 -0
  20. package/dist/src/const.js +157 -0
  21. package/dist/src/dm-policy.js +84 -0
  22. package/dist/src/dynamic-agent.d.ts +37 -0
  23. package/dist/src/dynamic-agent.js +60 -0
  24. package/dist/src/dynamic-routing.d.ts +75 -0
  25. package/dist/src/dynamic-routing.js +124 -0
  26. package/dist/src/group-policy.js +126 -0
  27. package/dist/src/http.d.ts +26 -0
  28. package/dist/src/http.js +93 -0
  29. package/dist/src/interface.d.ts +0 -2
  30. package/dist/src/interface.js +4 -0
  31. package/dist/src/mcp/index.js +6 -0
  32. package/dist/src/mcp/interceptors/biz-error.js +64 -0
  33. package/dist/src/mcp/interceptors/index.js +66 -0
  34. package/dist/src/mcp/interceptors/msg-media.js +133 -0
  35. package/dist/src/mcp/interceptors/smartpage-create.js +132 -0
  36. package/dist/src/mcp/interceptors/smartpage-export.js +87 -0
  37. package/dist/src/mcp/interceptors/types.js +7 -0
  38. package/dist/src/mcp/schema.js +99 -0
  39. package/dist/src/mcp/tool.js +202 -0
  40. package/dist/src/mcp/transport.js +410 -0
  41. package/dist/src/media-handler.js +122 -0
  42. package/dist/src/media-uploader.js +333 -0
  43. package/dist/src/message-parser.js +129 -0
  44. package/dist/src/message-sender.d.ts +18 -0
  45. package/dist/src/message-sender.js +120 -0
  46. package/dist/src/monitor.js +875 -0
  47. package/dist/src/onboarding.js +175 -0
  48. package/dist/src/openclaw-compat.d.ts +47 -0
  49. package/dist/src/openclaw-compat.js +477 -0
  50. package/dist/src/reqid-store.js +83 -0
  51. package/dist/src/routing.d.ts +24 -0
  52. package/dist/src/routing.js +34 -0
  53. package/dist/src/runtime.js +10 -0
  54. package/dist/src/shared/command-auth.d.ts +23 -0
  55. package/dist/src/shared/command-auth.js +73 -0
  56. package/dist/src/shared/xml-parser.d.ts +46 -0
  57. package/dist/src/shared/xml-parser.js +210 -0
  58. package/dist/src/state-dir-resolve.d.ts +2 -0
  59. package/dist/src/state-dir-resolve.js +9 -0
  60. package/dist/src/state-manager.js +216 -0
  61. package/dist/src/target.d.ts +35 -0
  62. package/dist/src/target.js +67 -0
  63. package/dist/src/template-card-manager.d.ts +55 -0
  64. package/dist/src/template-card-manager.js +205 -0
  65. package/dist/src/template-card-parser.js +647 -0
  66. package/dist/src/timeout.js +36 -0
  67. package/dist/src/types/account.d.ts +29 -0
  68. package/dist/src/types/account.js +4 -0
  69. package/dist/src/types/config.d.ts +100 -0
  70. package/dist/src/types/config.js +7 -0
  71. package/dist/src/types/constants.d.ts +42 -0
  72. package/dist/src/types/constants.js +42 -0
  73. package/dist/src/types/index.d.ts +7 -0
  74. package/dist/src/types/index.js +5 -0
  75. package/dist/src/types/message.d.ts +238 -0
  76. package/dist/src/types/message.js +5 -0
  77. package/dist/src/utils.d.ts +39 -0
  78. package/dist/src/utils.js +70 -0
  79. package/dist/src/version.d.ts +1 -1
  80. package/dist/src/version.js +24 -0
  81. package/dist/src/webhook/command-auth.d.ts +47 -0
  82. package/dist/src/webhook/command-auth.js +96 -0
  83. package/dist/src/webhook/gateway.d.ts +36 -0
  84. package/dist/src/webhook/gateway.js +227 -0
  85. package/dist/src/webhook/handler.d.ts +18 -0
  86. package/dist/src/webhook/handler.js +420 -0
  87. package/dist/src/webhook/helpers.d.ts +156 -0
  88. package/dist/src/webhook/helpers.js +833 -0
  89. package/dist/src/webhook/http.d.ts +26 -0
  90. package/dist/src/webhook/http.js +94 -0
  91. package/dist/src/webhook/index.d.ts +11 -0
  92. package/dist/src/webhook/index.js +14 -0
  93. package/dist/src/webhook/media.d.ts +29 -0
  94. package/dist/src/webhook/media.js +88 -0
  95. package/dist/src/webhook/monitor.d.ts +59 -0
  96. package/dist/src/webhook/monitor.js +1185 -0
  97. package/dist/src/webhook/state.d.ts +220 -0
  98. package/dist/src/webhook/state.js +491 -0
  99. package/dist/src/webhook/target.d.ts +41 -0
  100. package/dist/src/webhook/target.js +132 -0
  101. package/dist/src/webhook/types.d.ts +347 -0
  102. package/dist/src/webhook/types.js +33 -0
  103. package/package.json +15 -7
  104. package/dist/index.cjs.js +0 -4953
  105. package/dist/index.cjs.js.map +0 -1
  106. package/dist/index.esm.js +0 -4926
  107. package/dist/index.esm.js.map +0 -1
@@ -0,0 +1,126 @@
1
+ /**
2
+ * 企业微信群组访问控制模块
3
+ *
4
+ * 负责群组策略检查(groupPolicy、群组白名单、群内发送者白名单)
5
+ */
6
+ import { CHANNEL_ID } from "./const.js";
7
+ // ============================================================================
8
+ // 内部辅助函数
9
+ // ============================================================================
10
+ /**
11
+ * 解析企业微信群组配置
12
+ */
13
+ function resolveWeComGroupConfig(params) {
14
+ const groups = params.cfg?.groups ?? {};
15
+ const wildcard = groups["*"];
16
+ const groupId = params.groupId?.trim();
17
+ if (!groupId) {
18
+ return undefined;
19
+ }
20
+ const direct = groups[groupId];
21
+ if (direct) {
22
+ return direct;
23
+ }
24
+ const lowered = groupId.toLowerCase();
25
+ const matchKey = Object.keys(groups).find((key) => key.toLowerCase() === lowered);
26
+ if (matchKey) {
27
+ return groups[matchKey];
28
+ }
29
+ return wildcard;
30
+ }
31
+ /**
32
+ * 检查群组是否在允许列表中
33
+ */
34
+ function isWeComGroupAllowed(params) {
35
+ const { groupPolicy } = params;
36
+ if (groupPolicy === "disabled") {
37
+ return false;
38
+ }
39
+ if (groupPolicy === "open") {
40
+ return true;
41
+ }
42
+ // allowlist 模式:检查群组是否在允许列表中
43
+ const normalizedAllowFrom = params.allowFrom.map((entry) => String(entry).replace(new RegExp(`^${CHANNEL_ID}:`, "i"), "").trim());
44
+ if (normalizedAllowFrom.includes("*")) {
45
+ return true;
46
+ }
47
+ const normalizedGroupId = params.groupId.trim();
48
+ return normalizedAllowFrom.some((entry) => entry === normalizedGroupId || entry.toLowerCase() === normalizedGroupId.toLowerCase());
49
+ }
50
+ /**
51
+ * 检查群组内发送者是否在允许列表中
52
+ */
53
+ function isGroupSenderAllowed(params) {
54
+ const { senderId, groupId, wecomConfig } = params;
55
+ const groupConfig = resolveWeComGroupConfig({
56
+ cfg: wecomConfig,
57
+ groupId,
58
+ });
59
+ const perGroupSenderAllowFrom = (groupConfig?.allowFrom ?? []).map((v) => String(v));
60
+ if (perGroupSenderAllowFrom.length === 0) {
61
+ return true;
62
+ }
63
+ if (perGroupSenderAllowFrom.includes("*")) {
64
+ return true;
65
+ }
66
+ return perGroupSenderAllowFrom.some((entry) => {
67
+ const normalized = entry.replace(new RegExp(`^${CHANNEL_ID}:`, "i"), "").trim();
68
+ return normalized === senderId || normalized === `user:${senderId}`;
69
+ });
70
+ }
71
+ // ============================================================================
72
+ // 公开 API
73
+ // ============================================================================
74
+ /**
75
+ * 检查群组策略访问控制
76
+ * @returns 检查结果,包含是否允许继续处理
77
+ */
78
+ export function checkGroupPolicy(params) {
79
+ const { chatId, senderId, account, config, runtime } = params;
80
+ const wecomConfig = (config.channels?.[CHANNEL_ID] ?? {});
81
+ const defaultGroupPolicy = config.channels?.[CHANNEL_ID]?.groupPolicy;
82
+ const groupPolicy = account.config.groupPolicy ?? defaultGroupPolicy ?? "open";
83
+ // const { groupPolicy, providerMissingFallbackApplied } = resolveOpenProviderRuntimeGroupPolicy({
84
+ // providerConfigPresent: config.channels?.[CHANNEL_ID] !== undefined,
85
+ // groupPolicy: wecomConfig.groupPolicy,
86
+ // defaultGroupPolicy,
87
+ // });
88
+ // warnMissingProviderGroupPolicyFallbackOnce({
89
+ // providerMissingFallbackApplied,
90
+ // providerKey: CHANNEL_ID,
91
+ // accountId: account.accountId,
92
+ // log: (msg) => runtime.log?.(msg),
93
+ // });
94
+ const groupAllowFrom = wecomConfig.groupAllowFrom ?? [];
95
+ const groupAllowed = isWeComGroupAllowed({
96
+ groupPolicy,
97
+ allowFrom: groupAllowFrom,
98
+ groupId: chatId,
99
+ });
100
+ if (!groupAllowed) {
101
+ runtime.log?.(`[WeCom] Group ${chatId} not allowed (groupPolicy=${groupPolicy})`);
102
+ return { allowed: false };
103
+ }
104
+ const senderAllowed = isGroupSenderAllowed({
105
+ senderId,
106
+ groupId: chatId,
107
+ wecomConfig,
108
+ });
109
+ if (!senderAllowed) {
110
+ runtime.log?.(`[WeCom] Sender ${senderId} not in group ${chatId} sender allowlist`);
111
+ return { allowed: false };
112
+ }
113
+ return { allowed: true };
114
+ }
115
+ /**
116
+ * 检查发送者是否在允许列表中(通用)
117
+ */
118
+ export function isSenderAllowed(senderId, allowFrom) {
119
+ if (allowFrom.includes("*")) {
120
+ return true;
121
+ }
122
+ return allowFrom.some((entry) => {
123
+ const normalized = entry.replace(new RegExp(`^${CHANNEL_ID}:`, "i"), "").trim();
124
+ return normalized === senderId || normalized === `user:${senderId}`;
125
+ });
126
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * **WecomHttpOptions (HTTP 选项)**
3
+ *
4
+ * @property proxyUrl 代理服务器地址
5
+ * @property timeoutMs 请求超时时间 (毫秒)
6
+ * @property signal AbortSignal 信号
7
+ */
8
+ export type WecomHttpOptions = {
9
+ proxyUrl?: string;
10
+ timeoutMs?: number;
11
+ signal?: AbortSignal;
12
+ };
13
+ /**
14
+ * **wecomFetch (统一 HTTP 请求)**
15
+ *
16
+ * 基于 `undici` 的 fetch 封装,自动处理 ProxyAgent 和 Timeout。
17
+ * 所有对企业微信 API 的调用都应经过此函数。
18
+ */
19
+ export declare function wecomFetch(input: string | URL, init?: RequestInit, opts?: WecomHttpOptions): Promise<Response>;
20
+ /**
21
+ * **readResponseBodyAsBuffer (读取响应 Body)**
22
+ *
23
+ * 将 Response Body 读取为 Buffer,支持最大字节限制以防止内存溢出。
24
+ * 适用于下载媒体文件等场景。
25
+ */
26
+ export declare function readResponseBodyAsBuffer(res: Response, maxBytes?: number): Promise<Buffer>;
@@ -0,0 +1,93 @@
1
+ import { ProxyAgent, fetch as undiciFetch } from "undici";
2
+ const proxyDispatchers = new Map();
3
+ /**
4
+ * **getProxyDispatcher (获取代理 Dispatcher)**
5
+ *
6
+ * 缓存并复用 ProxyAgent,避免重复创建连接池。
7
+ */
8
+ function getProxyDispatcher(proxyUrl) {
9
+ const existing = proxyDispatchers.get(proxyUrl);
10
+ if (existing)
11
+ return existing;
12
+ const created = new ProxyAgent(proxyUrl);
13
+ proxyDispatchers.set(proxyUrl, created);
14
+ return created;
15
+ }
16
+ function mergeAbortSignal(params) {
17
+ const signals = [];
18
+ if (params.signal)
19
+ signals.push(params.signal);
20
+ if (params.timeoutMs && Number.isFinite(params.timeoutMs) && params.timeoutMs > 0) {
21
+ signals.push(AbortSignal.timeout(params.timeoutMs));
22
+ }
23
+ if (!signals.length)
24
+ return undefined;
25
+ if (signals.length === 1)
26
+ return signals[0];
27
+ return AbortSignal.any(signals);
28
+ }
29
+ /**
30
+ * **wecomFetch (统一 HTTP 请求)**
31
+ *
32
+ * 基于 `undici` 的 fetch 封装,自动处理 ProxyAgent 和 Timeout。
33
+ * 所有对企业微信 API 的调用都应经过此函数。
34
+ */
35
+ export async function wecomFetch(input, init, opts) {
36
+ const proxyUrl = opts?.proxyUrl?.trim() ?? "";
37
+ const dispatcher = proxyUrl ? getProxyDispatcher(proxyUrl) : undefined;
38
+ const initSignal = init?.signal ?? undefined;
39
+ const signal = mergeAbortSignal({ signal: opts?.signal ?? initSignal, timeoutMs: opts?.timeoutMs });
40
+ const headers = new Headers(init?.headers ?? {});
41
+ if (!headers.has("User-Agent")) {
42
+ headers.set("User-Agent", "OpenClaw/2.0 (WeCom-Agent)");
43
+ }
44
+ const nextInit = {
45
+ ...(init ?? {}),
46
+ ...(signal ? { signal } : {}),
47
+ ...(dispatcher ? { dispatcher } : {}),
48
+ headers,
49
+ };
50
+ try {
51
+ return await undiciFetch(input, nextInit);
52
+ }
53
+ catch (err) {
54
+ if (err instanceof Error && err.name === "TypeError" && err.message === "fetch failed") {
55
+ const cause = err.cause;
56
+ console.error(`[wecom-http] fetch failed: ${input} (proxy: ${proxyUrl || "none"})${cause ? ` - cause: ${String(cause)}` : ""}`);
57
+ }
58
+ throw err;
59
+ }
60
+ }
61
+ /**
62
+ * **readResponseBodyAsBuffer (读取响应 Body)**
63
+ *
64
+ * 将 Response Body 读取为 Buffer,支持最大字节限制以防止内存溢出。
65
+ * 适用于下载媒体文件等场景。
66
+ */
67
+ export async function readResponseBodyAsBuffer(res, maxBytes) {
68
+ if (!res.body)
69
+ return Buffer.alloc(0);
70
+ const limit = maxBytes && Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : undefined;
71
+ const chunks = [];
72
+ let total = 0;
73
+ const reader = res.body.getReader();
74
+ while (true) {
75
+ const { done, value } = await reader.read();
76
+ if (done)
77
+ break;
78
+ if (!value)
79
+ continue;
80
+ total += value.byteLength;
81
+ if (limit && total > limit) {
82
+ try {
83
+ await reader.cancel("body too large");
84
+ }
85
+ catch {
86
+ // ignore
87
+ }
88
+ throw new Error(`response body too large (>${limit} bytes)`);
89
+ }
90
+ chunks.push(value);
91
+ }
92
+ return Buffer.concat(chunks.map((c) => Buffer.from(c)));
93
+ }
@@ -29,8 +29,6 @@ export interface MessageState {
29
29
  hasMediaFailed?: boolean;
30
30
  /** 媒体发送失败时的纯文本错误摘要(用于替换 thinking 流展示给用户) */
31
31
  mediaErrorSummary?: string;
32
- /** deliver 回调是否被调用过(用于区分"核心无回复"和"核心回复了空内容") */
33
- deliverCalled?: boolean;
34
32
  /** 流式回复是否已过期(errcode 846608,>6分钟),需降级为主动发送 */
35
33
  streamExpired?: boolean;
36
34
  /** 是否已成功发送过模板卡片 */
@@ -0,0 +1,4 @@
1
+ /**
2
+ * 企业微信渠道类型定义
3
+ */
4
+ export {};
@@ -0,0 +1,6 @@
1
+ /**
2
+ * MCP 模块统一导出
3
+ */
4
+ export { createWeComMcpTool } from "./tool.js";
5
+ export { sendJsonRpc, clearCategoryCache, McpRpcError, McpHttpError } from "./transport.js";
6
+ export { cleanSchemaForGemini } from "./schema.js";
@@ -0,0 +1,64 @@
1
+ /**
2
+ * 业务错误码检查拦截器
3
+ *
4
+ * 检查 tools/call 返回结果中是否包含需要清理缓存的业务错误码。
5
+ * MCP Server 可能在正常的 JSON-RPC 响应中返回业务层错误,
6
+ * 这些错误被包裹在 result.content[].text 中,需要解析后判断。
7
+ *
8
+ * 此拦截器对所有 call 调用生效。
9
+ */
10
+ import { clearCategoryCache } from "../transport.js";
11
+ // ============================================================================
12
+ // 常量
13
+ // ============================================================================
14
+ /**
15
+ * 需要触发缓存清理的业务错误码集合
16
+ *
17
+ * 这些错误码出现在 MCP 工具调用返回的 content 文本中(业务层面),
18
+ * 与 JSON-RPC 层面的错误码不同,需要在此处额外检测。
19
+ *
20
+ * - 850002: 机器人未被授权使用对应能力,需清理缓存以便下次重新拉取配置
21
+ */
22
+ const BIZ_CACHE_CLEAR_ERROR_CODES = new Set([850002]);
23
+ // ============================================================================
24
+ // 拦截器实现
25
+ // ============================================================================
26
+ export const bizErrorInterceptor = {
27
+ name: "biz-error",
28
+ /** 对所有 call 调用生效 */
29
+ match: () => true,
30
+ /** 检查返回结果中的业务错误码,必要时清理缓存 */
31
+ afterCall(ctx, result) {
32
+ checkBizErrorAndClearCache(result, ctx.category);
33
+ // 不修改 result,透传给下一个拦截器
34
+ return result;
35
+ },
36
+ };
37
+ // ============================================================================
38
+ // 内部实现
39
+ // ============================================================================
40
+ /**
41
+ * 检查 tools/call 的返回结果中是否包含需要清理缓存的业务错误码
42
+ */
43
+ function checkBizErrorAndClearCache(result, category) {
44
+ if (!result || typeof result !== "object")
45
+ return;
46
+ const { content } = result;
47
+ if (!Array.isArray(content))
48
+ return;
49
+ for (const item of content) {
50
+ if (item.type !== "text" || !item.text)
51
+ continue;
52
+ try {
53
+ const parsed = JSON.parse(item.text);
54
+ if (typeof parsed.errcode === "number" && BIZ_CACHE_CLEAR_ERROR_CODES.has(parsed.errcode)) {
55
+ console.log(`[mcp] 检测到业务错误码 ${parsed.errcode} (category="${category}"),清理缓存`);
56
+ clearCategoryCache(category);
57
+ return;
58
+ }
59
+ }
60
+ catch {
61
+ // text 不是 JSON 格式,跳过
62
+ }
63
+ }
64
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * MCP call 拦截器注册表与调度入口
3
+ *
4
+ * 所有 call 拦截器在此注册,按注册顺序执行。
5
+ * 新增拦截器只需:
6
+ * 1. 在 interceptors/ 目录下新建文件,实现 CallInterceptor 接口
7
+ * 2. 在下方 interceptors 数组中注册
8
+ *
9
+ * tool.ts 的 handleCall 无需任何改动。
10
+ */
11
+ import { bizErrorInterceptor } from "./biz-error.js";
12
+ import { mediaInterceptor } from "./msg-media.js";
13
+ import { smartpageCreateInterceptor } from "./smartpage-create.js";
14
+ import { smartpageExportInterceptor } from "./smartpage-export.js";
15
+ // ============================================================================
16
+ // 拦截器注册表(按注册顺序执行)
17
+ // ============================================================================
18
+ const interceptors = [
19
+ bizErrorInterceptor, // 业务错误码检查(所有 call 生效)
20
+ mediaInterceptor, // get_msg_media base64 拦截
21
+ smartpageCreateInterceptor, // smartpage_create 本地文件读取
22
+ smartpageExportInterceptor, // smartpage_get_export_result content → 本地文件
23
+ ];
24
+ /**
25
+ * 收集匹配的 beforeCall 配置,合并后返回
26
+ *
27
+ * 合并策略:
28
+ * - timeoutMs: 取所有拦截器返回值中的最大值
29
+ * - args: 后注册的拦截器覆盖前者(一般同一调用只有一个拦截器会返回 args)
30
+ */
31
+ export async function resolveBeforeCall(ctx) {
32
+ let mergedTimeoutMs;
33
+ let mergedArgs;
34
+ for (const interceptor of interceptors) {
35
+ if (!interceptor.match(ctx) || !interceptor.beforeCall)
36
+ continue;
37
+ const opts = await interceptor.beforeCall(ctx);
38
+ if (opts?.timeoutMs !== undefined) {
39
+ mergedTimeoutMs = mergedTimeoutMs === undefined
40
+ ? opts.timeoutMs
41
+ : Math.max(mergedTimeoutMs, opts.timeoutMs);
42
+ }
43
+ if (opts?.args !== undefined) {
44
+ mergedArgs = opts.args;
45
+ }
46
+ }
47
+ return {
48
+ options: mergedTimeoutMs !== undefined ? { timeoutMs: mergedTimeoutMs } : undefined,
49
+ args: mergedArgs,
50
+ };
51
+ }
52
+ /**
53
+ * 依次执行匹配的 afterCall 拦截器,管道式传递 result
54
+ *
55
+ * 前一个拦截器的返回值作为下一个拦截器的输入。
56
+ * 拦截器若不需要修改 result,应原样返回。
57
+ */
58
+ export async function runAfterCall(ctx, result) {
59
+ let current = result;
60
+ for (const interceptor of interceptors) {
61
+ if (!interceptor.match(ctx) || !interceptor.afterCall)
62
+ continue;
63
+ current = await interceptor.afterCall(ctx, current);
64
+ }
65
+ return current;
66
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * get_msg_media 响应拦截器
3
+ *
4
+ * 核心逻辑:
5
+ * 1. beforeCall: 设置延长的超时时间(120s),因为 base64 数据可达 ~27MB
6
+ * 2. afterCall: 从 MCP result 的 content[].text 中提取 base64_data,
7
+ * 解码为 Buffer 并通过 saveMediaBuffer 保存到本地媒体目录,
8
+ * 替换响应中的 base64_data 为 local_path,避免大模型被 base64 数据消耗 token
9
+ */
10
+ import * as fs from "node:fs/promises";
11
+ import * as path from "node:path";
12
+ import { MEDIA_DOWNLOAD_TIMEOUT_MS } from "../transport.js";
13
+ import { getWeComRuntime } from "../../runtime.js";
14
+ import { detectMime } from "../../openclaw-compat.js";
15
+ // ============================================================================
16
+ // 拦截器实现
17
+ // ============================================================================
18
+ export const mediaInterceptor = {
19
+ name: "media",
20
+ /** 仅对 get_msg_media 方法生效 */
21
+ match: (ctx) => ctx.method === "get_msg_media",
22
+ /** 设置延长的超时时间 */
23
+ beforeCall() {
24
+ return { timeoutMs: MEDIA_DOWNLOAD_TIMEOUT_MS };
25
+ },
26
+ /** 拦截响应:base64 → 本地文件 */
27
+ async afterCall(ctx, result) {
28
+ return interceptMediaResponse(result);
29
+ },
30
+ };
31
+ // ============================================================================
32
+ // 内部实现
33
+ // ============================================================================
34
+ /**
35
+ * 拦截 get_msg_media 的 MCP 响应
36
+ *
37
+ * 1. 从 MCP result 的 content[].text 中提取业务 JSON
38
+ * 2. 提取 media_item.base64_data,解码为 Buffer
39
+ * 3. 通过 openclaw SDK 的 saveMediaBuffer 保存到本地媒体目录
40
+ * 4. 替换响应:移除 base64_data,加入 local_path
41
+ *
42
+ * 这样大模型只看到轻量的文件路径信息,不会被 base64 数据消耗 token。
43
+ */
44
+ async function interceptMediaResponse(result) {
45
+ const t0 = performance.now();
46
+ // 1. 提取 MCP result 中的 content 数组
47
+ const content = result?.content;
48
+ if (!Array.isArray(content))
49
+ return result;
50
+ const textItem = content.find((c) => c.type === "text" && typeof c.text === "string");
51
+ if (!textItem)
52
+ return result;
53
+ // 2. 解析业务 JSON
54
+ let bizData;
55
+ try {
56
+ bizData = JSON.parse(textItem.text);
57
+ }
58
+ catch {
59
+ // 非 JSON 格式,原样返回
60
+ return result;
61
+ }
62
+ // 3. 校验业务响应:errcode !== 0 或无 media_item 时原样返回
63
+ if (bizData.errcode !== 0)
64
+ return result;
65
+ const mediaItem = bizData.media_item;
66
+ if (!mediaItem || typeof mediaItem.base64_data !== "string")
67
+ return result;
68
+ const base64Data = mediaItem.base64_data;
69
+ const mediaName = mediaItem.name;
70
+ const mediaType = mediaItem.type;
71
+ const mediaId = mediaItem.media_id;
72
+ const tParsed = performance.now();
73
+ // 4. 解码 base64 → Buffer
74
+ const buffer = Buffer.from(base64Data, "base64");
75
+ const tDecoded = performance.now();
76
+ // 5. 检测 contentType,并通过 saveMediaBuffer 保存到本地媒体目录
77
+ const contentType = await detectMime({ buffer, filePath: mediaName }) ?? "application/octet-stream";
78
+ const tMimeDetected = performance.now();
79
+ // 企业微信聊天记录附件可达 20MB(文件消息上限),
80
+ // 而 saveMediaBuffer 默认 maxBytes 为 5MB(针对 outbound 场景),
81
+ // 此处显式放宽到 20MB 以支持大文件下载。
82
+ const INBOUND_MAX_BYTES = 20 * 1024 * 1024; // 20MB
83
+ const core = getWeComRuntime();
84
+ const saved = await core.channel.media.saveMediaBuffer(buffer, contentType, "inbound", INBOUND_MAX_BYTES, // maxBytes: 放宽到 20MB,匹配企业微信文件消息上限
85
+ mediaName);
86
+ // 5.1 补偿:核心库 EXT_BY_MIME 可能缺少某些格式映射(如 audio/amr),
87
+ // 导致保存的文件没有后缀。此处检测并修复。
88
+ const MIME_EXT_PATCH = {
89
+ "audio/amr": ".amr",
90
+ };
91
+ const patchExt = MIME_EXT_PATCH[contentType];
92
+ if (patchExt && !path.extname(saved.path)) {
93
+ const newPath = saved.path + patchExt;
94
+ try {
95
+ await fs.rename(saved.path, newPath);
96
+ saved.path = newPath;
97
+ }
98
+ catch {
99
+ // rename 失败不影响主流程,文件仍可用
100
+ }
101
+ }
102
+ const tSaved = performance.now();
103
+ // 6. 构造精简响应,移除 base64_data,加入本地路径
104
+ const newBizData = {
105
+ errcode: 0,
106
+ errmsg: "ok",
107
+ media_item: {
108
+ media_id: mediaId,
109
+ name: mediaName ?? saved.path.split("/").pop(),
110
+ type: mediaType,
111
+ local_path: saved.path,
112
+ size: buffer.length,
113
+ content_type: saved.contentType,
114
+ },
115
+ };
116
+ const tEnd = performance.now();
117
+ // 耗时日志:各环节耗时(ms)
118
+ console.log(`[mcp] get_msg_media 拦截成功: media_id=${mediaId ?? "unknown"}, ` +
119
+ `type=${mediaType ?? "unknown"}, size=${buffer.length}, saved=${saved.path}\n` +
120
+ ` ⏱ 耗时明细 (总 ${(tEnd - t0).toFixed(1)}ms):\n` +
121
+ ` 解析响应 JSON: ${(tParsed - t0).toFixed(1)}ms\n` +
122
+ ` base64 解码: ${(tDecoded - tParsed).toFixed(1)}ms (${(base64Data.length / 1024).toFixed(0)}KB base64 → ${(buffer.length / 1024).toFixed(0)}KB buffer)\n` +
123
+ ` MIME 检测: ${(tMimeDetected - tDecoded).toFixed(1)}ms (${contentType})\n` +
124
+ ` saveMediaBuffer: ${(tSaved - tMimeDetected).toFixed(1)}ms\n` +
125
+ ` 构造响应: ${(tEnd - tSaved).toFixed(1)}ms`);
126
+ // 7. 返回修改后的 MCP result 结构
127
+ return {
128
+ content: [{
129
+ type: "text",
130
+ text: JSON.stringify(newBizData),
131
+ }],
132
+ };
133
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * smartpage_create 请求拦截器
3
+ *
4
+ * 核心逻辑:
5
+ * smartpage_create 的 pages 数组中,每个 page 可能包含 page_filepath 字段
6
+ * (指向本地 markdown 文件),用于避免在命令行传递大段文本内容。
7
+ * 本拦截器在 beforeCall 阶段遍历 pages 数组,逐个读取 page_filepath
8
+ * 指向的本地文件内容,填入 page_content 字段,并移除 page_filepath。
9
+ *
10
+ * 入参约定:
11
+ * wecom_mcp call doc smartpage_create '{
12
+ * "title": "主页标题",
13
+ * "pages": [
14
+ * {"page_title": "页面1", "page_filepath": "/tmp/page1.md", "content_type": "markdown"},
15
+ * {"page_title": "页面2", "page_filepath": "/tmp/page2.md", "content_type": "markdown"}
16
+ * ]
17
+ * }'
18
+ *
19
+ * 拦截器行为:
20
+ * 1. 检测 args.pages 数组
21
+ * 2. 校验文件大小:单文件不超过 10MB,所有文件总计不超过 20MB
22
+ * 3. 遍历每个 page,若存在 page_filepath 则读取本地文件内容
23
+ * 4. 将文件内容填入 page_content 字段,移除 page_filepath
24
+ * 5. 返回修改后的完整 args
25
+ *
26
+ * 传给 MCP Server 的格式:
27
+ * { "title": "...", "pages": [{"page_title": "...", "page_content": "...", "content_type": "..."}] }
28
+ */
29
+ import * as fs from "node:fs/promises";
30
+ // ============================================================================
31
+ // 常量
32
+ // ============================================================================
33
+ /** 单个 page_filepath 文件大小上限:10MB */
34
+ const MAX_SINGLE_FILE_SIZE = 10 * 1024 * 1024;
35
+ /** 所有 page_filepath 文件总大小上限:20MB */
36
+ const MAX_TOTAL_FILE_SIZE = 20 * 1024 * 1024;
37
+ // ============================================================================
38
+ // 内部辅助函数
39
+ // ============================================================================
40
+ /**
41
+ * 校验所有 page_filepath 的文件大小
42
+ *
43
+ * 使用 fs.stat 在读取文件内容之前检查大小,避免超大文件被加载到内存。
44
+ * - 单文件 > 10MB → 报错
45
+ * - 所有文件累计 > 20MB → 报错
46
+ */
47
+ async function validateFileSize(pages) {
48
+ let totalSize = 0;
49
+ for (let i = 0; i < pages.length; i++) {
50
+ const filePath = pages[i].page_filepath;
51
+ if (typeof filePath !== "string" || !filePath)
52
+ continue;
53
+ let stat;
54
+ try {
55
+ stat = await fs.stat(filePath);
56
+ }
57
+ catch (err) {
58
+ // stat 失败不在这里处理,留给后续 readFile 阶段抛出更详细的错误
59
+ continue;
60
+ }
61
+ if (stat.size > MAX_SINGLE_FILE_SIZE) {
62
+ console.error(`[mcp] smartpage_create: pages[${i}] 文件 "${filePath}" ` +
63
+ `大小 ${(stat.size / 1024 / 1024).toFixed(1)}MB 超过单文件上限 10MB`);
64
+ throw new Error("内容大小超出限制,无法创建");
65
+ }
66
+ totalSize += stat.size;
67
+ if (totalSize > MAX_TOTAL_FILE_SIZE) {
68
+ console.error(`[mcp] smartpage_create: 累计文件大小 ${(totalSize / 1024 / 1024).toFixed(1)}MB ` +
69
+ `超过总上限 20MB(在 pages[${i}] "${filePath}" 处超出)`);
70
+ throw new Error("内容大小超出限制,无法创建");
71
+ }
72
+ }
73
+ if (totalSize > 0) {
74
+ console.log(`[mcp] smartpage_create: 文件大小校验通过,总计 ${(totalSize / 1024 / 1024).toFixed(2)}MB`);
75
+ }
76
+ }
77
+ /** 异步解析 pages 中的 page_filepath,返回 BeforeCallOptions */
78
+ async function resolvePages(ctx, pages) {
79
+ console.log(`[mcp] smartpage_create: 开始解析 ${pages.length} 个 page 的 page_filepath`);
80
+ // 阶段 1:文件大小校验(stat 阶段,不读内容)
81
+ await validateFileSize(pages);
82
+ // 阶段 2:读取文件内容
83
+ const resolvedPages = await Promise.all(pages.map(async (page, index) => {
84
+ const filePath = page.page_filepath;
85
+ if (typeof filePath !== "string" || !filePath) {
86
+ // 该 page 没有 page_filepath,保留原样(可能已有 page_content)
87
+ return page;
88
+ }
89
+ let fileContent;
90
+ try {
91
+ fileContent = await fs.readFile(filePath, "utf-8");
92
+ }
93
+ catch (err) {
94
+ throw new Error(`smartpage_create: pages[${index}] 无法读取文件 "${filePath}": ${err instanceof Error ? err.message : String(err)}`);
95
+ }
96
+ console.log(`[mcp] smartpage_create: pages[${index}] 读取成功 "${filePath}" (${fileContent.length} chars)`);
97
+ // 构造新的 page 对象:填入 page_content,移除 page_filepath
98
+ const { page_filepath: _, ...rest } = page;
99
+ return { ...rest, page_content: fileContent };
100
+ }));
101
+ console.log(`[mcp] smartpage_create: 所有 page_filepath 解析完成`);
102
+ // 返回修改后的完整 args
103
+ return {
104
+ args: {
105
+ ...ctx.args,
106
+ pages: resolvedPages,
107
+ },
108
+ };
109
+ }
110
+ // ============================================================================
111
+ // 拦截器实现
112
+ // ============================================================================
113
+ export const smartpageCreateInterceptor = {
114
+ name: "smartpage-create",
115
+ /** 仅对 doc 品类的 smartpage_create 方法生效 */
116
+ match: (ctx) => ctx.category === "doc" && ctx.method === "smartpage_create",
117
+ /** 遍历 pages 数组,逐个读取 page_filepath 填入 page_content */
118
+ beforeCall(ctx) {
119
+ const pages = ctx.args.pages;
120
+ if (!Array.isArray(pages) || pages.length === 0) {
121
+ // 没有 pages 数组,不做拦截
122
+ return undefined;
123
+ }
124
+ // 检查是否有任何 page 包含 page_filepath
125
+ const hasFilePath = pages.some((p) => typeof p.page_filepath === "string" && p.page_filepath);
126
+ if (!hasFilePath) {
127
+ // 所有 page 都没有 page_filepath(可能直接传了 page_content),不做拦截
128
+ return undefined;
129
+ }
130
+ return resolvePages(ctx, pages);
131
+ },
132
+ };