@yanhaidao/wecom 2.4.160 → 2.5.110

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 (313) hide show
  1. package/dist/index.js +68 -0
  2. package/dist/src/accounts.js +20 -0
  3. package/dist/src/agent/handler.js +895 -0
  4. package/dist/src/agent/index.js +5 -0
  5. package/dist/src/app/account-runtime.js +216 -0
  6. package/dist/src/app/bootstrap.js +19 -0
  7. package/dist/src/app/index.js +118 -0
  8. package/dist/src/capability/agent/delivery-service.js +63 -0
  9. package/dist/src/capability/agent/fallback-policy.js +6 -0
  10. package/dist/src/capability/agent/ingress-service.js +33 -0
  11. package/dist/src/capability/agent/upstream-delivery-service.js +71 -0
  12. package/dist/src/capability/bot/dispatch-config.js +45 -0
  13. package/dist/src/capability/bot/fallback-delivery.js +147 -0
  14. package/dist/src/capability/bot/local-path-delivery.js +178 -0
  15. package/dist/src/capability/bot/sandbox-media.js +138 -0
  16. package/dist/src/capability/bot/service.js +49 -0
  17. package/dist/src/capability/bot/stream-delivery.js +321 -0
  18. package/dist/src/capability/bot/stream-finalizer.js +81 -0
  19. package/dist/src/capability/bot/stream-orchestrator.js +318 -0
  20. package/dist/src/capability/bot/types.js +1 -0
  21. package/{src/capability/calendar/client.ts → dist/src/capability/calendar/client.js} +118 -241
  22. package/{src/capability/calendar/schema.ts → dist/src/capability/calendar/schema.js} +0 -38
  23. package/dist/src/capability/calendar/tool.js +365 -0
  24. package/dist/src/capability/calendar/types.js +12 -0
  25. package/{src/capability/doc/client.ts → dist/src/capability/doc/client.js} +370 -605
  26. package/{src/capability/doc/schema.ts → dist/src/capability/doc/schema.js} +345 -394
  27. package/dist/src/capability/doc/tool.js +1556 -0
  28. package/dist/src/capability/doc/types.js +113 -0
  29. package/dist/src/capability/mcp/index.js +3 -0
  30. package/dist/src/capability/mcp/schema.js +102 -0
  31. package/dist/src/capability/mcp/tool.js +146 -0
  32. package/dist/src/capability/mcp/transport.js +293 -0
  33. package/dist/src/channel.js +224 -0
  34. package/dist/src/config/accounts.js +236 -0
  35. package/dist/src/config/derived-paths.js +31 -0
  36. package/dist/src/config/index.js +7 -0
  37. package/dist/src/config/media.js +110 -0
  38. package/dist/src/config/network.js +32 -0
  39. package/dist/src/config/routing.js +20 -0
  40. package/dist/src/config/runtime-config.js +25 -0
  41. package/dist/src/config/schema.js +4 -0
  42. package/{src/config-schema.ts → dist/src/config-schema.js} +1 -1
  43. package/dist/src/context-store.js +219 -0
  44. package/{src/crypto/aes.ts → dist/src/crypto/aes.js} +11 -28
  45. package/dist/src/crypto/index.js +9 -0
  46. package/{src/crypto/signature.ts → dist/src/crypto/signature.js} +3 -18
  47. package/{src/crypto/xml.ts → dist/src/crypto/xml.js} +3 -11
  48. package/dist/src/crypto.js +145 -0
  49. package/dist/src/domain/models.js +1 -0
  50. package/dist/src/domain/policies.js +32 -0
  51. package/{src/dynamic-agent.ts → dist/src/dynamic-agent.js} +36 -73
  52. package/dist/src/gateway-monitor.js +139 -0
  53. package/dist/src/http.js +114 -0
  54. package/{src/media.ts → dist/src/media.js} +21 -40
  55. package/dist/src/monitor/limits.js +7 -0
  56. package/dist/src/monitor/state.js +28 -0
  57. package/dist/src/monitor.js +84 -0
  58. package/dist/src/observability/audit-log.js +30 -0
  59. package/dist/src/observability/legacy-operational-event-store.js +22 -0
  60. package/dist/src/observability/raw-envelope-log.js +24 -0
  61. package/dist/src/observability/status-registry.js +9 -0
  62. package/dist/src/observability/transport-session-view.js +14 -0
  63. package/dist/src/onboarding.js +546 -0
  64. package/dist/src/outbound.js +557 -0
  65. package/dist/src/runtime/dispatcher.js +57 -0
  66. package/{src/runtime/index.ts → dist/src/runtime/index.js} +0 -1
  67. package/dist/src/runtime/outbound-intent.js +1 -0
  68. package/dist/src/runtime/reply-orchestrator.js +38 -0
  69. package/dist/src/runtime/routing-bridge.js +26 -0
  70. package/dist/src/runtime/session-manager.js +112 -0
  71. package/dist/src/runtime/source-registry.js +174 -0
  72. package/dist/src/runtime.js +1 -0
  73. package/dist/src/shared/command-auth.js +57 -0
  74. package/{src/shared/index.ts → dist/src/shared/index.js} +0 -1
  75. package/dist/src/shared/media-asset.js +65 -0
  76. package/dist/src/shared/media-service.js +59 -0
  77. package/dist/src/shared/media-types.js +1 -0
  78. package/{src/shared/xml-parser.ts → dist/src/shared/xml-parser.js} +72 -63
  79. package/dist/src/store/active-reply-store.js +41 -0
  80. package/dist/src/store/interfaces.js +1 -0
  81. package/dist/src/store/memory-store.js +33 -0
  82. package/dist/src/store/stream-batch-store.js +319 -0
  83. package/{src/target.ts → dist/src/target.js} +15 -48
  84. package/dist/src/transport/agent-api/client.js +168 -0
  85. package/dist/src/transport/agent-api/core.js +337 -0
  86. package/dist/src/transport/agent-api/delivery.js +28 -0
  87. package/dist/src/transport/agent-api/media-upload.js +4 -0
  88. package/dist/src/transport/agent-api/reply.js +24 -0
  89. package/dist/src/transport/agent-api/upstream-delivery.js +30 -0
  90. package/dist/src/transport/agent-api/upstream-media-upload.js +46 -0
  91. package/dist/src/transport/agent-api/upstream-reply.js +26 -0
  92. package/dist/src/transport/agent-callback/http-handler.js +30 -0
  93. package/dist/src/transport/agent-callback/inbound.js +4 -0
  94. package/dist/src/transport/agent-callback/reply.js +8 -0
  95. package/dist/src/transport/agent-callback/request-handler.js +189 -0
  96. package/dist/src/transport/agent-callback/session.js +15 -0
  97. package/dist/src/transport/bot-webhook/active-reply.js +27 -0
  98. package/dist/src/transport/bot-webhook/http-handler.js +31 -0
  99. package/dist/src/transport/bot-webhook/inbound-normalizer.js +496 -0
  100. package/dist/src/transport/bot-webhook/inbound.js +4 -0
  101. package/dist/src/transport/bot-webhook/message-shape.js +98 -0
  102. package/dist/src/transport/bot-webhook/protocol.js +124 -0
  103. package/dist/src/transport/bot-webhook/reply.js +9 -0
  104. package/dist/src/transport/bot-webhook/request-handler.js +285 -0
  105. package/dist/src/transport/bot-webhook/session.js +15 -0
  106. package/dist/src/transport/bot-ws/inbound.js +147 -0
  107. package/dist/src/transport/bot-ws/media.js +236 -0
  108. package/dist/src/transport/bot-ws/reply.js +310 -0
  109. package/dist/src/transport/bot-ws/sdk-adapter.js +257 -0
  110. package/dist/src/transport/bot-ws/session.js +15 -0
  111. package/dist/src/transport/http/common.js +78 -0
  112. package/dist/src/transport/http/registry.js +71 -0
  113. package/dist/src/transport/http/request-handler.js +51 -0
  114. package/{src/transport/index.ts → dist/src/transport/index.js} +2 -10
  115. package/dist/src/types/account.js +1 -0
  116. package/dist/src/types/config.js +1 -0
  117. package/dist/src/types/constants.js +28 -0
  118. package/dist/src/types/events.js +1 -0
  119. package/dist/src/types/index.js +1 -0
  120. package/dist/src/types/legacy-stream.js +1 -0
  121. package/dist/src/types/message.js +5 -0
  122. package/dist/src/types/runtime-context.js +1 -0
  123. package/dist/src/types/runtime.js +1 -0
  124. package/dist/src/types.js +1 -0
  125. package/dist/src/upstream/index.js +111 -0
  126. package/dist/src/wecom_msg_adapter/markdown_adapter.js +280 -0
  127. package/openclaw.plugin.json +15 -0
  128. package/package.json +18 -1
  129. package/.github/workflows/release.yml +0 -143
  130. package/GOVERNANCE.md +0 -26
  131. package/SKILLS_CAL.md +0 -895
  132. package/SKILLS_DOC.md +0 -2288
  133. package/UPSTREAM_CONFIG.md +0 -170
  134. package/UPSTREAM_PLAN.md +0 -175
  135. package/assets/01.bot-add.png +0 -0
  136. package/assets/01.bot-setp2.png +0 -0
  137. package/assets/01.image.jpg +0 -0
  138. package/assets/02.agent.add.png +0 -0
  139. package/assets/02.agent.api-set.png +0 -0
  140. package/assets/02.image.jpg +0 -0
  141. package/assets/03.agent.page.png +0 -0
  142. package/assets/03.bot.page.png +0 -0
  143. package/assets/link-me.jpg +0 -0
  144. package/assets/register.png +0 -0
  145. package/changelog/v2.2.28.md +0 -70
  146. package/changelog/v2.3.10.md +0 -17
  147. package/changelog/v2.3.11.md +0 -19
  148. package/changelog/v2.3.12.md +0 -25
  149. package/changelog/v2.3.13.md +0 -19
  150. package/changelog/v2.3.14.md +0 -48
  151. package/changelog/v2.3.15.md +0 -15
  152. package/changelog/v2.3.16.md +0 -11
  153. package/changelog/v2.3.18.md +0 -22
  154. package/changelog/v2.3.19.md +0 -73
  155. package/changelog/v2.3.2.md +0 -28
  156. package/changelog/v2.3.26.md +0 -21
  157. package/changelog/v2.3.27.md +0 -33
  158. package/changelog/v2.3.4.md +0 -20
  159. package/changelog/v2.3.9.md +0 -22
  160. package/changelog/v2.4.12.md +0 -37
  161. package/changelog/v2.4.16.md +0 -19
  162. package/compat-single-account.md +0 -148
  163. package/index.test.ts +0 -38
  164. package/scripts/test-proxy.ts +0 -70
  165. package/src/accounts.ts +0 -34
  166. package/src/agent/api-client.upload.test.ts +0 -109
  167. package/src/agent/handler.event-filter.test.ts +0 -100
  168. package/src/agent/handler.ts +0 -1105
  169. package/src/agent/index.ts +0 -12
  170. package/src/app/account-runtime.ts +0 -276
  171. package/src/app/bootstrap.ts +0 -29
  172. package/src/app/index.ts +0 -192
  173. package/src/capability/agent/delivery-service.ts +0 -87
  174. package/src/capability/agent/fallback-policy.ts +0 -13
  175. package/src/capability/agent/ingress-service.ts +0 -38
  176. package/src/capability/agent/upstream-delivery-service.ts +0 -96
  177. package/src/capability/bot/dispatch-config.ts +0 -47
  178. package/src/capability/bot/fallback-delivery.ts +0 -178
  179. package/src/capability/bot/local-path-delivery.ts +0 -215
  180. package/src/capability/bot/sandbox-media.test.ts +0 -221
  181. package/src/capability/bot/sandbox-media.ts +0 -176
  182. package/src/capability/bot/service.ts +0 -56
  183. package/src/capability/bot/stream-delivery.ts +0 -379
  184. package/src/capability/bot/stream-finalizer.ts +0 -120
  185. package/src/capability/bot/stream-orchestrator.ts +0 -371
  186. package/src/capability/bot/types.ts +0 -8
  187. package/src/capability/calendar/SKILLS_CHECKLIST.md +0 -251
  188. package/src/capability/calendar/tool.ts +0 -417
  189. package/src/capability/calendar/types.ts +0 -309
  190. package/src/capability/doc/tool.ts +0 -1629
  191. package/src/capability/doc/types.ts +0 -792
  192. package/src/capability/mcp/index.ts +0 -10
  193. package/src/capability/mcp/schema.ts +0 -107
  194. package/src/capability/mcp/tool.ts +0 -174
  195. package/src/capability/mcp/transport.ts +0 -394
  196. package/src/channel.config.test.ts +0 -147
  197. package/src/channel.lifecycle.test.ts +0 -255
  198. package/src/channel.meta.test.ts +0 -26
  199. package/src/channel.ts +0 -256
  200. package/src/config/accounts.resolve.test.ts +0 -75
  201. package/src/config/accounts.ts +0 -296
  202. package/src/config/derived-paths.test.ts +0 -111
  203. package/src/config/derived-paths.ts +0 -41
  204. package/src/config/index.ts +0 -26
  205. package/src/config/media.test.ts +0 -113
  206. package/src/config/media.ts +0 -139
  207. package/src/config/network.ts +0 -53
  208. package/src/config/routing.test.ts +0 -88
  209. package/src/config/routing.ts +0 -26
  210. package/src/config/runtime-config.ts +0 -46
  211. package/src/config/schema.ts +0 -90
  212. package/src/context-store.ts +0 -297
  213. package/src/crypto/index.ts +0 -24
  214. package/src/crypto.test.ts +0 -32
  215. package/src/crypto.ts +0 -176
  216. package/src/domain/models.ts +0 -7
  217. package/src/domain/policies.ts +0 -36
  218. package/src/dynamic-agent.account-scope.test.ts +0 -17
  219. package/src/gateway-monitor.ts +0 -181
  220. package/src/http.ts +0 -145
  221. package/src/media.test.ts +0 -82
  222. package/src/monitor/limits.ts +0 -7
  223. package/src/monitor/state.queue.test.ts +0 -185
  224. package/src/monitor/state.ts +0 -34
  225. package/src/monitor.active.test.ts +0 -245
  226. package/src/monitor.inbound-filter.test.ts +0 -63
  227. package/src/monitor.integration.test.ts +0 -208
  228. package/src/monitor.ts +0 -121
  229. package/src/monitor.webhook.test.ts +0 -774
  230. package/src/observability/audit-log.ts +0 -48
  231. package/src/observability/legacy-operational-event-store.ts +0 -36
  232. package/src/observability/raw-envelope-log.ts +0 -28
  233. package/src/observability/status-registry.ts +0 -13
  234. package/src/observability/transport-session-view.ts +0 -14
  235. package/src/onboarding.test.ts +0 -336
  236. package/src/onboarding.ts +0 -704
  237. package/src/outbound.test.ts +0 -1271
  238. package/src/outbound.ts +0 -746
  239. package/src/runtime/dispatcher.ts +0 -71
  240. package/src/runtime/outbound-intent.ts +0 -4
  241. package/src/runtime/reply-orchestrator.test.ts +0 -71
  242. package/src/runtime/reply-orchestrator.ts +0 -67
  243. package/src/runtime/routing-bridge.test.ts +0 -115
  244. package/src/runtime/routing-bridge.ts +0 -44
  245. package/src/runtime/session-manager.test.ts +0 -174
  246. package/src/runtime/session-manager.ts +0 -139
  247. package/src/runtime/source-registry.ts +0 -249
  248. package/src/runtime.ts +0 -14
  249. package/src/shared/command-auth.ts +0 -87
  250. package/src/shared/media-asset.ts +0 -78
  251. package/src/shared/media-service.test.ts +0 -111
  252. package/src/shared/media-service.ts +0 -84
  253. package/src/shared/media-types.ts +0 -5
  254. package/src/shared/xml-parser.test.ts +0 -50
  255. package/src/store/active-reply-store.ts +0 -42
  256. package/src/store/interfaces.ts +0 -11
  257. package/src/store/memory-store.ts +0 -43
  258. package/src/store/stream-batch-store.ts +0 -350
  259. package/src/transport/agent-api/client.ts +0 -277
  260. package/src/transport/agent-api/core.ts +0 -463
  261. package/src/transport/agent-api/delivery.ts +0 -41
  262. package/src/transport/agent-api/media-upload.ts +0 -11
  263. package/src/transport/agent-api/reply.ts +0 -39
  264. package/src/transport/agent-api/upstream-delivery.ts +0 -45
  265. package/src/transport/agent-api/upstream-media-upload.ts +0 -70
  266. package/src/transport/agent-api/upstream-reply.ts +0 -43
  267. package/src/transport/agent-callback/http-handler.ts +0 -47
  268. package/src/transport/agent-callback/inbound.ts +0 -5
  269. package/src/transport/agent-callback/reply.ts +0 -13
  270. package/src/transport/agent-callback/request-handler.ts +0 -244
  271. package/src/transport/agent-callback/session.ts +0 -23
  272. package/src/transport/bot-webhook/active-reply.ts +0 -39
  273. package/src/transport/bot-webhook/http-handler.ts +0 -48
  274. package/src/transport/bot-webhook/inbound-normalizer.test.ts +0 -433
  275. package/src/transport/bot-webhook/inbound-normalizer.ts +0 -558
  276. package/src/transport/bot-webhook/inbound.ts +0 -5
  277. package/src/transport/bot-webhook/message-shape.ts +0 -92
  278. package/src/transport/bot-webhook/protocol.ts +0 -148
  279. package/src/transport/bot-webhook/reply.ts +0 -15
  280. package/src/transport/bot-webhook/request-handler.ts +0 -394
  281. package/src/transport/bot-webhook/session.ts +0 -23
  282. package/src/transport/bot-ws/inbound.test.ts +0 -290
  283. package/src/transport/bot-ws/inbound.ts +0 -163
  284. package/src/transport/bot-ws/media.test.ts +0 -44
  285. package/src/transport/bot-ws/media.ts +0 -321
  286. package/src/transport/bot-ws/reply.test.ts +0 -450
  287. package/src/transport/bot-ws/reply.ts +0 -365
  288. package/src/transport/bot-ws/sdk-adapter.test.ts +0 -187
  289. package/src/transport/bot-ws/sdk-adapter.ts +0 -314
  290. package/src/transport/bot-ws/session.ts +0 -28
  291. package/src/transport/http/common.ts +0 -109
  292. package/src/transport/http/registry.ts +0 -92
  293. package/src/transport/http/request-handler.ts +0 -84
  294. package/src/types/account.ts +0 -70
  295. package/src/types/config.ts +0 -114
  296. package/src/types/constants.ts +0 -31
  297. package/src/types/events.ts +0 -21
  298. package/src/types/global.d.ts +0 -9
  299. package/src/types/index.ts +0 -17
  300. package/src/types/legacy-stream.ts +0 -50
  301. package/src/types/message.ts +0 -189
  302. package/src/types/runtime-context.ts +0 -28
  303. package/src/types/runtime.ts +0 -165
  304. package/src/types.ts +0 -41
  305. package/src/upstream/index.ts +0 -150
  306. package/src/upstream.test.ts +0 -84
  307. package/src/wecom_msg_adapter/markdown_adapter.ts +0 -331
  308. package/tsconfig.json +0 -22
  309. package/vitest.config.ts +0 -26
  310. /package/{src/capability/agent/index.ts → dist/src/capability/agent/index.js} +0 -0
  311. /package/{src/capability/bot/index.ts → dist/src/capability/bot/index.js} +0 -0
  312. /package/{src/capability/calendar/index.ts → dist/src/capability/calendar/index.js} +0 -0
  313. /package/{src/capability/index.ts → dist/src/capability/index.js} +0 -0
