@yanhaidao/wecom 2.3.3 → 2.3.9

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 (111) hide show
  1. package/.github/workflows/release.yml +69 -1
  2. package/README.md +213 -337
  3. package/assets/03.bot.page.png +0 -0
  4. package/changelog/v2.3.4.md +20 -0
  5. package/changelog/v2.3.9.md +22 -0
  6. package/compat-single-account.md +32 -2
  7. package/index.test.ts +34 -0
  8. package/index.ts +15 -7
  9. package/package.json +8 -7
  10. package/src/agent/api-client.upload.test.ts +1 -2
  11. package/src/agent/handler.ts +82 -9
  12. package/src/agent/index.ts +1 -1
  13. package/src/app/account-runtime.ts +245 -0
  14. package/src/app/bootstrap.ts +29 -0
  15. package/src/app/index.ts +31 -0
  16. package/src/capability/agent/delivery-service.ts +79 -0
  17. package/src/capability/agent/fallback-policy.ts +13 -0
  18. package/src/capability/agent/index.ts +3 -0
  19. package/src/capability/agent/ingress-service.ts +38 -0
  20. package/src/capability/bot/dispatch-config.ts +47 -0
  21. package/src/capability/bot/fallback-delivery.ts +178 -0
  22. package/src/capability/bot/index.ts +1 -0
  23. package/src/capability/bot/local-path-delivery.ts +215 -0
  24. package/src/capability/bot/service.ts +56 -0
  25. package/src/capability/bot/stream-delivery.ts +379 -0
  26. package/src/capability/bot/stream-finalizer.ts +120 -0
  27. package/src/capability/bot/stream-orchestrator.ts +352 -0
  28. package/src/capability/bot/types.ts +8 -0
  29. package/src/capability/index.ts +2 -0
  30. package/src/channel.lifecycle.test.ts +9 -6
  31. package/src/channel.meta.test.ts +12 -0
  32. package/src/channel.ts +48 -21
  33. package/src/config/accounts.ts +223 -283
  34. package/src/config/derived-paths.test.ts +111 -0
  35. package/src/config/derived-paths.ts +41 -0
  36. package/src/config/index.ts +10 -12
  37. package/src/config/runtime-config.ts +46 -0
  38. package/src/config/schema.ts +59 -102
  39. package/src/domain/models.ts +7 -0
  40. package/src/domain/policies.ts +36 -0
  41. package/src/dynamic-agent.ts +6 -0
  42. package/src/gateway-monitor.ts +43 -93
  43. package/src/http.ts +23 -2
  44. package/src/monitor/limits.ts +7 -0
  45. package/src/monitor/state.ts +28 -508
  46. package/src/monitor.active.test.ts +3 -3
  47. package/src/monitor.integration.test.ts +0 -1
  48. package/src/monitor.ts +64 -2603
  49. package/src/monitor.webhook.test.ts +127 -42
  50. package/src/observability/audit-log.ts +48 -0
  51. package/src/observability/legacy-operational-event-store.ts +36 -0
  52. package/src/observability/raw-envelope-log.ts +28 -0
  53. package/src/observability/status-registry.ts +13 -0
  54. package/src/observability/transport-session-view.ts +14 -0
  55. package/src/onboarding.test.ts +219 -0
  56. package/src/onboarding.ts +88 -71
  57. package/src/outbound.test.ts +5 -5
  58. package/src/outbound.ts +18 -66
  59. package/src/runtime/dispatcher.ts +52 -0
  60. package/src/runtime/index.ts +4 -0
  61. package/src/runtime/outbound-intent.ts +4 -0
  62. package/src/runtime/reply-orchestrator.test.ts +38 -0
  63. package/src/runtime/reply-orchestrator.ts +55 -0
  64. package/src/runtime/routing-bridge.ts +19 -0
  65. package/src/runtime/session-manager.ts +76 -0
  66. package/src/runtime.ts +7 -14
  67. package/src/shared/command-auth.ts +1 -17
  68. package/src/shared/media-service.ts +36 -0
  69. package/src/shared/media-types.ts +5 -0
  70. package/src/store/active-reply-store.ts +42 -0
  71. package/src/store/interfaces.ts +11 -0
  72. package/src/store/memory-store.ts +43 -0
  73. package/src/store/stream-batch-store.ts +350 -0
  74. package/src/target.ts +28 -0
  75. package/src/transport/agent-api/client.ts +44 -0
  76. package/src/transport/agent-api/core.ts +367 -0
  77. package/src/transport/agent-api/delivery.ts +41 -0
  78. package/src/transport/agent-api/media-upload.ts +11 -0
  79. package/src/transport/agent-api/reply.ts +39 -0
  80. package/src/transport/agent-callback/http-handler.ts +47 -0
  81. package/src/transport/agent-callback/inbound.ts +5 -0
  82. package/src/transport/agent-callback/reply.ts +13 -0
  83. package/src/transport/agent-callback/request-handler.ts +244 -0
  84. package/src/transport/agent-callback/session.ts +23 -0
  85. package/src/transport/bot-webhook/active-reply.ts +36 -0
  86. package/src/transport/bot-webhook/http-handler.ts +48 -0
  87. package/src/transport/bot-webhook/inbound-normalizer.ts +371 -0
  88. package/src/transport/bot-webhook/inbound.ts +5 -0
  89. package/src/transport/bot-webhook/message-shape.ts +89 -0
  90. package/src/transport/bot-webhook/protocol.ts +148 -0
  91. package/src/transport/bot-webhook/reply.ts +15 -0
  92. package/src/transport/bot-webhook/request-handler.ts +394 -0
  93. package/src/transport/bot-webhook/session.ts +23 -0
  94. package/src/transport/bot-ws/inbound.ts +109 -0
  95. package/src/transport/bot-ws/reply.ts +48 -0
  96. package/src/transport/bot-ws/sdk-adapter.ts +180 -0
  97. package/src/transport/bot-ws/session.ts +28 -0
  98. package/src/transport/http/common.ts +109 -0
  99. package/src/transport/http/registry.ts +92 -0
  100. package/src/transport/http/request-handler.ts +84 -0
  101. package/src/transport/index.ts +14 -0
  102. package/src/types/account.ts +56 -91
  103. package/src/types/config.ts +59 -112
  104. package/src/types/constants.ts +20 -35
  105. package/src/types/events.ts +21 -0
  106. package/src/types/index.ts +14 -38
  107. package/src/types/legacy-stream.ts +50 -0
  108. package/src/types/runtime-context.ts +28 -0
  109. package/src/types/runtime.ts +161 -0
  110. package/src/agent/api-client.ts +0 -383
  111. package/src/monitor/types.ts +0 -136
