@yuriai/web 0.2.27-beta.6 → 0.2.27

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 (228) hide show
  1. package/README.md +8 -0
  2. package/dist/assets/{AgentAvatar-Bi1vvWPC.js → AgentAvatar-DNm_jMna.js} +1 -1
  3. package/dist/assets/AssistantContactStatus-BPRpgMFh.js +3 -0
  4. package/dist/assets/{AssistantUnreadBadge-DdJyySwn.js → AssistantUnreadBadge-BssH-RvV.js} +1 -1
  5. package/dist/assets/AssistantView-CxQv-9Ms.js +1 -0
  6. package/dist/assets/{DiagramView-CI4bTtxy.js → DiagramView-DPpG0fwx.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-BB4qEnAn.js → FadeInOnReveal-S6UbimjB.js} +1 -1
  8. package/dist/assets/{GuiPluginSurface-CguxFUbM.js → GuiPluginSurface-BOf0JA1T.js} +1 -1
  9. package/dist/assets/{GuiPluginWindow-DOJ7wuRH.js → GuiPluginWindow-OrYkfQ4m.js} +1 -1
  10. package/dist/assets/{Icon-t2xvbAyN.js → Icon-BE4mEwzV.js} +1 -1
  11. package/dist/assets/{ImageLoadingPlaceholder-D1L13TK0.js → ImageLoadingPlaceholder-CBFJC_KD.js} +1 -1
  12. package/dist/assets/{LoadingImage-5rY_edNm.js → LoadingImage-NLq7_P-i.js} +1 -1
  13. package/dist/assets/MarkdownRenderer-BaMotAOQ.js +2 -0
  14. package/dist/assets/{MarkdownRendererImpl-cE-0AYRg.js → MarkdownRendererImpl-Cv6UnGG7.js} +1 -1
  15. package/dist/assets/{MarkstreamRendererImpl-BZyqDl82.js → MarkstreamRendererImpl-Rb9O6wkW.js} +1 -1
  16. package/dist/assets/{MobileDetailNavigation-tbfsMfB-.js → MobileDetailNavigation-CK4KbkeS.js} +1 -1
  17. package/dist/assets/{MobileResizableSheet-BeRmT6_x.js → MobileResizableSheet-Deidw1br.js} +1 -1
  18. package/dist/assets/{MobileShareBridge-C3Equ3P_.js → MobileShareBridge-CO_OWEfq.js} +2 -2
  19. package/dist/assets/MobileTabPageHeader-DbC8L6A4.js +2 -0
  20. package/dist/assets/{MultiRunWindow-CAM2XPII.js → MultiRunWindow-DtVW9NTV.js} +1 -1
  21. package/dist/assets/{OnboardingScreen-4ftRerP5.js → OnboardingScreen-C8ld4wO7.js} +1 -1
  22. package/dist/assets/{OverlayScrollbar-CF0PCvQz.js → OverlayScrollbar-B3auC2WH.js} +1 -1
  23. package/dist/assets/{SettingsView-2tk4WH7R.js → SettingsView-Cm7woZWl.js} +15 -15
  24. package/dist/assets/{SettingsWindow-B9zbeJaW.js → SettingsWindow-CdL4PFxW.js} +1 -1
  25. package/dist/assets/{TerminalView-DfxvTHye.js → TerminalView-CwRB6Yyr.js} +1 -1
  26. package/dist/assets/{ToolOutputDialog-CrjDIhru.js → ToolOutputDialog-B4BfmoVH.js} +1 -1
  27. package/dist/assets/{YuriLogo-QvS1ZEHi.js → YuriLogo-BOx0s0Ue.js} +1 -1
  28. package/dist/assets/{appThemeRegistry-Bb_DtiV9.js → appThemeRegistry-B6woJIX5.js} +1 -1
  29. package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
  30. package/dist/assets/{button-DinGM3tu.js → button-BXxwtxsG.js} +1 -1
  31. package/dist/assets/{capgoAdapter-DufzjXRs.js → capgoAdapter-C5HFS-rx.js} +1 -1
  32. package/dist/assets/{collapsible-Bh1GLNYV.js → collapsible-BEm0787p.js} +1 -1
  33. package/dist/assets/context-menu-DUwvVUDY.js +1 -0
  34. package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
  35. package/dist/assets/device-BcRP6Tjd.js +2 -0
  36. package/dist/assets/{diagram-BmG-7Jb4.js → diagram-DyY8dxjZ.js} +1 -1
  37. package/dist/assets/{dialog-BXssfGXA.js → dialog-CLca6ojn.js} +1 -1
  38. package/dist/assets/dropdown-menu.styles-DGaALKP0.js +1 -0
  39. package/dist/assets/{es-HP_Ise0X.js → es-CrsHvgue.js} +2 -2
  40. package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
  41. package/dist/assets/fileMentionAutocompleteState-BZJqfgae.js +2 -0
  42. package/dist/assets/{fileMentionTouchSelection-DSl0tj2r.js → fileMentionTouchSelection-C4dvP8GY.js} +2 -2
  43. package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
  44. package/dist/assets/{fileReferenceActions-CGpBSFq4.js → fileReferenceActions-CrIAce3K.js} +1 -1
  45. package/dist/assets/{fr-D0kJXJ6U.js → fr-CEgiRlfa.js} +2 -2
  46. package/dist/assets/{gitApi-Wo0IZow9.js → gitApi-D2G9ny2O.js} +1 -1
  47. package/dist/assets/{gitApiHttp-De9liKnG.js → gitApiHttp-B7vYwgBh.js} +4 -4
  48. package/dist/assets/{gui-9enrif_1.js → gui-CJjEj3l4.js} +1 -1
  49. package/dist/assets/host-CnVx34Dh.js +1 -0
  50. package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
  51. package/dist/assets/{input-v8-rVbo-.js → input-D59Q2pm8.js} +1 -1
  52. package/dist/assets/insertionBoundaries-CedfTSM5.js +1 -0
  53. package/dist/assets/{ja-BjHKXazE.js → ja-CX-_p9jZ.js} +2 -2
  54. package/dist/assets/{ko-Llwnl876.js → ko-D5xlLYJM.js} +2 -2
  55. package/dist/assets/main-CxpUooVS.js +2 -0
  56. package/dist/assets/main-Dpm4KxWX.js +169 -0
  57. package/dist/assets/{markdownHeightCache-BVV2dktw.js → markdownHeightCache-D2VWb_4E.js} +1 -1
  58. package/dist/assets/{mcpQueries-BoBrB4a4.js → mcpQueries-DQ3KthDF.js} +1 -1
  59. package/dist/assets/miniChat-CTdj8Ug9.js +2 -0
  60. package/dist/assets/mobile-ChbA3Q8j.js +2 -0
  61. package/dist/assets/{mobileBackNavigation-DMSzAvb6.js → mobileBackNavigation-BJqt3oHk.js} +1 -1
  62. package/dist/assets/{multirun-BhWttsRQ.js → multirun-BILeETbd.js} +1 -1
  63. package/dist/assets/{native-DSvNnKAm.js → native-BYMhr-xH.js} +1 -1
  64. package/dist/assets/{native-config-DjdrW_9n.js → native-config-BIY0Cr-l.js} +1 -1
  65. package/dist/assets/{persistence-CfrHIiIS.js → persistence-CWuLIq1J.js} +2 -2
  66. package/dist/assets/{pl-BOd_idqn.js → pl-BjH81A_q.js} +2 -2
  67. package/dist/assets/projectMeta-B9_Uh8YH.js +1 -0
  68. package/dist/assets/{pt-BR-B8djxMsl.js → pt-BR-Dp5oK2x3.js} +2 -2
  69. package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
  70. package/dist/assets/queue-abort-optimistic-CS5jTJq-.js +1 -0
  71. package/dist/assets/react-DRe85o5s.js +1 -0
  72. package/dist/assets/readiness-BNIgH81X.js +1 -0
  73. package/dist/assets/renderElectronMiniChatApp-asOqV7FB.js +2 -0
  74. package/dist/assets/renderMobileApp-DAfque7-.js +28 -0
  75. package/dist/assets/runtime-fetch-D0YWp3FJ.js +1 -0
  76. package/dist/assets/{runtime-file-download-CcNIVp7u.js → runtime-file-download-Cf1WxfeW.js} +1 -1
  77. package/dist/assets/{runtime-file-resource-6np6lzoV.js → runtime-file-resource-UJjHUF2C.js} +1 -1
  78. package/dist/assets/runtimeConfig-BX8JirIc.js +2 -0
  79. package/dist/assets/runtimeEndpointReset-CFQgUiUr.js +149 -0
  80. package/dist/assets/scheduledTaskNavigation-EomDNVu2.js +1 -0
  81. package/dist/assets/sessionLookup-BxAaxPOw.js +1 -0
  82. package/dist/assets/{sortable-tabs-strip-yKyqsqut.js → sortable-tabs-strip-DpbW5MqX.js} +1 -1
  83. package/dist/assets/speechSettingsQueries-CC0fusUo.js +4 -0
  84. package/dist/assets/src-BMKjN2ip.css +2 -0
  85. package/dist/assets/{store-CUBymvAC.js → store-CkIHVrmT.js} +4 -3
  86. package/dist/assets/{terminalApi-BblSkqch.js → terminalApi-rl9mZAlB.js} +1 -1
  87. package/dist/assets/{textarea-B39OCNPV.js → textarea-7eTptEtD.js} +1 -1
  88. package/dist/assets/{tooltip-d8TNN4lx.js → tooltip-BPwoSTzO.js} +1 -1
  89. package/dist/assets/types-CUtSV1V8.js +2 -0
  90. package/dist/assets/{uk-BNd7CjVO.js → uk-BEfkaLtM.js} +2 -2
  91. package/dist/assets/{useAppFontEffects-BVoVpJYO.js → useAppFontEffects-Ck2PdQRx.js} +52 -52
  92. package/dist/assets/{useAssistantUIStore-Bp6TxG5E.js → useAssistantUIStore-CfaQV3ID.js} +1 -1
  93. package/dist/assets/useDesktopWindowControlsLayout-DxxOUZj1.js +1 -0
  94. package/dist/assets/useEffectiveDirectory-CNCQfN_x.js +1 -0
  95. package/dist/assets/{useFontPreferences-BFyBjtQ6.js → useFontPreferences-DeqW9nRx.js} +1 -1
  96. package/dist/assets/useMobileNavigationStore-BmVr5a5c.js +17 -0
  97. package/dist/assets/useUIStore-C6CE42oh.js +1 -0
  98. package/dist/assets/{useWorkerHighlightedLines-CPxG8Fya.js → useWorkerHighlightedLines-CN_RGaSw.js} +1 -1
  99. package/dist/assets/{vendor-effect-DV9F8PTZ.js → vendor-effect-X1Hqc7ba.js} +13 -13
  100. package/dist/assets/vendor-opencode-client-cQ47ywrT.js +23 -0
  101. package/dist/assets/{vendor-opencode-plugin-CgKz9Hcy.js → vendor-opencode-plugin-BmdTE4Te.js} +1 -1
  102. package/dist/assets/vendor-opencode-schema-DWT45VBX.js +1 -0
  103. package/dist/assets/vendor-solid-js-D98iXT7C.js +1 -0
  104. package/dist/assets/vendor-zod-DZzbCm1s.js +55 -0
  105. package/dist/assets/{zh-CN-BkTAEOZG.js → zh-CN-DipfA56P.js} +2 -2
  106. package/dist/assets/{zh-TW-x8SfMzfc.js → zh-TW-B7pXMVjt.js} +2 -2
  107. package/dist/index.html +18 -18
  108. package/dist/mini-chat.html +18 -18
  109. package/dist/mobile.html +18 -18
  110. package/package.json +6 -1
  111. package/server/index.js +2 -145
  112. package/server/lib/assistants/DOCUMENTATION.md +69 -11
  113. package/server/lib/assistants/cards.js +1 -1
  114. package/server/lib/assistants/channel-image.js +92 -0
  115. package/server/lib/assistants/channel-image.test.js +76 -0
  116. package/server/lib/assistants/channel-output-store.test.js +41 -0
  117. package/server/lib/assistants/channel-output.integration.test.js +114 -0
  118. package/server/lib/assistants/channel-output.js +90 -0
  119. package/server/lib/assistants/channel-output.test.js +79 -0
  120. package/server/lib/assistants/channels/DOCUMENTATION.md +329 -0
  121. package/server/lib/assistants/channels/PROTOCOLS.md +250 -0
  122. package/server/lib/assistants/channels/dingtalk-chat-adapter.js +645 -0
  123. package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +423 -0
  124. package/server/lib/assistants/channels/integration.test.js +44 -0
  125. package/server/lib/assistants/channels/routes.js +59 -0
  126. package/server/lib/assistants/channels/routes.test.js +139 -0
  127. package/server/lib/assistants/channels/runtime.js +958 -0
  128. package/server/lib/assistants/channels/runtime.test.js +897 -0
  129. package/server/lib/assistants/channels/sdk-adapters.js +383 -0
  130. package/server/lib/assistants/channels/sdk-adapters.test.js +384 -0
  131. package/server/lib/assistants/channels/store.js +249 -0
  132. package/server/lib/assistants/channels/store.test.js +296 -0
  133. package/server/lib/assistants/channels/transport.js +42 -0
  134. package/server/lib/assistants/channels/transport.test.js +23 -0
  135. package/server/lib/assistants/channels/wecom-chat-adapter.js +703 -0
  136. package/server/lib/assistants/channels/wecom-chat-adapter.test.js +130 -0
  137. package/server/lib/assistants/contact-store.js +9 -3
  138. package/server/lib/assistants/contact-store.test.js +27 -0
  139. package/server/lib/assistants/contact-tools.js +65 -75
  140. package/server/lib/assistants/contact-tools.test.js +114 -22
  141. package/server/lib/assistants/harness.js +79 -34
  142. package/server/lib/assistants/harness.test.js +52 -20
  143. package/server/lib/assistants/message-channel-origin.js +7 -0
  144. package/server/lib/assistants/resource-reference.integration.test.js +284 -0
  145. package/server/lib/assistants/routes.js +14 -4
  146. package/server/lib/assistants/service.js +116 -69
  147. package/server/lib/assistants/service.test.js +31 -17
  148. package/server/lib/assistants/weixin/DOCUMENTATION.md +121 -14
  149. package/server/lib/assistants/weixin/api.js +45 -1
  150. package/server/lib/assistants/weixin/api.test.js +28 -0
  151. package/server/lib/assistants/weixin/chat-adapter.js +113 -0
  152. package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
  153. package/server/lib/assistants/weixin/inbound.js +149 -0
  154. package/server/lib/assistants/weixin/inbound.test.js +141 -0
  155. package/server/lib/assistants/weixin/media.js +79 -0
  156. package/server/lib/assistants/weixin/media.test.js +66 -0
  157. package/server/lib/assistants/weixin/runtime.js +105 -74
  158. package/server/lib/assistants/weixin/runtime.test.js +192 -4
  159. package/server/lib/assistants/weixin/store.js +16 -8
  160. package/server/lib/assistants/weixin/store.test.js +93 -0
  161. package/server/lib/assistants/weixin/toon.js +49 -0
  162. package/server/lib/assistants/weixin/toon.test.js +25 -0
  163. package/server/lib/assistants/yuri-project.http.test.js +9 -3
  164. package/server/lib/github/DOCUMENTATION.md +9 -8
  165. package/server/lib/llm/bridge-plugin.bundle.js +188 -188
  166. package/server/lib/notifications/DOCUMENTATION.md +6 -0
  167. package/server/lib/notifications/runtime.js +26 -15
  168. package/server/lib/notifications/runtime.test.js +14 -13
  169. package/server/lib/opencode/DOCUMENTATION.md +10 -1
  170. package/server/lib/opencode/auth.d.ts +6 -2
  171. package/server/lib/opencode/core-routes.js +0 -1
  172. package/server/lib/opencode/feature-routes-runtime.js +0 -24
  173. package/server/lib/opencode/location-release.d.ts +5 -1
  174. package/server/lib/opencode/managed-capabilities/scheduled-task.js +1 -1
  175. package/server/lib/opencode/managed-capabilities-runtime.test.js +1 -1
  176. package/server/lib/opencode/native-goal.js +15 -0
  177. package/server/lib/opencode/native-goal.test.js +17 -0
  178. package/server/lib/opencode/settings-helpers.js +0 -6
  179. package/server/lib/opencode/shutdown-runtime.js +0 -2
  180. package/server/lib/projects/project-config.js +3 -6
  181. package/server/lib/scheduled-tasks/DOCUMENTATION.md +10 -35
  182. package/server/lib/scheduled-tasks/managed-tool-route.js +1 -30
  183. package/server/lib/scheduled-tasks/routes.js +0 -26
  184. package/server/lib/scheduled-tasks/runtime.js +33 -257
  185. package/server/lib/scheduled-tasks/runtime.test.js +24 -65
  186. package/server/lib/session-metadata/DOCUMENTATION.md +9 -12
  187. package/server/lib/session-metadata/routes.js +4 -38
  188. package/server/lib/session-metadata/routes.test.js +2 -2
  189. package/dist/assets/AssistantContactStatus-CWq-PDz6.js +0 -3
  190. package/dist/assets/AssistantView-Br1iETTs.js +0 -1
  191. package/dist/assets/MarkdownRenderer-BlGxjOei.js +0 -2
  192. package/dist/assets/MobileTabPageHeader-DQRqAAEf.js +0 -2
  193. package/dist/assets/context-menu-DpbkRkk1.js +0 -1
  194. package/dist/assets/device-BjRYYXNT.js +0 -2
  195. package/dist/assets/host-FR_grJxM.js +0 -1
  196. package/dist/assets/insertionBoundaries-CZz7TWJv.js +0 -1
  197. package/dist/assets/main-Bp9HHqTr.js +0 -2
  198. package/dist/assets/main-DOwAfmxJ.js +0 -169
  199. package/dist/assets/miniChat-BJDgCrfF.js +0 -2
  200. package/dist/assets/mobile-GM9931J_.js +0 -2
  201. package/dist/assets/projectMeta-31PobC-M.js +0 -1
  202. package/dist/assets/react-B9v0P7kT.js +0 -1
  203. package/dist/assets/readiness-CYNnsekT.js +0 -1
  204. package/dist/assets/renderElectronMiniChatApp-N2r999Bf.js +0 -2
  205. package/dist/assets/renderMobileApp-CU1ec6Ak.js +0 -28
  206. package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
  207. package/dist/assets/runtimeConfig-Db7yfo6L.js +0 -2
  208. package/dist/assets/runtimeEndpointReset-DO5WVetV.js +0 -149
  209. package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +0 -1
  210. package/dist/assets/sessionLookup-DRVy7LM1.js +0 -1
  211. package/dist/assets/speechSettingsQueries-DU25rmGc.js +0 -4
  212. package/dist/assets/src-Bckdo2XS.css +0 -2
  213. package/dist/assets/types-BqFQhQTt.js +0 -2
  214. package/dist/assets/useDesktopWindowControlsLayout-CYx1LNO5.js +0 -1
  215. package/dist/assets/useEffectiveDirectory-D8FFE5Yn.js +0 -1
  216. package/dist/assets/useMobileNavigationStore-BHMFeMjo.js +0 -23
  217. package/dist/assets/useUIStore-BbYD420L.js +0 -1
  218. package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
  219. package/dist/assets/vendor-solid-js-0T254UHG.js +0 -1
  220. package/dist/assets/vendor-zod-Dzk5kdUU.js +0 -39
  221. package/server/lib/session-goal/DOCUMENTATION.md +0 -371
  222. package/server/lib/session-goal/capability.js +0 -57
  223. package/server/lib/session-goal/capability.test.js +0 -33
  224. package/server/lib/session-goal/objectives.js +0 -61
  225. package/server/lib/session-goal/routes.js +0 -274
  226. package/server/lib/session-goal/routes.test.js +0 -211
  227. package/server/lib/session-goal/runtime.js +0 -2452
  228. package/server/lib/session-goal/runtime.test.js +0 -2125