@@ -1,314 +0,0 @@
1
- import crypto from "node:crypto";
2
- import AiBot, {
3
- generateReqId,
4
- type BaseMessage,
5
- type EventMessage,
6
- type WsFrame,
7
- } from "@wecom/aibot-node-sdk";
8
- import type { WecomAccountRuntime } from "../../app/account-runtime.js";
9
- import { registerBotWsPushHandle, unregisterBotWsPushHandle } from "../../app/index.js";
10
- import { clearWecomMcpAccountCache } from "../../capability/mcp/index.js";
11
- import type { RuntimeLogSink } from "../../types/index.js";
12
- import { mapBotWsFrameToInboundEvent } from "./inbound.js";
13
- import { uploadAndSendBotWsMedia } from "./media.js";
14
- import { createBotWsReplyHandle } from "./reply.js";
15
- import { createBotWsSessionSnapshot } from "./session.js";
16
-
17
- export class BotWsSdkAdapter {
18
- private client?: AiBot.WSClient;
19
- private readonly ownerId: string;
20
-
21
- constructor(
22
- private readonly runtime: WecomAccountRuntime,
23
- private readonly log: RuntimeLogSink,
24
- ) {
25
- this.ownerId = `${this.runtime.account.accountId}:ws:${crypto.randomUUID().slice(0, 8)}`;
26
- }
27
-
28
- start(): void {
29
- const bot = this.runtime.account.bot;
30
- if (!bot?.wsConfigured || !bot.ws) {
31
- throw new Error(`WeCom bot account "${this.runtime.account.accountId}" missing WS config.`);
32
- }
33
- this.log.info?.(
34
- `[wecom-ws] start account=${this.runtime.account.accountId} botId=${bot.ws.botId} wsUrl=default heartbeat=default reconnectInterval=default`,
35
- );
36
- const client = new AiBot.WSClient({
37
- botId: bot.ws.botId,
38
- secret: bot.ws.secret,
39
- logger: {
40
- debug: (message, ...args) =>
41
- this.log.info?.(`[wecom-ws] ${message} ${args.join(" ")}`.trim()),
42
- info: (message, ...args) =>
43
- this.log.info?.(`[wecom-ws] ${message} ${args.join(" ")}`.trim()),
44
- warn: (message, ...args) =>
45
- this.log.warn?.(`[wecom-ws] ${message} ${args.join(" ")}`.trim()),
46
- error: (message, ...args) =>
47
- this.log.error?.(`[wecom-ws] ${message} ${args.join(" ")}`.trim()),
48
- },
49
- });
50
- this.client = client;
51
- registerBotWsPushHandle(this.runtime.account.accountId, {
52
- isConnected: () => client.isConnected,
53
- replyCommand: async ({ cmd, body, headers }) => {
54
- const replyHeaders = {
55
- ...(headers ?? {}),
56
- req_id: headers?.req_id ?? generateReqId("wecom_ws"),
57
- };
58
- const result = await client.reply({ headers: replyHeaders }, body ?? {}, cmd);
59
- this.runtime.touchTransportSession("bot-ws", {
60
- ownerId: this.ownerId,
61
- running: true,
62
- connected: client.isConnected,
63
- authenticated: client.isConnected,
64
- lastOutboundAt: Date.now(),
65
- lastError: undefined,
66
- });
67
- return result as unknown as Record<string, unknown>;
68
- },
69
- sendMarkdown: async (chatId, content) => {
70
- await client.sendMessage(chatId, {
71
- msgtype: "markdown",
72
- markdown: { content },
73
- });
74
- this.runtime.touchTransportSession("bot-ws", {
75
- ownerId: this.ownerId,
76
- running: true,
77
- connected: client.isConnected,
78
- authenticated: client.isConnected,
79
- lastOutboundAt: Date.now(),
80
- lastError: undefined,
81
- });
82
- },
83
- sendMedia: async ({ chatId, mediaUrl, text, mediaLocalRoots, maxBytes }) => {
84
- const result = await uploadAndSendBotWsMedia({
85
- wsClient: client,
86
- chatId,
87
- mediaUrl,
88
- mediaLocalRoots,
89
- maxBytes,
90
- });
91
- if (result.ok && text?.trim()) {
92
- await client.sendMessage(chatId, {
93
- msgtype: "markdown",
94
- markdown: { content: text.trim() },
95
- });
96
- }
97
- this.runtime.touchTransportSession("bot-ws", {
98
- ownerId: this.ownerId,
99
- running: true,
100
- connected: client.isConnected,
101
- authenticated: client.isConnected,
102
- lastOutboundAt: Date.now(),
103
- lastError: result.ok ? undefined : result.error,
104
- });
105
- return result;
106
- },
107
- });
108
-
109
- client.on("connected", () => {
110
- this.log.info?.(`[wecom-ws] connected account=${this.runtime.account.accountId}`);
111
- this.runtime.updateTransportSession(
112
- createBotWsSessionSnapshot({
113
- accountId: this.runtime.account.accountId,
114
- ownerId: this.ownerId,
115
- connected: true,
116
- authenticated: false,
117
- }),
118
- );
119
- });
120
-
121
- client.on("authenticated", () => {
122
- this.log.info?.(`[wecom-ws] authenticated account=${this.runtime.account.accountId}`);
123
- this.runtime.updateTransportSession(
124
- createBotWsSessionSnapshot({
125
- accountId: this.runtime.account.accountId,
126
- ownerId: this.ownerId,
127
- connected: true,
128
- authenticated: true,
129
- }),
130
- );
131
- });
132
-
133
- client.on("disconnected", (reason) => {
134
- clearWecomMcpAccountCache(this.runtime.account.accountId);
135
- const normalizedReason = String(reason ?? "").toLowerCase();
136
- const kicked =
137
- normalizedReason.includes("kick") ||
138
- normalizedReason.includes("owner") ||
139
- normalizedReason.includes("replaced");
140
- this.log.warn?.(
141
- `[wecom-ws] disconnected account=${this.runtime.account.accountId} kicked=${String(kicked)} reason=${reason ?? "unknown"}`,
142
- );
143
- if (kicked) {
144
- this.runtime.recordOperationalIssue({
145
- transport: "bot-ws",
146
- category: "ws-kicked",
147
- summary: `ws owner lost: ${reason ?? "unknown"}`,
148
- error: reason ?? "unknown",
149
- });
150
- }
151
- this.runtime.updateTransportSession(
152
- createBotWsSessionSnapshot({
153
- accountId: this.runtime.account.accountId,
154
- ownerId: this.ownerId,
155
- running: false,
156
- connected: false,
157
- authenticated: false,
158
- lastDisconnectedAt: Date.now(),
159
- lastError: reason,
160
- }),
161
- );
162
- });
163
-
164
- client.on("reconnecting", (attempt) => {
165
- this.log.warn?.(
166
- `[wecom-ws] reconnecting account=${this.runtime.account.accountId} attempt=${attempt}`,
167
- );
168
- });
169
-
170
- client.on("error", (error) => {
171
- this.log.error?.(
172
- `[wecom-ws] error account=${this.runtime.account.accountId} message=${error.message}`,
173
- );
174
- this.runtime.updateTransportSession(
175
- createBotWsSessionSnapshot({
176
- accountId: this.runtime.account.accountId,
177
- ownerId: this.ownerId,
178
- running: false,
179
- connected: client.isConnected,
180
- authenticated: client.isConnected,
181
- lastError: error.message,
182
- }),
183
- );
184
- });
185
-
186
- const handleFrame = async (frame: WsFrame<BaseMessage | EventMessage>) => {
187
- const botAccount = this.runtime.account.bot;
188
- if (!botAccount) {
189
- return;
190
- }
191
- this.log.info?.(
192
- `[wecom-ws] frame account=${this.runtime.account.accountId} cmd=${frame.cmd} reqId=${frame.headers.req_id ?? "n/a"}`,
193
- );
194
- this.runtime.touchTransportSession("bot-ws", {
195
- ownerId: this.ownerId,
196
- running: true,
197
- connected: client.isConnected,
198
- authenticated: client.isConnected,
199
- lastInboundAt: Date.now(),
200
- });
201
- const event = mapBotWsFrameToInboundEvent({
202
- account: botAccount,
203
- frame,
204
- });
205
- const replyHandle = createBotWsReplyHandle({
206
- client,
207
- frame,
208
- accountId: this.runtime.account.accountId,
209
- inboundKind: event.inboundKind,
210
- placeholderContent: botAccount.config.streamPlaceholderContent,
211
- autoSendPlaceholder:
212
- event.inboundKind === "text" ||
213
- event.inboundKind === "image" ||
214
- event.inboundKind === "file" ||
215
- event.inboundKind === "voice" ||
216
- event.inboundKind === "mixed",
217
- onDeliver: () => {
218
- this.runtime.touchTransportSession("bot-ws", {
219
- ownerId: this.ownerId,
220
- running: true,
221
- connected: client.isConnected,
222
- authenticated: client.isConnected,
223
- lastOutboundAt: Date.now(),
224
- });
225
- },
226
- onFail: (error) => {
227
- this.runtime.touchTransportSession("bot-ws", {
228
- ownerId: this.ownerId,
229
- running: client.isConnected,
230
- connected: client.isConnected,
231
- authenticated: client.isConnected,
232
- lastError: error instanceof Error ? error.message : String(error),
233
- });
234
- },
235
- });
236
-
237
- const staticWelcomeText =
238
- event.inboundKind === "welcome" ? botAccount.config.welcomeText?.trim() : undefined;
239
- if (staticWelcomeText) {
240
- this.log.info?.(
241
- `[wecom-ws] static welcome reply account=${this.runtime.account.accountId} messageId=${event.messageId} peer=${event.conversation.peerKind}:${event.conversation.peerId} len=${staticWelcomeText.length}`,
242
- );
243
- await replyHandle.deliver(
244
- {
245
- text: staticWelcomeText,
246
- },
247
- { kind: "final" },
248
- );
249
- this.log.info?.(
250
- `[wecom-ws] static welcome delivered account=${this.runtime.account.accountId} messageId=${event.messageId}`,
251
- );
252
- return;
253
- }
254
-
255
- await this.runtime.handleEvent(event, replyHandle);
256
- };
257
-
258
- const runHandleFrame = (frame: WsFrame<BaseMessage | EventMessage>) => {
259
- void handleFrame(frame).catch((error) => {
260
- const message = error instanceof Error ? error.message : String(error);
261
- this.log.error?.(
262
- `[wecom-ws] frame handler failed account=${this.runtime.account.accountId} reqId=${frame.headers?.req_id ?? "n/a"} message=${message}`,
263
- );
264
- this.runtime.recordOperationalIssue({
265
- transport: "bot-ws",
266
- category: "runtime-error",
267
- messageId: frame.body?.msgid,
268
- raw: {
269
- transport: "bot-ws",
270
- command: frame.cmd,
271
- headers: frame.headers,
272
- body: frame.body,
273
- envelopeType: "ws",
274
- },
275
- summary: `bot-ws frame handler crashed reqId=${frame.headers?.req_id ?? "n/a"}`,
276
- error: message,
277
- });
278
- this.runtime.touchTransportSession("bot-ws", {
279
- ownerId: this.ownerId,
280
- running: client.isConnected,
281
- connected: client.isConnected,
282
- authenticated: client.isConnected,
283
- lastError: message,
284
- });
285
- });
286
- };
287
-
288
- client.on("message", (frame) => {
289
- runHandleFrame(frame);
290
- });
291
- client.on("event", (frame) => {
292
- runHandleFrame(frame);
293
- });
294
-
295
- client.connect();
296
- }
297
-
298
- stop(): void {
299
- this.log.info?.(`[wecom-ws] stop account=${this.runtime.account.accountId}`);
300
- clearWecomMcpAccountCache(this.runtime.account.accountId);
301
- unregisterBotWsPushHandle(this.runtime.account.accountId);
302
- this.runtime.updateTransportSession(
303
- createBotWsSessionSnapshot({
304
- accountId: this.runtime.account.accountId,
305
- ownerId: this.ownerId,
306
- running: false,
307
- connected: false,
308
- authenticated: false,
309
- lastDisconnectedAt: Date.now(),
310
- }),
311
- );
312
- this.client?.disconnect();
313
- }
314
- }
@@ -1,28 +0,0 @@
1
- import type { TransportSessionSnapshot } from "../../types/index.js";
2
-
3
- export function createBotWsSessionSnapshot(params: {
4
- accountId: string;
5
- ownerId: string;
6
- connected?: boolean;
7
- authenticated?: boolean;
8
- lastError?: string;
9
- running?: boolean;
10
- lastConnectedAt?: number;
11
- lastDisconnectedAt?: number;
12
- lastInboundAt?: number;
13
- lastOutboundAt?: number;
14
- }): TransportSessionSnapshot {
15
- return {
16
- accountId: params.accountId,
17
- transport: "bot-ws",
18
- running: params.running ?? true,
19
- ownerId: params.ownerId,
20
- connected: params.connected,
21
- authenticated: params.authenticated,
22
- lastConnectedAt: params.lastConnectedAt ?? (params.connected ? Date.now() : undefined),
23
- lastDisconnectedAt: params.lastDisconnectedAt,
24
- lastInboundAt: params.lastInboundAt,
25
- lastOutboundAt: params.lastOutboundAt,
26
- lastError: params.lastError,
27
- };
28
- }
@@ -1,109 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
-
3
- import { WEBHOOK_PATHS } from "../../types/constants.js";
4
-
5
- export type RouteFailureReason =
6
- | "wecom_account_not_found"
7
- | "wecom_account_conflict"
8
- | "wecom_identity_mismatch"
9
- | "wecom_matrix_path_required";
10
-
11
- export function normalizeWecomWebhookPath(raw: string): string {
12
- const trimmed = raw.trim();
13
- if (!trimmed) return "/";
14
- const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
15
- if (withSlash.length > 1 && withSlash.endsWith("/")) return withSlash.slice(0, -1);
16
- return withSlash;
17
- }
18
-
19
- export function resolveQueryParams(req: IncomingMessage): URLSearchParams {
20
- const url = new URL(req.url ?? "/", "http://localhost");
21
- return url.searchParams;
22
- }
23
-
24
- export function resolvePath(req: IncomingMessage): string {
25
- const url = new URL(req.url ?? "/", "http://localhost");
26
- return normalizeWecomWebhookPath(url.pathname || "/");
27
- }
28
-
29
- export function resolveSignatureParam(params: URLSearchParams): string {
30
- return params.get("msg_signature") ?? params.get("msgsignature") ?? params.get("signature") ?? "";
31
- }
32
-
33
- export function isAgentCallbackPathCandidate(path: string): boolean {
34
- return (
35
- path === WEBHOOK_PATHS.AGENT ||
36
- path === WEBHOOK_PATHS.AGENT_PLUGIN ||
37
- path.startsWith(`${WEBHOOK_PATHS.AGENT}/`) ||
38
- path.startsWith(`${WEBHOOK_PATHS.AGENT_PLUGIN}/`)
39
- );
40
- }
41
-
42
- export function isNonMatrixWecomBasePath(path: string): boolean {
43
- return (
44
- path === WEBHOOK_PATHS.BOT ||
45
- path === WEBHOOK_PATHS.BOT_ALT ||
46
- path === WEBHOOK_PATHS.AGENT ||
47
- path === WEBHOOK_PATHS.BOT_PLUGIN ||
48
- path === WEBHOOK_PATHS.AGENT_PLUGIN
49
- );
50
- }
51
-
52
- function maskAccountId(accountId: string): string {
53
- const normalized = accountId.trim();
54
- if (!normalized) return "***";
55
- if (normalized.length <= 4) return `${normalized[0] ?? "*"}***`;
56
- return `${normalized.slice(0, 2)}***${normalized.slice(-2)}`;
57
- }
58
-
59
- export function logRouteFailure(params: {
60
- reqId: string;
61
- path: string;
62
- method: string;
63
- reason: RouteFailureReason;
64
- candidateAccountIds: string[];
65
- }): void {
66
- const payload = {
67
- reqId: params.reqId,
68
- path: params.path,
69
- method: params.method,
70
- reason: params.reason,
71
- candidateAccountIds: params.candidateAccountIds.map(maskAccountId),
72
- };
73
- console.error(`[wecom] route-error ${JSON.stringify(payload)}`);
74
- }
75
-
76
- export function writeRouteFailure(
77
- res: ServerResponse,
78
- reason: RouteFailureReason,
79
- message: string,
80
- ): void {
81
- res.statusCode = 401;
82
- res.setHeader("Content-Type", "application/json; charset=utf-8");
83
- res.end(JSON.stringify({ error: reason, message }));
84
- }
85
-
86
- export async function readTextBody(
87
- req: IncomingMessage,
88
- maxBytes: number,
89
- ): Promise<{ ok: true; value: string } | { ok: false; error: string }> {
90
- const chunks: Buffer[] = [];
91
- let total = 0;
92
- return await new Promise((resolve) => {
93
- req.on("data", (chunk: Buffer) => {
94
- total += chunk.length;
95
- if (total > maxBytes) {
96
- resolve({ ok: false as const, error: "payload too large" });
97
- req.destroy();
98
- return;
99
- }
100
- chunks.push(chunk);
101
- });
102
- req.on("end", () => {
103
- resolve({ ok: true as const, value: Buffer.concat(chunks).toString("utf8") });
104
- });
105
- req.on("error", (err) => {
106
- resolve({ ok: false as const, error: String(err) });
107
- });
108
- });
109
- }
@@ -1,92 +0,0 @@
1
- import type { OpenClawConfig } from "openclaw/plugin-sdk";
2
- import { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk/routing";
3
-
4
- import type { ResolvedAgentAccount, TransportSessionPatch } from "../../types/index.js";
5
- import { monitorState } from "../../monitor/state.js";
6
- import type { WecomRuntimeAuditEvent, WecomRuntimeEnv, WecomWebhookTarget } from "../../types/runtime-context.js";
7
- import { WEBHOOK_PATHS } from "../../types/constants.js";
8
- import { normalizeWecomWebhookPath } from "./common.js";
9
-
10
- export type AgentWebhookTarget = {
11
- agent: ResolvedAgentAccount;
12
- config: OpenClawConfig;
13
- runtimeEnv: WecomRuntimeEnv;
14
- path: string;
15
- touchTransportSession?: (patch: TransportSessionPatch) => void;
16
- auditSink?: (event: WecomRuntimeAuditEvent) => void;
17
- };
18
-
19
- const webhookTargets = new Map<string, WecomWebhookTarget[]>();
20
- const agentTargets = new Map<string, AgentWebhookTarget[]>();
21
-
22
- function ensurePruneTimer(): void {
23
- monitorState.startPruning();
24
- }
25
-
26
- function checkPruneTimer(): void {
27
- if (webhookTargets.size === 0 && agentTargets.size === 0) {
28
- monitorState.stopPruning();
29
- }
30
- }
31
-
32
- export function registerWecomWebhookTarget(target: WecomWebhookTarget): () => void {
33
- const key = normalizeWecomWebhookPath(target.path);
34
- const normalizedTarget = { ...target, path: key };
35
- const existing = webhookTargets.get(key) ?? [];
36
- webhookTargets.set(key, [...existing, normalizedTarget]);
37
- ensurePruneTimer();
38
- return () => {
39
- const updated = (webhookTargets.get(key) ?? []).filter((entry) => entry !== normalizedTarget);
40
- if (updated.length > 0) webhookTargets.set(key, updated);
41
- else webhookTargets.delete(key);
42
- checkPruneTimer();
43
- };
44
- }
45
-
46
- export function registerAgentWebhookTarget(target: AgentWebhookTarget): () => void {
47
- const key = normalizeWecomWebhookPath(target.path);
48
- const normalizedTarget = { ...target, path: key };
49
- const existing = agentTargets.get(key) ?? [];
50
- agentTargets.set(key, [...existing, normalizedTarget]);
51
- ensurePruneTimer();
52
- return () => {
53
- const updated = (agentTargets.get(key) ?? []).filter((entry) => entry !== normalizedTarget);
54
- if (updated.length > 0) agentTargets.set(key, updated);
55
- else agentTargets.delete(key);
56
- checkPruneTimer();
57
- };
58
- }
59
-
60
- export function getWecomWebhookTargets(path: string): WecomWebhookTarget[] {
61
- return webhookTargets.get(normalizeWecomWebhookPath(path)) ?? [];
62
- }
63
-
64
- export function getAgentWebhookTargets(path: string): AgentWebhookTarget[] {
65
- return agentTargets.get(normalizeWecomWebhookPath(path)) ?? [];
66
- }
67
-
68
- export function hasMatrixExplicitRoutesRegistered(): boolean {
69
- for (const [key, targets] of webhookTargets.entries()) {
70
- if (key.startsWith(`${WEBHOOK_PATHS.BOT_ALT}/`) && targets.some((target) => target.account.accountId !== DEFAULT_ACCOUNT_ID)) {
71
- return true;
72
- }
73
- if (
74
- key.startsWith(`${WEBHOOK_PATHS.BOT_PLUGIN}/`) &&
75
- targets.some((target) => target.account.accountId !== DEFAULT_ACCOUNT_ID)
76
- ) {
77
- return true;
78
- }
79
- }
80
- for (const [key, targets] of agentTargets.entries()) {
81
- if (key.startsWith(`${WEBHOOK_PATHS.AGENT}/`) && targets.some((target) => target.agent.accountId !== DEFAULT_ACCOUNT_ID)) {
82
- return true;
83
- }
84
- if (
85
- key.startsWith(`${WEBHOOK_PATHS.AGENT_PLUGIN}/`) &&
86
- targets.some((target) => target.agent.accountId !== DEFAULT_ACCOUNT_ID)
87
- ) {
88
- return true;
89
- }
90
- }
91
- return false;
92
- }
@@ -1,84 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
-
3
- import crypto from "node:crypto";
4
-
5
- import { handleAgentCallbackRequest } from "../agent-callback/request-handler.js";
6
- import type { WecomWebhookTarget } from "../../types/runtime-context.js";
7
- import { getAgentWebhookTargets, getWecomWebhookTargets, hasMatrixExplicitRoutesRegistered } from "./registry.js";
8
- import {
9
- isAgentCallbackPathCandidate,
10
- isNonMatrixWecomBasePath,
11
- logRouteFailure,
12
- resolvePath,
13
- resolveQueryParams,
14
- writeRouteFailure,
15
- } from "./common.js";
16
-
17
- export async function handleWecomHttpRequest(params: {
18
- req: IncomingMessage;
19
- res: ServerResponse;
20
- handleBotWebhookRequest: (params: {
21
- req: IncomingMessage;
22
- res: ServerResponse;
23
- path: string;
24
- reqId: string;
25
- targets: WecomWebhookTarget[];
26
- }) => Promise<boolean>;
27
- }): Promise<boolean> {
28
- const { req, res, handleBotWebhookRequest } = params;
29
-
30
- const path = resolvePath(req);
31
- const reqId = crypto.randomUUID().slice(0, 8);
32
- const remote = req.socket?.remoteAddress ?? "unknown";
33
- const ua = String(req.headers["user-agent"] ?? "");
34
- const cl = String(req.headers["content-length"] ?? "");
35
- const q = resolveQueryParams(req);
36
- const hasTimestamp = Boolean(q.get("timestamp"));
37
- const hasNonce = Boolean(q.get("nonce"));
38
- const hasEchostr = Boolean(q.get("echostr"));
39
- const hasMsgSig = Boolean(q.get("msg_signature"));
40
- const hasSignature = Boolean(q.get("signature"));
41
- console.log(
42
- `[wecom] inbound(http): reqId=${reqId} path=${path} method=${req.method ?? "UNKNOWN"} remote=${remote} ua=${ua ? `"${ua}"` : "N/A"} contentLength=${cl || "N/A"} query={timestamp:${hasTimestamp},nonce:${hasNonce},echostr:${hasEchostr},msg_signature:${hasMsgSig},signature:${hasSignature}}`,
43
- );
44
-
45
- if (hasMatrixExplicitRoutesRegistered() && isNonMatrixWecomBasePath(path)) {
46
- logRouteFailure({
47
- reqId,
48
- path,
49
- method: req.method ?? "UNKNOWN",
50
- reason: "wecom_matrix_path_required",
51
- candidateAccountIds: [],
52
- });
53
- writeRouteFailure(
54
- res,
55
- "wecom_matrix_path_required",
56
- "Matrix mode requires explicit account path. Use /plugins/wecom/bot/{accountId} or /plugins/wecom/agent/{accountId}.",
57
- );
58
- return true;
59
- }
60
-
61
- const agentTargets = getAgentWebhookTargets(path);
62
- if (agentTargets.length > 0 || isAgentCallbackPathCandidate(path)) {
63
- return handleAgentCallbackRequest({
64
- req,
65
- res,
66
- path,
67
- reqId,
68
- targets: agentTargets,
69
- });
70
- }
71
-
72
- const botTargets = getWecomWebhookTargets(path);
73
- if (botTargets.length === 0) {
74
- return false;
75
- }
76
-
77
- return handleBotWebhookRequest({
78
- req,
79
- res,
80
- path,
81
- reqId,
82
- targets: botTargets,
83
- });
84
- }
@@ -1,70 +0,0 @@
1
- import type {
2
- WecomAccountConfig,
3
- WecomAgentConfig,
4
- WecomBotConfig,
5
- WecomBotPrimaryTransport,
6
- WecomNetworkConfig,
7
- } from "./config.js";
8
-
9
- export type ResolvedMode = "disabled" | "legacy" | "matrix";
10
-
11
- export type ResolvedBotWsTransport = {
12
- botId: string;
13
- secret: string;
14
- };
15
-
16
- export type ResolvedBotWebhookTransport = {
17
- token: string;
18
- encodingAESKey: string;
19
- receiveId: string;
20
- };
21
-
22
- export type ResolvedBotAccount = {
23
- accountId: string;
24
- configured: boolean;
25
- primaryTransport: WecomBotPrimaryTransport;
26
- wsConfigured: boolean;
27
- webhookConfigured: boolean;
28
- config: WecomBotConfig;
29
- network?: WecomNetworkConfig;
30
- ws?: ResolvedBotWsTransport;
31
- webhook?: ResolvedBotWebhookTransport;
32
- // Compatibility flattening for old webhook-centric helpers.
33
- token: string;
34
- encodingAESKey: string;
35
- receiveId: string;
36
- botId: string;
37
- secret: string;
38
- };
39
-
40
- export type ResolvedAgentAccount = {
41
- accountId: string;
42
- configured: boolean;
43
- callbackConfigured: boolean;
44
- apiConfigured: boolean;
45
- corpId: string;
46
- corpSecret: string;
47
- agentId?: number;
48
- token: string;
49
- encodingAESKey: string;
50
- config: WecomAgentConfig;
51
- network?: WecomNetworkConfig;
52
- };
53
-
54
- export type ResolvedWecomAccount = {
55
- accountId: string;
56
- name?: string;
57
- enabled: boolean;
58
- configured: boolean;
59
- config: WecomAccountConfig;
60
- bot?: ResolvedBotAccount;
61
- agent?: ResolvedAgentAccount;
62
- };
63
-
64
- export type ResolvedWecomAccounts = {
65
- mode: ResolvedMode;
66
- defaultAccountId: string;
67
- accounts: Record<string, ResolvedWecomAccount>;
68
- bot?: ResolvedBotAccount;
69
- agent?: ResolvedAgentAccount;
70
- };