@@ -0,0 +1,29 @@
1
+ import type { ChannelGatewayContext } from "openclaw/plugin-sdk";
2
+
3
+ import { resolveWecomRuntimeAccount } from "../config/runtime-config.js";
4
+ import type { ResolvedWecomAccount } from "../types/index.js";
5
+ import { WecomAccountRuntime } from "./account-runtime.js";
6
+ import { getWecomRuntime } from "./index.js";
7
+
8
+ export function createAccountRuntime(ctx: ChannelGatewayContext<ResolvedWecomAccount>): WecomAccountRuntime {
9
+ const resolved = resolveWecomRuntimeAccount({
10
+ cfg: ctx.cfg,
11
+ accountId: ctx.accountId,
12
+ });
13
+ return new WecomAccountRuntime(
14
+ getWecomRuntime(),
15
+ ctx.cfg,
16
+ resolved,
17
+ {
18
+ info: (message) => ctx.log?.info(message),
19
+ warn: (message) => ctx.log?.warn(message),
20
+ error: (message) => ctx.log?.error(message),
21
+ },
22
+ (snapshot) => {
23
+ ctx.setStatus({
24
+ accountId: ctx.accountId,
25
+ ...snapshot,
26
+ });
27
+ },
28
+ );
29
+ }
@@ -0,0 +1,31 @@
1
+ import type { PluginRuntime } from "openclaw/plugin-sdk";
2
+
3
+ import { WecomAccountRuntime } from "./account-runtime.js";
4
+
5
+ let runtime: PluginRuntime | null = null;
6
+ const runtimes = new Map<string, WecomAccountRuntime>();
7
+
8
+ export function setWecomRuntime(next: PluginRuntime): void {
9
+ runtime = next;
10
+ }
11
+
12
+ export function getWecomRuntime(): PluginRuntime {
13
+ if (!runtime) {
14
+ throw new Error("WeCom runtime not initialized");
15
+ }
16
+ return runtime;
17
+ }
18
+
19
+ export function registerAccountRuntime(accountRuntime: WecomAccountRuntime): void {
20
+ runtimes.set(accountRuntime.account.accountId, accountRuntime);
21
+ console.log(`[wecom-runtime] register account=${accountRuntime.account.accountId}`);
22
+ }
23
+
24
+ export function getAccountRuntimeSnapshot(accountId: string) {
25
+ return runtimes.get(accountId)?.buildRuntimeStatus();
26
+ }
27
+
28
+ export function unregisterAccountRuntime(accountId: string): void {
29
+ runtimes.delete(accountId);
30
+ console.log(`[wecom-runtime] unregister account=${accountId}`);
31
+ }
@@ -0,0 +1,79 @@
1
+ import type { ResolvedAgentAccount } from "../../types/index.js";
2
+ import { resolveScopedWecomTarget } from "../../target.js";
3
+ import { deliverAgentApiMedia, deliverAgentApiText } from "../../transport/agent-api/delivery.js";
4
+ import { canUseAgentApiDelivery } from "./fallback-policy.js";
5
+
6
+ export class WecomAgentDeliveryService {
7
+ constructor(private readonly agent: ResolvedAgentAccount) {}
8
+
9
+ assertAvailable(): void {
10
+ if (!canUseAgentApiDelivery(this.agent)) {
11
+ throw new Error(
12
+ `WeCom outbound requires channels.wecom.accounts.<accountId>.agent.agentId (or legacy channels.wecom.agent.agentId) for account=${this.agent.accountId}.`,
13
+ );
14
+ }
15
+ }
16
+
17
+ resolveTargetOrThrow(to: string | undefined) {
18
+ const scoped = resolveScopedWecomTarget(to, this.agent.accountId);
19
+ if (!scoped) {
20
+ console.error(`[wecom-agent-delivery] missing target account=${this.agent.accountId}`);
21
+ throw new Error("WeCom outbound requires a target (userid, partyid, tagid or chatid).");
22
+ }
23
+ if (scoped.accountId && scoped.accountId !== this.agent.accountId) {
24
+ console.error(
25
+ `[wecom-agent-delivery] account mismatch current=${this.agent.accountId} targetAccount=${scoped.accountId} raw=${String(to ?? "")}`,
26
+ );
27
+ throw new Error(
28
+ `WeCom outbound account mismatch: target belongs to account=${scoped.accountId}, current account=${this.agent.accountId}.`,
29
+ );
30
+ }
31
+ const target = scoped.target;
32
+ if (target.chatid) {
33
+ console.warn(
34
+ `[wecom-agent-delivery] blocked chat target account=${this.agent.accountId} chatId=${target.chatid}`,
35
+ );
36
+ throw new Error(
37
+ `企业微信(WeCom)Agent 主动发送不支持向群 chatId 发送(chatId=${target.chatid})。` +
38
+ `该路径在实际环境中经常失败(例如 86008:无权限访问该会话/会话由其他应用创建)。` +
39
+ `请改为发送给用户(userid / user:xxx),或由 Bot 模式在群内交付。`,
40
+ );
41
+ }
42
+ return target;
43
+ }
44
+
45
+ async sendText(params: { to: string | undefined; text: string }): Promise<void> {
46
+ this.assertAvailable();
47
+ const target = this.resolveTargetOrThrow(params.to);
48
+ console.log(
49
+ `[wecom-agent-delivery] sendText account=${this.agent.accountId} to=${String(params.to ?? "")} len=${params.text.length}`,
50
+ );
51
+ await deliverAgentApiText({
52
+ agent: this.agent,
53
+ target,
54
+ text: params.text,
55
+ });
56
+ }
57
+
58
+ async sendMedia(params: {
59
+ to: string | undefined;
60
+ text?: string;
61
+ buffer: Buffer;
62
+ filename: string;
63
+ contentType: string;
64
+ }): Promise<void> {
65
+ this.assertAvailable();
66
+ const target = this.resolveTargetOrThrow(params.to);
67
+ console.log(
68
+ `[wecom-agent-delivery] sendMedia account=${this.agent.accountId} to=${String(params.to ?? "")} filename=${params.filename} contentType=${params.contentType}`,
69
+ );
70
+ await deliverAgentApiMedia({
71
+ agent: this.agent,
72
+ target,
73
+ buffer: params.buffer,
74
+ filename: params.filename,
75
+ contentType: params.contentType,
76
+ text: params.text,
77
+ });
78
+ }
79
+ }
@@ -0,0 +1,13 @@
1
+ import type { ResolvedAgentAccount } from "../../types/index.js";
2
+
3
+ export function canUseAgentApiDelivery(agent: ResolvedAgentAccount | undefined): boolean {
4
+ return Boolean(agent?.apiConfigured && typeof agent.agentId === "number");
5
+ }
6
+
7
+ export function shouldFallbackToAgentApi(params: {
8
+ agent: ResolvedAgentAccount | undefined;
9
+ hasText?: boolean;
10
+ hasMedia?: boolean;
11
+ }): boolean {
12
+ return canUseAgentApiDelivery(params.agent) && Boolean(params.hasText || params.hasMedia);
13
+ }
@@ -0,0 +1,3 @@
1
+ export { WecomAgentIngressService } from "./ingress-service.js";
2
+ export { WecomAgentDeliveryService } from "./delivery-service.js";
3
+ export { canUseAgentApiDelivery, shouldFallbackToAgentApi } from "./fallback-policy.js";
@@ -0,0 +1,38 @@
1
+ import type { OpenClawConfig } from "openclaw/plugin-sdk";
2
+
3
+ import type { WecomRuntimeEnv } from "../../types/runtime-context.js";
4
+ import type { WecomAccountRuntime } from "../../app/account-runtime.js";
5
+ import { startAgentCallbackTransport } from "../../transport/agent-callback/http-handler.js";
6
+
7
+ export class WecomAgentIngressService {
8
+ private stopTransport?: () => void;
9
+
10
+ constructor(
11
+ private readonly runtime: WecomAccountRuntime,
12
+ private readonly cfg: OpenClawConfig,
13
+ private readonly runtimeEnv: WecomRuntimeEnv,
14
+ ) {}
15
+
16
+ start(): { transport: "agent-callback"; descriptors: string[] } | undefined {
17
+ const agent = this.runtime.account.agent;
18
+ if (!agent?.callbackConfigured) {
19
+ return undefined;
20
+ }
21
+ const callback = startAgentCallbackTransport({
22
+ account: agent,
23
+ cfg: this.cfg,
24
+ runtime: this.runtime,
25
+ runtimeEnv: this.runtimeEnv,
26
+ });
27
+ this.stopTransport = callback.stop;
28
+ return {
29
+ transport: "agent-callback",
30
+ descriptors: callback.paths,
31
+ };
32
+ }
33
+
34
+ stop(): void {
35
+ this.stopTransport?.();
36
+ this.stopTransport = undefined;
37
+ }
38
+ }
@@ -0,0 +1,47 @@
1
+ import type { OpenClawConfig } from "openclaw/plugin-sdk";
2
+
3
+ export function buildWecomBotDispatchConfig(config: OpenClawConfig): OpenClawConfig {
4
+ const baseAgents = (config as any)?.agents ?? {};
5
+ const baseAgentDefaults = (baseAgents as any)?.defaults ?? {};
6
+ const baseBlockChunk = (baseAgentDefaults as any)?.blockStreamingChunk ?? {};
7
+ const baseBlockCoalesce = (baseAgentDefaults as any)?.blockStreamingCoalesce ?? {};
8
+ const baseTools = (config as any)?.tools ?? {};
9
+ const baseSandbox = (baseTools as any)?.sandbox ?? {};
10
+ const baseSandboxTools = (baseSandbox as any)?.tools ?? {};
11
+ const existingTopLevelDeny = Array.isArray((baseTools as any).deny) ? ((baseTools as any).deny as string[]) : [];
12
+ const existingSandboxDeny = Array.isArray((baseSandboxTools as any).deny) ? ((baseSandboxTools as any).deny as string[]) : [];
13
+ const topLevelDeny = Array.from(new Set([...existingTopLevelDeny, "message"]));
14
+ const sandboxDeny = Array.from(new Set([...existingSandboxDeny, "message"]));
15
+ return {
16
+ ...(config as any),
17
+ agents: {
18
+ ...baseAgents,
19
+ defaults: {
20
+ ...baseAgentDefaults,
21
+ blockStreamingChunk: {
22
+ ...baseBlockChunk,
23
+ minChars: baseBlockChunk.minChars ?? 120,
24
+ maxChars: baseBlockChunk.maxChars ?? 360,
25
+ breakPreference: baseBlockChunk.breakPreference ?? "sentence",
26
+ },
27
+ blockStreamingCoalesce: {
28
+ ...baseBlockCoalesce,
29
+ minChars: baseBlockCoalesce.minChars ?? 120,
30
+ maxChars: baseBlockCoalesce.maxChars ?? 360,
31
+ idleMs: baseBlockCoalesce.idleMs ?? 250,
32
+ },
33
+ },
34
+ },
35
+ tools: {
36
+ ...baseTools,
37
+ deny: topLevelDeny,
38
+ sandbox: {
39
+ ...baseSandbox,
40
+ tools: {
41
+ ...baseSandboxTools,
42
+ deny: sandboxDeny,
43
+ },
44
+ },
45
+ },
46
+ } as OpenClawConfig;
47
+ }
@@ -0,0 +1,178 @@
1
+ import type { OpenClawConfig, PluginRuntime } from "openclaw/plugin-sdk";
2
+
3
+ import { resolveWecomAccount } from "../../config/index.js";
4
+ import { wecomFetch } from "../../http.js";
5
+ import { LIMITS } from "../../monitor/state.js";
6
+ import type { StreamState } from "../../types/legacy-stream.js";
7
+ import type { ResolvedAgentAccount } from "../../types/index.js";
8
+ import { sendMedia as sendAgentMedia, sendText as sendAgentText, uploadMedia } from "../../transport/agent-api/core.js";
9
+ import { buildStreamReplyFromState } from "../../transport/bot-webhook/protocol.js";
10
+ import { useActiveReplyOnce } from "../../transport/bot-webhook/active-reply.js";
11
+ import { guessContentTypeFromPath } from "../../transport/bot-webhook/inbound-normalizer.js";
12
+
13
+ const STREAM_MAX_DM_BYTES = 200_000;
14
+
15
+ export function appendDmContent(state: StreamState, text: string): void {
16
+ const next = state.dmContent ? `${state.dmContent}\n\n${text}`.trim() : text.trim();
17
+ const buf = Buffer.from(next, "utf8");
18
+ state.dmContent = buf.length <= STREAM_MAX_DM_BYTES ? next : buf.subarray(buf.length - STREAM_MAX_DM_BYTES).toString("utf8");
19
+ }
20
+
21
+ export function resolveAgentAccountOrUndefined(cfg: OpenClawConfig, accountId: string): ResolvedAgentAccount | undefined {
22
+ const agent = resolveWecomAccount({ cfg, accountId }).agent;
23
+ return agent?.configured ? agent : undefined;
24
+ }
25
+
26
+ export function buildFallbackPrompt(params: {
27
+ kind: "media" | "timeout" | "error";
28
+ agentConfigured: boolean;
29
+ userId?: string;
30
+ filename?: string;
31
+ chatType?: "group" | "direct";
32
+ }): string {
33
+ const who = params.userId ? `(${params.userId})` : "";
34
+ const scope = params.chatType === "group" ? "群聊" : params.chatType === "direct" ? "私聊" : "会话";
35
+ if (!params.agentConfigured) {
36
+ return `${scope}中需要通过应用私信发送${params.filename ? `(${params.filename})` : ""},但管理员尚未配置企业微信自建应用(Agent)通道。请联系管理员配置后再试。${who}`.trim();
37
+ }
38
+ if (!params.userId) {
39
+ return `${scope}中需要通过应用私信兜底发送${params.filename ? `(${params.filename})` : ""},但本次回调未能识别触发者 userid(请检查企微回调字段 from.userid / fromuserid)。请联系管理员排查配置。`.trim();
40
+ }
41
+ if (params.kind === "media") {
42
+ return `已生成文件${params.filename ? `(${params.filename})` : ""},将通过应用私信发送给你。${who}`.trim();
43
+ }
44
+ if (params.kind === "timeout") {
45
+ return `内容较长,为避免超时,后续内容将通过应用私信发送给你。${who}`.trim();
46
+ }
47
+ return `交付出现异常,已尝试通过应用私信发送给你。${who}`.trim();
48
+ }
49
+
50
+ export async function sendBotFallbackPromptNow(params: { streamId: string; text: string }): Promise<void> {
51
+ await useActiveReplyOnce(params.streamId, async ({ responseUrl, proxyUrl }) => {
52
+ const payload = {
53
+ msgtype: "stream",
54
+ stream: {
55
+ id: params.streamId,
56
+ finish: true,
57
+ content: params.text.trim() || "1",
58
+ },
59
+ };
60
+ const res = await wecomFetch(
61
+ responseUrl,
62
+ {
63
+ method: "POST",
64
+ headers: { "Content-Type": "application/json" },
65
+ body: JSON.stringify(payload),
66
+ },
67
+ { proxyUrl, timeoutMs: LIMITS.REQUEST_TIMEOUT_MS },
68
+ );
69
+ if (!res.ok) {
70
+ throw new Error(`fallback prompt push failed: ${res.status}`);
71
+ }
72
+ });
73
+ }
74
+
75
+ export async function pushFinalStreamReplyNow(params: { streamId: string; state: StreamState }): Promise<void> {
76
+ const finalReply = buildStreamReplyFromState(params.state) as unknown as Record<string, unknown>;
77
+ await useActiveReplyOnce(params.streamId, async ({ responseUrl, proxyUrl }) => {
78
+ const res = await wecomFetch(
79
+ responseUrl,
80
+ {
81
+ method: "POST",
82
+ headers: { "Content-Type": "application/json" },
83
+ body: JSON.stringify(finalReply),
84
+ },
85
+ { proxyUrl, timeoutMs: LIMITS.REQUEST_TIMEOUT_MS },
86
+ );
87
+ if (!res.ok) {
88
+ throw new Error(`final stream push failed: ${res.status}`);
89
+ }
90
+ });
91
+ }
92
+
93
+ export async function sendAgentDmText(params: {
94
+ agent: ResolvedAgentAccount;
95
+ userId: string;
96
+ text: string;
97
+ core: PluginRuntime;
98
+ }): Promise<void> {
99
+ const chunks = params.core.channel.text.chunkText(params.text, 20480);
100
+ for (const chunk of chunks) {
101
+ const trimmed = chunk.trim();
102
+ if (!trimmed) continue;
103
+ await sendAgentText({ agent: params.agent, toUser: params.userId, text: trimmed });
104
+ }
105
+ }
106
+
107
+ export async function sendAgentDmMedia(params: {
108
+ agent: ResolvedAgentAccount;
109
+ userId: string;
110
+ mediaUrlOrPath: string;
111
+ contentType?: string;
112
+ filename: string;
113
+ }): Promise<void> {
114
+ let buffer: Buffer;
115
+ let inferredContentType = params.contentType;
116
+ const looksLikeUrl = /^https?:\/\//i.test(params.mediaUrlOrPath);
117
+ if (looksLikeUrl) {
118
+ const res = await fetch(params.mediaUrlOrPath, { signal: AbortSignal.timeout(30_000) });
119
+ if (!res.ok) throw new Error(`media download failed: ${res.status}`);
120
+ buffer = Buffer.from(await res.arrayBuffer());
121
+ inferredContentType = inferredContentType || res.headers.get("content-type") || "application/octet-stream";
122
+ } else {
123
+ const fs = await import("node:fs/promises");
124
+ buffer = await fs.readFile(params.mediaUrlOrPath);
125
+ }
126
+
127
+ let mediaType: "image" | "voice" | "video" | "file" = "file";
128
+ const ct = (inferredContentType || "").toLowerCase();
129
+ if (ct.startsWith("image/")) mediaType = "image";
130
+ else if (ct.startsWith("audio/")) mediaType = "voice";
131
+ else if (ct.startsWith("video/")) mediaType = "video";
132
+
133
+ const mediaId = await uploadMedia({
134
+ agent: params.agent,
135
+ type: mediaType,
136
+ buffer,
137
+ filename: params.filename,
138
+ });
139
+ await sendAgentMedia({
140
+ agent: params.agent,
141
+ toUser: params.userId,
142
+ mediaId,
143
+ mediaType,
144
+ });
145
+ }
146
+
147
+ export function extractLocalImagePathsFromText(params: { text: string; mustAlsoAppearIn: string }): string[] {
148
+ const text = params.text;
149
+ const mustAlsoAppearIn = params.mustAlsoAppearIn;
150
+ if (!text.trim()) return [];
151
+ const exts = "(png|jpg|jpeg|gif|webp|bmp)";
152
+ const re = new RegExp(String.raw`(\/(?:Users|tmp|root|home)\/[^\s"'<>]+?\.${exts})`, "gi");
153
+ const found = new Set<string>();
154
+ let m: RegExpExecArray | null;
155
+ while ((m = re.exec(text))) {
156
+ const p = m[1];
157
+ if (!p) continue;
158
+ if (!mustAlsoAppearIn.includes(p)) continue;
159
+ found.add(p);
160
+ }
161
+ return Array.from(found);
162
+ }
163
+
164
+ export function extractLocalFilePathsFromText(text: string): string[] {
165
+ if (!text.trim()) return [];
166
+ const re = /\/(?:Users|tmp|root|home)\/[^\s"'<>]+/g;
167
+ const found = new Set<string>();
168
+ let m: RegExpExecArray | null;
169
+ while ((m = re.exec(text))) {
170
+ const p = m[0]?.trim();
171
+ if (p) found.add(p);
172
+ }
173
+ return Array.from(found);
174
+ }
175
+
176
+ export function guessLocalPathContentType(filePath: string): string | undefined {
177
+ return guessContentTypeFromPath(filePath);
178
+ }
@@ -0,0 +1 @@
1
+ export { WecomBotCapabilityService } from "./service.js";
@@ -0,0 +1,215 @@
1
+ import crypto from "node:crypto";
2
+
3
+ import { wecomFetch } from "../../http.js";
4
+ import { LIMITS, type StreamStore } from "../../monitor/state.js";
5
+ import { getActiveReplyUrl, useActiveReplyOnce } from "../../transport/bot-webhook/active-reply.js";
6
+ import type { WecomWebhookTarget } from "../../types/runtime-context.js";
7
+ import { buildStreamReplyFromState } from "../../transport/bot-webhook/protocol.js";
8
+ import {
9
+ buildFallbackPrompt,
10
+ extractLocalFilePathsFromText,
11
+ guessLocalPathContentType,
12
+ resolveAgentAccountOrUndefined,
13
+ sendAgentDmMedia,
14
+ sendBotFallbackPromptNow,
15
+ } from "./fallback-delivery.js";
16
+ import type { BotRuntimeLogger } from "./types.js";
17
+
18
+ export async function handleDirectLocalPathIntent(params: {
19
+ streamStore: StreamStore;
20
+ target: WecomWebhookTarget;
21
+ streamId: string;
22
+ rawBody: string;
23
+ userId: string;
24
+ chatType: "group" | "direct";
25
+ logVerbose: BotRuntimeLogger;
26
+ looksLikeSendLocalFileIntent: (rawBody: string) => boolean;
27
+ }): Promise<boolean> {
28
+ const { streamStore, target, streamId, rawBody, userId, chatType, logVerbose, looksLikeSendLocalFileIntent } = params;
29
+ const directLocalPaths = extractLocalFilePathsFromText(rawBody);
30
+ if (directLocalPaths.length) {
31
+ logVerbose(
32
+ target,
33
+ `local-path: 检测到用户消息包含本机路径 count=${directLocalPaths.length} intent=${looksLikeSendLocalFileIntent(rawBody)}`,
34
+ );
35
+ }
36
+ if (!directLocalPaths.length || !looksLikeSendLocalFileIntent(rawBody)) {
37
+ return false;
38
+ }
39
+
40
+ const fs = await import("node:fs/promises");
41
+ const pathModule = await import("node:path");
42
+ const imageExts = new Set(["png", "jpg", "jpeg", "gif", "webp", "bmp"]);
43
+
44
+ const imagePaths: string[] = [];
45
+ const otherPaths: string[] = [];
46
+ for (const p of directLocalPaths) {
47
+ const ext = pathModule.extname(p).slice(1).toLowerCase();
48
+ if (imageExts.has(ext)) imagePaths.push(p);
49
+ else otherPaths.push(p);
50
+ }
51
+
52
+ if (imagePaths.length > 0 && otherPaths.length === 0) {
53
+ const loaded: Array<{ base64: string; md5: string; path: string }> = [];
54
+ for (const p of imagePaths) {
55
+ try {
56
+ const buf = await fs.readFile(p);
57
+ const base64 = buf.toString("base64");
58
+ const md5 = crypto.createHash("md5").update(buf).digest("hex");
59
+ loaded.push({ base64, md5, path: p });
60
+ } catch (err) {
61
+ target.runtime.error?.(`local-path: 读取图片失败 path=${p}: ${String(err)}`);
62
+ }
63
+ }
64
+
65
+ if (loaded.length > 0) {
66
+ streamStore.updateStream(streamId, (s) => {
67
+ s.images = loaded.map(({ base64, md5 }) => ({ base64, md5 }));
68
+ s.content = loaded.length === 1 ? `已发送图片(${pathModule.basename(loaded[0]!.path)})` : `已发送 ${loaded.length} 张图片`;
69
+ s.finished = true;
70
+ });
71
+
72
+ const responseUrl = getActiveReplyUrl(streamId);
73
+ if (responseUrl) {
74
+ try {
75
+ const finalReply = buildStreamReplyFromState(streamStore.getStream(streamId)!) as unknown as Record<string, unknown>;
76
+ await useActiveReplyOnce(streamId, async ({ responseUrl, proxyUrl }) => {
77
+ const res = await wecomFetch(
78
+ responseUrl,
79
+ {
80
+ method: "POST",
81
+ headers: { "Content-Type": "application/json" },
82
+ body: JSON.stringify(finalReply),
83
+ },
84
+ { proxyUrl, timeoutMs: LIMITS.REQUEST_TIMEOUT_MS },
85
+ );
86
+ if (!res.ok) throw new Error(`local-path image push failed: ${res.status}`);
87
+ });
88
+ logVerbose(target, `local-path: 已通过 Bot response_url 推送图片 frames=final images=${loaded.length}`);
89
+ } catch (err) {
90
+ target.runtime.error?.(`local-path: Bot 主动推送图片失败(将依赖 stream_refresh 拉取): ${String(err)}`);
91
+ }
92
+ } else {
93
+ logVerbose(target, "local-path: 无 response_url,等待 stream_refresh 拉取最终图片");
94
+ }
95
+ streamStore.onStreamFinished(streamId);
96
+ return true;
97
+ }
98
+
99
+ const agentCfg = resolveAgentAccountOrUndefined(target.config, target.account.accountId);
100
+ const agentOk = Boolean(agentCfg);
101
+ const fallbackName = imagePaths.length === 1 ? (imagePaths[0]!.split("/").pop() || "image") : `${imagePaths.length} 张图片`;
102
+ const prompt = buildFallbackPrompt({
103
+ kind: "media",
104
+ agentConfigured: agentOk,
105
+ userId,
106
+ filename: fallbackName,
107
+ chatType,
108
+ });
109
+
110
+ streamStore.updateStream(streamId, (s) => {
111
+ s.fallbackMode = "error";
112
+ s.finished = true;
113
+ s.content = prompt;
114
+ s.fallbackPromptSentAt = s.fallbackPromptSentAt ?? Date.now();
115
+ });
116
+
117
+ try {
118
+ await sendBotFallbackPromptNow({ streamId, text: prompt });
119
+ logVerbose(target, "local-path: 图片读取失败后已推送兜底提示");
120
+ } catch (err) {
121
+ target.runtime.error?.(`local-path: 图片读取失败后的兜底提示推送失败: ${String(err)}`);
122
+ }
123
+
124
+ if (agentCfg && userId && userId !== "unknown") {
125
+ for (const p of imagePaths) {
126
+ const guessedType = guessLocalPathContentType(p);
127
+ try {
128
+ await sendAgentDmMedia({
129
+ agent: agentCfg,
130
+ userId,
131
+ mediaUrlOrPath: p,
132
+ contentType: guessedType,
133
+ filename: p.split("/").pop() || "image",
134
+ });
135
+ streamStore.updateStream(streamId, (s) => {
136
+ s.agentMediaKeys = Array.from(new Set([...(s.agentMediaKeys ?? []), p]));
137
+ });
138
+ logVerbose(
139
+ target,
140
+ `local-path: 图片已通过 Agent 私信发送 user=${userId} path=${p} contentType=${guessedType ?? "unknown"}`,
141
+ );
142
+ } catch (err) {
143
+ target.runtime.error?.(`local-path: 图片 Agent 私信兜底失败 path=${p}: ${String(err)}`);
144
+ }
145
+ }
146
+ }
147
+ streamStore.onStreamFinished(streamId);
148
+ return true;
149
+ }
150
+
151
+ if (otherPaths.length > 0) {
152
+ const agentCfg = resolveAgentAccountOrUndefined(target.config, target.account.accountId);
153
+ const agentOk = Boolean(agentCfg);
154
+ const filename = otherPaths.length === 1 ? otherPaths[0]!.split("/").pop()! : `${otherPaths.length} 个文件`;
155
+ const prompt = buildFallbackPrompt({
156
+ kind: "media",
157
+ agentConfigured: agentOk,
158
+ userId,
159
+ filename,
160
+ chatType,
161
+ });
162
+
163
+ streamStore.updateStream(streamId, (s) => {
164
+ s.fallbackMode = "media";
165
+ s.finished = true;
166
+ s.content = prompt;
167
+ s.fallbackPromptSentAt = s.fallbackPromptSentAt ?? Date.now();
168
+ });
169
+
170
+ try {
171
+ await sendBotFallbackPromptNow({ streamId, text: prompt });
172
+ logVerbose(target, "local-path: 文件兜底提示已推送");
173
+ } catch (err) {
174
+ target.runtime.error?.(`local-path: 文件兜底提示推送失败: ${String(err)}`);
175
+ }
176
+
177
+ if (!agentCfg) {
178
+ streamStore.onStreamFinished(streamId);
179
+ return true;
180
+ }
181
+ if (!userId || userId === "unknown") {
182
+ target.runtime.error?.("local-path: 无法识别触发者 userId,无法 Agent 私信发送文件");
183
+ streamStore.onStreamFinished(streamId);
184
+ return true;
185
+ }
186
+
187
+ for (const p of otherPaths) {
188
+ const alreadySent = streamStore.getStream(streamId)?.agentMediaKeys?.includes(p);
189
+ if (alreadySent) continue;
190
+ const guessedType = guessLocalPathContentType(p);
191
+ try {
192
+ await sendAgentDmMedia({
193
+ agent: agentCfg,
194
+ userId,
195
+ mediaUrlOrPath: p,
196
+ contentType: guessedType,
197
+ filename: p.split("/").pop() || "file",
198
+ });
199
+ streamStore.updateStream(streamId, (s) => {
200
+ s.agentMediaKeys = Array.from(new Set([...(s.agentMediaKeys ?? []), p]));
201
+ });
202
+ logVerbose(
203
+ target,
204
+ `local-path: 文件已通过 Agent 私信发送 user=${userId} path=${p} contentType=${guessedType ?? "unknown"}`,
205
+ );
206
+ } catch (err) {
207
+ target.runtime.error?.(`local-path: Agent 私信发送文件失败 path=${p}: ${String(err)}`);
208
+ }
209
+ }
210
+ streamStore.onStreamFinished(streamId);
211
+ return true;
212
+ }
213
+
214
+ return false;
215
+ }