@@ -0,0 +1,703 @@
1
+ import { WSClient } from '@wecom/aibot-node-sdk';
2
+ import { Message, NotImplementedError, parseMarkdown, stringifyMarkdown } from 'chat';
3
+ import { channelError } from './transport.js';
4
+
5
+ /**
6
+ * WeCom smart-bot adapter on the official `@wecom/aibot-node-sdk`.
7
+ *
8
+ * The official `WSClient` owns the WebSocket, authentication, heartbeat,
9
+ * reconnect and the per-`req_id` ACK queue. This adapter only projects messages,
10
+ * enforces the owner private-chat scope and maps SDK events/Acks onto Yuri's
11
+ * safe channel errors.
12
+ */
13
+
14
+ const THREAD_PREFIX = 'wecom:';
15
+ const INIT_TIMEOUT_MS = 20_000;
16
+ const MAX_TEXT_CHARS = 20_000;
17
+ const MAX_RESOURCES = 8;
18
+ const MAX_NAME_CHARS = 120;
19
+
20
+ function nonEmptyString(value) {
21
+ return typeof value === 'string' && value.length > 0;
22
+ }
23
+
24
+ function truncate(value, limit = MAX_TEXT_CHARS) {
25
+ if (!nonEmptyString(value)) return '';
26
+ return Array.from(value).slice(0, limit).join('');
27
+ }
28
+
29
+ function truncateName(value) {
30
+ if (!nonEmptyString(value)) return undefined;
31
+ return Array.from(value).slice(0, MAX_NAME_CHARS).join('');
32
+ }
33
+
34
+ function credentialKey(clientID, clientSecret) {
35
+ return `${clientID}\u0000${clientSecret}`;
36
+ }
37
+
38
+ function isYuriError(error) {
39
+ return typeof error?.code === 'string' && typeof error?.ambiguous === 'boolean';
40
+ }
41
+
42
+ /** Inert logger: the SDK logs frame bodies and IDs, so nothing is forwarded. */
43
+ function noopLogger() {
44
+ const logger = {
45
+ debug: () => {},
46
+ info: () => {},
47
+ warn: () => {},
48
+ error: () => {},
49
+ };
50
+ return logger;
51
+ }
52
+
53
+ function requireConfig(config) {
54
+ if (!config || typeof config !== 'object') throw channelError('invalid_response');
55
+ if (!nonEmptyString(config.clientID) || !nonEmptyString(config.clientSecret)) {
56
+ throw channelError('invalid_response');
57
+ }
58
+ if (config.ownerID !== undefined && typeof config.ownerID !== 'string') throw channelError('invalid_response');
59
+ return { clientID: config.clientID, clientSecret: config.clientSecret, ownerID: config.ownerID ?? '' };
60
+ }
61
+
62
+ function threadIdOf(chatType, id) {
63
+ return `${THREAD_PREFIX}${chatType}:${id}`;
64
+ }
65
+
66
+ function decodeThreadId(threadId) {
67
+ if (typeof threadId !== 'string' || !threadId.startsWith(THREAD_PREFIX)) throw channelError('invalid_response');
68
+ const rest = threadId.slice(THREAD_PREFIX.length);
69
+ const separator = rest.indexOf(':');
70
+ if (separator <= 0) throw channelError('invalid_response');
71
+ const chatType = rest.slice(0, separator);
72
+ const id = rest.slice(separator + 1);
73
+ if ((chatType !== 'private' && chatType !== 'group') || !id) throw channelError('invalid_response');
74
+ return { chatType, id };
75
+ }
76
+
77
+ function resourceName(body) {
78
+ return truncateName(body?.file?.filename ?? body?.file?.name);
79
+ }
80
+
81
+ function inboundContent(body, msgtype) {
82
+ if (msgtype === 'text') return { text: truncate(body?.text?.content), resources: [] };
83
+ if (msgtype === 'voice') {
84
+ const transcript = truncate(body?.voice?.content);
85
+ return transcript
86
+ ? { text: transcript, resources: [], transcript: 'platform' }
87
+ : { text: '', resources: [{ type: 'audio' }] };
88
+ }
89
+ if (msgtype === 'image') return { text: '', resources: [{ type: 'image' }] };
90
+ if (msgtype === 'video') return { text: '', resources: [{ type: 'video' }] };
91
+ if (msgtype === 'file') {
92
+ const name = resourceName(body);
93
+ return { text: '', resources: [{ type: 'file', ...(name ? { name } : {}) }] };
94
+ }
95
+ if (msgtype === 'mixed') {
96
+ const lines = [];
97
+ const resources = [];
98
+ const items = Array.isArray(body?.mixed?.msg_item) ? body.mixed.msg_item.slice(0, 64) : [];
99
+ for (const item of items) {
100
+ if (item?.msgtype === 'text') {
101
+ const line = truncate(item?.text?.content);
102
+ if (line) lines.push(line);
103
+ } else if (item?.msgtype === 'image') {
104
+ resources.push({ type: 'image' });
105
+ }
106
+ }
107
+ return { text: lines.join('\n'), resources };
108
+ }
109
+ return { text: '', resources: [] };
110
+ }
111
+
112
+ function readBody(body) {
113
+ if (!body || typeof body !== 'object') return null;
114
+ const senderID = body?.from?.userid;
115
+ if (!nonEmptyString(senderID)) return null;
116
+ const msgtype = nonEmptyString(body.msgtype) ? body.msgtype : '';
117
+ if (!['single', 'group'].includes(body.chattype) || !nonEmptyString(body.msgid)) return null;
118
+ const chatType = body.chattype === 'group' ? 'group' : 'private';
119
+ const chatID = chatType === 'group' ? String(body.chatid ?? senderID) : senderID;
120
+ const content = inboundContent(body, msgtype);
121
+ const createdAt = Number(body.create_time);
122
+ return {
123
+ id: String(body.msgid ?? ''),
124
+ senderID,
125
+ chatType,
126
+ chatID,
127
+ threadId: threadIdOf(chatType, chatID),
128
+ msgtype,
129
+ text: truncate(content.text),
130
+ resources: content.resources.slice(0, MAX_RESOURCES),
131
+ transcript: content.transcript,
132
+ createdAt: Number.isFinite(createdAt) && createdAt > 0
133
+ ? new Date(createdAt > 1e12 ? createdAt : createdAt * 1000)
134
+ : new Date(),
135
+ };
136
+ }
137
+
138
+ /** Public raw projection: no download URL, aeskey, response_url or quote body. */
139
+ function sanitizeRaw(data) {
140
+ const raw = {
141
+ msgid: data.id,
142
+ chattype: data.chatType === 'group' ? 'group' : 'single',
143
+ from: { userid: data.senderID },
144
+ msgtype: data.msgtype,
145
+ };
146
+ if (data.chatType === 'group') raw.chatid = data.chatID;
147
+ if (data.text) raw.text = { content: data.text };
148
+ if (data.transcript) raw.voice = { content: data.text };
149
+ if (data.resources.length > 0) raw.attachments = data.resources;
150
+ return raw;
151
+ }
152
+
153
+ function buildMessage(data) {
154
+ return new Message({
155
+ id: data.id,
156
+ threadId: data.threadId,
157
+ text: data.text,
158
+ formatted: parseMarkdown(data.text),
159
+ raw: sanitizeRaw(data),
160
+ author: {
161
+ userId: data.senderID,
162
+ userName: data.senderID,
163
+ fullName: data.senderID,
164
+ isBot: false,
165
+ isMe: false,
166
+ },
167
+ metadata: {
168
+ dateSent: data.createdAt,
169
+ edited: false,
170
+ platform: 'wecom',
171
+ ...(data.transcript ? { transcript: 'platform' } : {}),
172
+ ...(data.resources.length > 0 ? { notDownloaded: true } : {}),
173
+ },
174
+ attachments: data.resources,
175
+ });
176
+ }
177
+
178
+ /** Yuri projection used by the runtime. Metadata is public-only. */
179
+ function buildProjection(data) {
180
+ return {
181
+ id: data.id,
182
+ senderID: data.senderID,
183
+ chatType: 'private',
184
+ text: data.text,
185
+ metadata: {
186
+ platform: 'wecom',
187
+ chatType: 'private',
188
+ ...(data.transcript ? { transcript: 'platform' } : {}),
189
+ ...(data.resources.length > 0 ? { notDownloaded: true, resources: data.resources } : {}),
190
+ },
191
+ };
192
+ }
193
+
194
+ /** Accept standard Chat postables only; cards/unknown shapes are explicit. */
195
+ function messageText(message) {
196
+ if (typeof message === 'string') return message;
197
+ if (!message || typeof message !== 'object') {
198
+ throw new NotImplementedError('wecom: unsupported postable message', 'postMessage');
199
+ }
200
+ if (message.files?.length || message.attachments?.length) throw new NotImplementedError('wecom: media sending is not supported');
201
+ if (typeof message.raw === 'string') return message.raw;
202
+ if (typeof message.markdown === 'string') return message.markdown;
203
+ if (message.ast) return stringifyMarkdown(message.ast);
204
+ throw new NotImplementedError('wecom: unsupported postable message', 'postMessage');
205
+ }
206
+
207
+ function lifecycleCode(error) {
208
+ if (error?.code === 'WS_AUTH_FAILURE_EXHAUSTED') return 'auth_expired';
209
+ if (error?.code === 'WS_RECONNECT_EXHAUSTED') return 'reconnect_exhausted';
210
+ if (/Authentication failed/i.test(String(error?.message ?? ''))) return 'auth_expired';
211
+ return 'network_error';
212
+ }
213
+
214
+ /**
215
+ * Map an official `sendMessage` rejection.
216
+ * - non-zero ACK frame: definite failure
217
+ * - not connected before the write: definite network failure
218
+ * - timeout / close / manual abort: unknown (the frame may be on the wire)
219
+ */
220
+ function sendError(error) {
221
+ if (error && typeof error === 'object' && Number.isFinite(error.errcode)) {
222
+ return error.errcode === 0 ? null : channelError('delivery_failed');
223
+ }
224
+ if (error?.code === 'WS_AUTH_FAILURE_EXHAUSTED') return channelError('auth_expired');
225
+ if (/Authentication failed/i.test(String(error?.message ?? ''))) return channelError('auth_expired');
226
+ if (/WebSocket not connected/i.test(String(error?.message ?? ''))) return channelError('network_error');
227
+ return channelError('delivery_unknown', true);
228
+ }
229
+
230
+ function withAbort(promise, signal) {
231
+ if (!signal) return promise;
232
+ return new Promise((resolve, reject) => {
233
+ let settled = false;
234
+ const onAbort = () => {
235
+ if (settled) return;
236
+ settled = true;
237
+ signal.removeEventListener('abort', onAbort);
238
+ // The frame may already be on the wire; never retry automatically.
239
+ reject(channelError('delivery_unknown', true));
240
+ };
241
+ signal.addEventListener('abort', onAbort, { once: true });
242
+ if (signal.aborted) onAbort();
243
+ promise.then(
244
+ (value) => {
245
+ if (settled) return;
246
+ settled = true;
247
+ signal.removeEventListener('abort', onAbort);
248
+ resolve(value);
249
+ },
250
+ (error) => {
251
+ if (settled) return;
252
+ settled = true;
253
+ signal.removeEventListener('abort', onAbort);
254
+ reject(error);
255
+ },
256
+ );
257
+ });
258
+ }
259
+
260
+ export class WecomChatAdapter {
261
+ name = 'wecom';
262
+
263
+ userName;
264
+
265
+ persistMessageHistory = false;
266
+
267
+ constructor({
268
+ clientId,
269
+ clientSecret,
270
+ userName,
271
+ ownerId,
272
+ wsUrl,
273
+ wsOptions,
274
+ reconnectInterval,
275
+ maxReconnectAttempts,
276
+ maxAuthFailureAttempts,
277
+ requestTimeout,
278
+ } = {}) {
279
+ this.clientId = nonEmptyString(clientId) ? clientId : undefined;
280
+ this.clientSecret = nonEmptyString(clientSecret) ? clientSecret : undefined;
281
+ this.ownerId = nonEmptyString(ownerId) ? ownerId : undefined;
282
+ this.userName = nonEmptyString(userName) ? userName : 'Yuri';
283
+ this.wsUrl = wsUrl;
284
+ this.wsOptions = wsOptions;
285
+ this.reconnectInterval = reconnectInterval;
286
+ this.maxReconnectAttempts = maxReconnectAttempts;
287
+ this.maxAuthFailureAttempts = maxAuthFailureAttempts;
288
+ this.requestTimeout = requestTimeout;
289
+ this.chat = null;
290
+ this.client = null;
291
+ this.controller = null;
292
+ this.handle = null;
293
+ this.ready = false;
294
+ this.replaced = false;
295
+ this.fatal = null;
296
+ }
297
+
298
+ // ── Chat SDK Adapter contract ────────────────────────────────────────────
299
+
300
+ async initialize(chat) {
301
+ if (this.client) throw channelError('channel_in_use');
302
+ this.chat = chat ?? null;
303
+ const controller = new AbortController();
304
+ this.controller = controller;
305
+ const handle = await this._open({
306
+ signal: controller.signal,
307
+ onReady: () => {},
308
+ onError: () => {},
309
+ onMessage: (projection, message) => this.chat?.processMessage?.(
310
+ this,
311
+ message.threadId,
312
+ () => Promise.resolve(message),
313
+ ),
314
+ });
315
+ this.handle = handle;
316
+ void handle.done.then(() => {
317
+ if (this.handle === handle) {
318
+ this.handle = null;
319
+ this.controller = null;
320
+ void handle.close();
321
+ }
322
+ });
323
+ }
324
+
325
+ encodeThreadId(data) {
326
+ const chatType = data?.chatType === 'group' ? 'group' : 'private';
327
+ const id = data?.id ?? data?.chatId;
328
+ if (!nonEmptyString(id)) throw channelError('invalid_response');
329
+ return threadIdOf(chatType, id);
330
+ }
331
+
332
+ decodeThreadId(threadId) {
333
+ return decodeThreadId(threadId);
334
+ }
335
+
336
+ channelIdFromThreadId(threadId) {
337
+ return decodeThreadId(threadId).id;
338
+ }
339
+
340
+ isDM(threadId) {
341
+ return decodeThreadId(threadId).chatType === 'private';
342
+ }
343
+
344
+ openDM(userId) {
345
+ return threadIdOf('private', userId);
346
+ }
347
+
348
+ async handleWebhook() {
349
+ return new Response(JSON.stringify({ error: 'wecom adapter is long-connection only; webhook not supported' }), {
350
+ status: 501,
351
+ headers: { 'content-type': 'application/json' },
352
+ });
353
+ }
354
+
355
+ parseMessage(raw) {
356
+ const data = readBody(raw?.body ?? raw);
357
+ if (!data) throw channelError('invalid_response');
358
+ return buildMessage(data);
359
+ }
360
+
361
+ renderFormatted(content) {
362
+ if (typeof content === 'string') return content;
363
+ if (content && typeof content === 'object' && content.type === 'root') return stringifyMarkdown(content);
364
+ return messageText(content);
365
+ }
366
+
367
+ async postMessage(threadId, message) {
368
+ const { chatType, id } = decodeThreadId(threadId);
369
+ if (chatType !== 'private') {
370
+ throw new NotImplementedError('wecom: group messages are not supported; only the owner private chat', 'postMessage');
371
+ }
372
+ if (this.ownerId && id !== this.ownerId) throw channelError('invalid_response');
373
+ const text = messageText(message);
374
+ const ack = await this.send({ config: { clientID: this.clientId, clientSecret: this.clientSecret, ownerID: this.ownerId }, target: { userID: id }, text });
375
+ return { id: ack.headers?.req_id ?? '', threadId, raw: {} };
376
+ }
377
+
378
+ async editMessage() {
379
+ throw new NotImplementedError('wecom: editMessage is not supported', 'editMessage');
380
+ }
381
+
382
+ async deleteMessage() {
383
+ throw new NotImplementedError('wecom: deleteMessage is not supported', 'deleteMessage');
384
+ }
385
+
386
+ async fetchMessages() {
387
+ throw new NotImplementedError('wecom: fetchMessages is not supported', 'fetchMessages');
388
+ }
389
+
390
+ async fetchThread() {
391
+ throw new NotImplementedError('wecom: fetchThread is not supported', 'fetchThread');
392
+ }
393
+
394
+ async addReaction() {
395
+ throw new NotImplementedError('wecom: addReaction is not supported', 'addReaction');
396
+ }
397
+
398
+ async removeReaction() {
399
+ throw new NotImplementedError('wecom: removeReaction is not supported', 'removeReaction');
400
+ }
401
+
402
+ async startTyping() {
403
+ throw new NotImplementedError('wecom: typing indicators are not supported', 'startTyping');
404
+ }
405
+
406
+ async disconnect() {
407
+ this.controller?.abort();
408
+ const handle = this.handle;
409
+ this.handle = null;
410
+ this.controller = null;
411
+ await handle?.close?.();
412
+ }
413
+
414
+ // ── Yuri channel bridge ─────────────────────────────────────────────────
415
+
416
+ async connect({ config, signal, onReady, onMessage, onError } = {}) {
417
+ const normalized = requireConfig(config);
418
+ if ((this.ownerId ?? '') !== (normalized.ownerID ?? '')) throw channelError('invalid_response');
419
+ if (this.client) throw channelError('channel_in_use');
420
+
421
+ const controller = new AbortController();
422
+ const forwardAbort = () => controller.abort();
423
+ if (signal?.aborted) controller.abort();
424
+ else signal?.addEventListener('abort', forwardAbort, { once: true });
425
+ this.controller = controller;
426
+
427
+ try {
428
+ const handle = await this._open({
429
+ signal: controller.signal,
430
+ onReady,
431
+ onError,
432
+ onMessage: (projection) => onMessage?.(projection),
433
+ });
434
+ this.handle = handle;
435
+ await handle.done;
436
+ } finally {
437
+ signal?.removeEventListener('abort', forwardAbort);
438
+ this.controller = null;
439
+ const handle = this.handle;
440
+ this.handle = null;
441
+ await handle?.close?.();
442
+ }
443
+ }
444
+
445
+ async send({ config, target, text, image, signal, beforeSend } = {}) {
446
+ const normalized = requireConfig(config);
447
+ const chatId = this.ownerId || target?.userID;
448
+ if (!nonEmptyString(chatId)) throw channelError('invalid_response');
449
+ // A caller-supplied target can never move an owner-bound assistant.
450
+ if (this.ownerId && target?.userID && target.userID !== this.ownerId) throw channelError('invalid_response');
451
+ if ((this.ownerId ?? '') !== (normalized.ownerID ?? '')) throw channelError('invalid_response');
452
+
453
+ if (signal?.aborted) throw channelError('cancelled');
454
+ const client = this.client;
455
+ if (!client || !client.isConnected || !this.ready) throw channelError('network_error');
456
+
457
+ const content = typeof text === 'string' ? text : '';
458
+ let mediaID;
459
+ if (image) {
460
+ try {
461
+ const uploaded = await withAbort(client.uploadMedia(image.buffer, { type: 'image', filename: image.filename }), signal);
462
+ if (!nonEmptyString(uploaded?.media_id)) throw channelError('delivery_failed');
463
+ mediaID = uploaded.media_id;
464
+ } catch {
465
+ // Uploading a resource never delivers a chat message; a retry is safe.
466
+ throw channelError(signal?.aborted ? 'cancelled' : 'delivery_failed');
467
+ }
468
+ signal?.throwIfAborted();
469
+ if (this.client !== client || !client.isConnected || !this.ready) throw channelError('network_error');
470
+ }
471
+ let frame;
472
+ beforeSend?.();
473
+ try {
474
+ // `sendMessage` resolves only after the platform ACK with errcode 0.
475
+ frame = await withAbort(image ? client.sendMediaMessage(chatId, 'image', mediaID) : client.sendMessage(chatId, {
476
+ msgtype: 'markdown',
477
+ markdown: { content },
478
+ }), signal);
479
+ } catch (error) {
480
+ throw sendError(error) ?? channelError('delivery_unknown', true);
481
+ }
482
+ if (!frame || frame.errcode !== 0) throw channelError('delivery_failed');
483
+ return frame;
484
+ }
485
+
486
+ // ── internals ───────────────────────────────────────────────────────────
487
+
488
+ _createClient() {
489
+ if (!this.clientId || !this.clientSecret) throw channelError('invalid_response');
490
+ return new WSClient({
491
+ botId: this.clientId,
492
+ secret: this.clientSecret,
493
+ ...(nonEmptyString(this.wsUrl) ? { wsUrl: this.wsUrl } : {}),
494
+ ...(this.wsOptions ? { wsOptions: this.wsOptions } : {}),
495
+ ...(this.reconnectInterval != null ? { reconnectInterval: this.reconnectInterval } : {}),
496
+ ...(this.maxReconnectAttempts != null ? { maxReconnectAttempts: this.maxReconnectAttempts } : {}),
497
+ ...(this.maxAuthFailureAttempts != null ? { maxAuthFailureAttempts: this.maxAuthFailureAttempts } : {}),
498
+ ...(this.requestTimeout != null ? { requestTimeout: this.requestTimeout } : {}),
499
+ logger: noopLogger(),
500
+ });
501
+ }
502
+
503
+ _deliver(frame, onMessage, onError) {
504
+ const data = readBody(frame?.body);
505
+ // Group chats are never executed; the runtime remains owner-private only.
506
+ if (!data || data.chatType !== 'private') return;
507
+ if (this.ownerId && data.senderID !== this.ownerId) return;
508
+ const message = buildMessage(data);
509
+ const projection = buildProjection(data);
510
+ let result;
511
+ try {
512
+ result = onMessage?.(projection, message);
513
+ } catch {
514
+ onError?.(channelError('network_error'));
515
+ return;
516
+ }
517
+ if (result && typeof result.then === 'function') {
518
+ result.catch(() => onError?.(channelError('network_error')));
519
+ }
520
+ }
521
+
522
+ async _open({ signal, onReady, onError, onMessage }) {
523
+ const client = this._createClient();
524
+ let closed = false;
525
+ let phase = 'connecting';
526
+ let fatal = null;
527
+ let resolveReady;
528
+ let rejectReady;
529
+ const ready = new Promise((resolve, reject) => {
530
+ resolveReady = resolve;
531
+ rejectReady = reject;
532
+ });
533
+ let resolveDone;
534
+ const done = new Promise((resolve) => { resolveDone = resolve; });
535
+ const cleanups = [];
536
+ let deadline;
537
+ let onAbort;
538
+
539
+ const bind = (event, handler) => {
540
+ client.on(event, handler);
541
+ cleanups.push(() => {
542
+ try {
543
+ client.off?.(event, handler) ?? client.removeListener(event, handler);
544
+ } catch {}
545
+ });
546
+ };
547
+
548
+ const close = async () => {
549
+ if (closed) return;
550
+ closed = true;
551
+ clearTimeout(deadline);
552
+ signal?.removeEventListener('abort', onAbort);
553
+ for (const off of cleanups.splice(0)) off();
554
+ this.client = null;
555
+ this.ready = false;
556
+ resolveDone();
557
+ try {
558
+ client.disconnect();
559
+ } catch {}
560
+ };
561
+
562
+ const settle = (error) => {
563
+ if (closed) return;
564
+ if (error?.code) fatal = error.code;
565
+ if (phase === 'connecting') {
566
+ phase = 'settled';
567
+ rejectReady(error ?? channelError('network_error'));
568
+ } else if (phase === 'live') {
569
+ phase = 'settled';
570
+ resolveDone();
571
+ }
572
+ };
573
+
574
+ this.client = client;
575
+ this.ready = false;
576
+ this.replaced = false;
577
+ this.fatal = null;
578
+
579
+ bind('authenticated', () => {
580
+ if (closed) return;
581
+ clearTimeout(deadline);
582
+ this.ready = true;
583
+ try {
584
+ onReady?.();
585
+ } catch {}
586
+ if (phase === 'connecting') {
587
+ phase = 'live';
588
+ resolveReady();
589
+ }
590
+ });
591
+
592
+ bind('disconnected', (reason) => {
593
+ if (closed) return;
594
+ this.ready = false;
595
+ if (/new connection established/i.test(String(reason ?? ''))) {
596
+ this.replaced = true;
597
+ onError?.(channelError('connection_replaced'));
598
+ settle(channelError('connection_replaced'));
599
+ return;
600
+ }
601
+ if (!this.replaced) onError?.(channelError('network_error'));
602
+ });
603
+
604
+ bind('reconnecting', () => {
605
+ if (closed) return;
606
+ this.ready = false;
607
+ if (!this.replaced) onError?.(channelError('network_error'));
608
+ });
609
+
610
+ // Backup for the explicit server-replaced event.
611
+ bind('event.disconnected_event', () => {
612
+ if (closed) return;
613
+ this.replaced = true;
614
+ onError?.(channelError('connection_replaced'));
615
+ settle(channelError('connection_replaced'));
616
+ });
617
+
618
+ bind('error', (error) => {
619
+ if (closed) return;
620
+ this.ready = false;
621
+ const code = lifecycleCode(error);
622
+ if (code === 'auth_expired') {
623
+ this.fatal = 'auth_expired';
624
+ onError?.(channelError('auth_expired'));
625
+ settle(channelError('auth_expired'));
626
+ return;
627
+ }
628
+ if (code === 'reconnect_exhausted') {
629
+ onError?.(channelError('network_error'));
630
+ settle(channelError('network_error'));
631
+ return;
632
+ }
633
+ onError?.(channelError('network_error'));
634
+ });
635
+
636
+ bind('message', (frame) => {
637
+ if (closed || !this.ready || this.replaced || this.fatal) return;
638
+ this._deliver(frame, onMessage, onError);
639
+ });
640
+
641
+ deadline = setTimeout(() => settle(channelError('network_error')), INIT_TIMEOUT_MS);
642
+ deadline.unref?.();
643
+ onAbort = () => settle(channelError('cancelled'));
644
+ if (signal?.aborted) {
645
+ await close();
646
+ throw channelError('cancelled');
647
+ }
648
+ signal?.addEventListener('abort', onAbort, { once: true });
649
+
650
+ try {
651
+ client.connect();
652
+ } catch (error) {
653
+ await close();
654
+ throw isYuriError(error) ? error : channelError('network_error');
655
+ }
656
+
657
+ try {
658
+ await ready;
659
+ } catch (error) {
660
+ await close();
661
+ throw error;
662
+ }
663
+ if (closed) throw channelError('cancelled');
664
+ return { close, done, fatal: () => fatal };
665
+ }
666
+ }
667
+
668
+ /**
669
+ * Registry-facing factory. One official WSClient per bot credential; a second
670
+ * live connection for the same credential is rejected instead of replacing the
671
+ * first. Different accounts/credentials connect independently.
672
+ */
673
+ export function createWecomSdkAdapter(options = {}) {
674
+ const sessions = new Map();
675
+
676
+ return {
677
+ async connect(args = {}) {
678
+ const config = requireConfig(args.config);
679
+ const key = credentialKey(config.clientID, config.clientSecret);
680
+ if (sessions.has(key)) throw channelError('channel_in_use');
681
+ const adapter = new WecomChatAdapter({
682
+ ...options,
683
+ clientId: config.clientID,
684
+ clientSecret: config.clientSecret,
685
+ ownerId: config.ownerID,
686
+ });
687
+ const entry = { adapter };
688
+ sessions.set(key, entry);
689
+ try {
690
+ await adapter.connect(args);
691
+ } finally {
692
+ if (sessions.get(key) === entry) sessions.delete(key);
693
+ }
694
+ },
695
+
696
+ async send(args = {}) {
697
+ const config = requireConfig(args.config);
698
+ const entry = sessions.get(credentialKey(config.clientID, config.clientSecret));
699
+ if (!entry) throw channelError('network_error');
700
+ await entry.adapter.send(args);
701
+ },
702
+ };
703
+ }