@botharness/im-provider 4.32.0-botharness.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/PROVENANCE.json +25 -0
- package/README.en.md +445 -0
- package/README.md +448 -0
- package/THIRD_PARTY_NOTICES.md +93 -0
- package/assets/dingtalk-menu-template.json +6 -0
- package/assets/logo-dsh-im-chinese-readme-3x2.png +0 -0
- package/assets/logo-dsh-im-connecting-readme-3x2.png +0 -0
- package/assets/logo-dsh-im-connecting-square-v4.png +0 -0
- package/assets/logo-icon.png +0 -0
- package/assets/logo-plugin-message-link-gradient.webp +0 -0
- package/assets/logo-plugin-phone.png +0 -0
- package/assets/logo.png +0 -0
- package/assets/logo_cn.png +0 -0
- package/assets/screenshot-menu-card.png +0 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +20330 -0
- package/lib/index.js +602 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +5 -0
- package/package.json +181 -0
- package/plugin-src/client/access-policy-settings.js +362 -0
- package/plugin-src/client/agent-preset.js +119 -0
- package/plugin-src/client/bot-alias.js +169 -0
- package/plugin-src/client/build.mjs +38 -0
- package/plugin-src/client/channel-card-meta.js +132 -0
- package/plugin-src/client/channel-logos.js +190 -0
- package/plugin-src/client/channels/dingtalk/api.js +267 -0
- package/plugin-src/client/channels/dingtalk/index.js +954 -0
- package/plugin-src/client/channels/dingtalk/styles.js +136 -0
- package/plugin-src/client/channels/discord/api.js +11 -0
- package/plugin-src/client/channels/discord/index.js +25 -0
- package/plugin-src/client/channels/discord/styles.js +19 -0
- package/plugin-src/client/channels/email/api.js +52 -0
- package/plugin-src/client/channels/email/index.js +728 -0
- package/plugin-src/client/channels/email/styles.js +51 -0
- package/plugin-src/client/channels/feishu/api.js +405 -0
- package/plugin-src/client/channels/feishu/group-settings.js +581 -0
- package/plugin-src/client/channels/feishu/index.js +1583 -0
- package/plugin-src/client/channels/feishu/slash-panel-settings.js +322 -0
- package/plugin-src/client/channels/feishu/styles.js +573 -0
- package/plugin-src/client/channels/feishu/voice-editor.js +115 -0
- package/plugin-src/client/channels/feishu/voice-settings.js +71 -0
- package/plugin-src/client/channels/imessage/api.js +12 -0
- package/plugin-src/client/channels/imessage/index.js +46 -0
- package/plugin-src/client/channels/imessage/styles.js +19 -0
- package/plugin-src/client/channels/matrix/api.js +11 -0
- package/plugin-src/client/channels/matrix/index.js +151 -0
- package/plugin-src/client/channels/matrix/styles.js +36 -0
- package/plugin-src/client/channels/office/api.js +46 -0
- package/plugin-src/client/channels/office/index.js +153 -0
- package/plugin-src/client/channels/office/styles.js +50 -0
- package/plugin-src/client/channels/qq/api.js +171 -0
- package/plugin-src/client/channels/qq/index.js +593 -0
- package/plugin-src/client/channels/qq/styles.js +19 -0
- package/plugin-src/client/channels/shared/collapsible-account.js +103 -0
- package/plugin-src/client/channels/shared/token-api.js +124 -0
- package/plugin-src/client/channels/shared/token-channel.js +495 -0
- package/plugin-src/client/channels/slack/api.js +11 -0
- package/plugin-src/client/channels/slack/index.js +131 -0
- package/plugin-src/client/channels/slack/styles.js +34 -0
- package/plugin-src/client/channels/telegram/api.js +11 -0
- package/plugin-src/client/channels/telegram/index.js +28 -0
- package/plugin-src/client/channels/telegram/styles.js +31 -0
- package/plugin-src/client/channels/telegram/thinking-traces.js +25 -0
- package/plugin-src/client/channels/wecom/api.js +160 -0
- package/plugin-src/client/channels/wecom/index.js +625 -0
- package/plugin-src/client/channels/wecom/styles.js +19 -0
- package/plugin-src/client/channels/wecom-app/api.js +132 -0
- package/plugin-src/client/channels/wecom-app/index.js +634 -0
- package/plugin-src/client/channels/wecom-app/styles.js +25 -0
- package/plugin-src/client/channels/weixin/api.js +211 -0
- package/plugin-src/client/channels/weixin/connection-error.js +1 -0
- package/plugin-src/client/channels/weixin/index.js +801 -0
- package/plugin-src/client/channels/weixin/styles.js +115 -0
- package/plugin-src/client/channels/whatsapp/api.js +152 -0
- package/plugin-src/client/channels/whatsapp/index.js +609 -0
- package/plugin-src/client/channels/whatsapp/styles.js +19 -0
- package/plugin-src/client/connection-error.js +87 -0
- package/plugin-src/client/context-enhancement.js +415 -0
- package/plugin-src/client/credential-binding.js +118 -0
- package/plugin-src/client/delivery-settings.js +905 -0
- package/plugin-src/client/global-settings.js +433 -0
- package/plugin-src/client/i18n.js +1314 -0
- package/plugin-src/client/index.js +624 -0
- package/plugin-src/client/interface-language.js +89 -0
- package/plugin-src/client/last-message-error.js +18 -0
- package/plugin-src/client/lifecycle.js +86 -0
- package/plugin-src/client/loopback-recovery.js +75 -0
- package/plugin-src/client/model-setting.js +172 -0
- package/plugin-src/client/panel-error-boundary.js +21 -0
- package/plugin-src/client/plugin-page.js +51 -0
- package/plugin-src/client/session-channel-logos.js +243 -0
- package/plugin-src/client/styles.js +770 -0
- package/plugin-src/client/update-panel.js +14 -0
- package/plugin-src/client/workspace-directory-picker.js +280 -0
- package/plugin-src/client/workspace-editor.js +69 -0
- package/plugin-src/client/workspace-snapshot-fence.js +28 -0
- package/plugin-src/host/build.mjs +52 -0
- package/plugin-src/host/channels/dingtalk/connection-supervisor.mjs +130 -0
- package/plugin-src/host/channels/dingtalk/index.mjs +35 -0
- package/plugin-src/host/channels/dingtalk/production.mjs +193 -0
- package/plugin-src/host/channels/dingtalk/rpc.mjs +359 -0
- package/plugin-src/host/channels/discord/index.mjs +33 -0
- package/plugin-src/host/channels/discord/production.mjs +17 -0
- package/plugin-src/host/channels/discord/rpc.mjs +21 -0
- package/plugin-src/host/channels/email/availability.mjs +60 -0
- package/plugin-src/host/channels/email/index.mjs +36 -0
- package/plugin-src/host/channels/email/production.mjs +58 -0
- package/plugin-src/host/channels/email/rpc.mjs +163 -0
- package/plugin-src/host/channels/feishu/connection-supervisor.mjs +167 -0
- package/plugin-src/host/channels/feishu/controller.mjs +172 -0
- package/plugin-src/host/channels/feishu/credential-store.mjs +84 -0
- package/plugin-src/host/channels/feishu/index.mjs +69 -0
- package/plugin-src/host/channels/feishu/production.mjs +318 -0
- package/plugin-src/host/channels/feishu/rpc.mjs +863 -0
- package/plugin-src/host/channels/imessage/index.mjs +21 -0
- package/plugin-src/host/channels/imessage/production.mjs +13 -0
- package/plugin-src/host/channels/imessage/rpc.mjs +78 -0
- package/plugin-src/host/channels/matrix/index.mjs +31 -0
- package/plugin-src/host/channels/matrix/production.mjs +241 -0
- package/plugin-src/host/channels/matrix/rpc.mjs +228 -0
- package/plugin-src/host/channels/office/index.mjs +14 -0
- package/plugin-src/host/channels/office/production.mjs +45 -0
- package/plugin-src/host/channels/office/rpc.mjs +51 -0
- package/plugin-src/host/channels/qq/connection-supervisor.mjs +124 -0
- package/plugin-src/host/channels/qq/index.mjs +28 -0
- package/plugin-src/host/channels/qq/production.mjs +181 -0
- package/plugin-src/host/channels/qq/rpc.mjs +250 -0
- package/plugin-src/host/channels/shared/access-policy-production.mjs +137 -0
- package/plugin-src/host/channels/shared/access-policy-rpc.mjs +17 -0
- package/plugin-src/host/channels/shared/agent-preset-rpc.mjs +25 -0
- package/plugin-src/host/channels/shared/bot-alias-rpc.mjs +15 -0
- package/plugin-src/host/channels/shared/connection-supervisor.mjs +133 -0
- package/plugin-src/host/channels/shared/context-enhancement-rpc.mjs +17 -0
- package/plugin-src/host/channels/shared/model-setting-rpc.mjs +18 -0
- package/plugin-src/host/channels/shared/production.mjs +237 -0
- package/plugin-src/host/channels/shared/rpc.mjs +226 -0
- package/plugin-src/host/channels/shared/startup-error.mjs +55 -0
- package/plugin-src/host/channels/shared/startup.mjs +76 -0
- package/plugin-src/host/channels/shared/thinking-traces-rpc.mjs +11 -0
- package/plugin-src/host/channels/shared/workspace-rpc.mjs +31 -0
- package/plugin-src/host/channels/slack/index.mjs +31 -0
- package/plugin-src/host/channels/slack/production.mjs +176 -0
- package/plugin-src/host/channels/slack/rpc.mjs +221 -0
- package/plugin-src/host/channels/telegram/index.mjs +33 -0
- package/plugin-src/host/channels/telegram/production.mjs +19 -0
- package/plugin-src/host/channels/telegram/rpc.mjs +22 -0
- package/plugin-src/host/channels/wecom/connection-supervisor.mjs +124 -0
- package/plugin-src/host/channels/wecom/index.mjs +34 -0
- package/plugin-src/host/channels/wecom/production.mjs +187 -0
- package/plugin-src/host/channels/wecom/rpc.mjs +255 -0
- package/plugin-src/host/channels/wecom-app/index.mjs +33 -0
- package/plugin-src/host/channels/wecom-app/production.mjs +221 -0
- package/plugin-src/host/channels/wecom-app/rpc.mjs +235 -0
- package/plugin-src/host/channels/weixin/connection-supervisor.mjs +139 -0
- package/plugin-src/host/channels/weixin/index.mjs +44 -0
- package/plugin-src/host/channels/weixin/production.mjs +257 -0
- package/plugin-src/host/channels/weixin/rpc.mjs +285 -0
- package/plugin-src/host/channels/whatsapp/index.mjs +33 -0
- package/plugin-src/host/channels/whatsapp/production.mjs +198 -0
- package/plugin-src/host/channels/whatsapp/rpc.mjs +242 -0
- package/plugin-src/host/delivery-adapter.mjs +388 -0
- package/plugin-src/host/delivery-http.mjs +132 -0
- package/plugin-src/host/delivery-rpc.mjs +173 -0
- package/plugin-src/host/delivery-service.mjs +552 -0
- package/plugin-src/host/delivery-suggestions.mjs +198 -0
- package/plugin-src/host/harness-command-executor.mjs +48 -0
- package/plugin-src/host/harness-connection.mjs +20 -0
- package/plugin-src/host/harness-session-coordinator.mjs +183 -0
- package/plugin-src/host/host-language-rpc.mjs +71 -0
- package/plugin-src/host/host-language.mjs +157 -0
- package/plugin-src/host/image-input-rpc.mjs +24 -0
- package/plugin-src/host/inbound-ttl-rpc.mjs +86 -0
- package/plugin-src/host/inbound-ttl-runtime.mjs +85 -0
- package/plugin-src/host/inbound-ttl-service.mjs +179 -0
- package/plugin-src/host/index.mjs +224 -0
- package/plugin-src/host/injected-context.mjs +104 -0
- package/plugin-src/host/lark-sdk-handshake-patch.mjs +181 -0
- package/plugin-src/host/modern-harness-api.mjs +738 -0
- package/plugin-src/host/rpc-authority.mjs +12 -0
- package/plugin-src/host/session-sync-coordinator.mjs +233 -0
- package/plugin-src/host/session-title-prefix.mjs +122 -0
- package/plugin-src/host/update-policy.mjs +31 -0
- package/plugin-src/host/update-rpc.mjs +16 -0
- package/plugin-src/host/update-runtime.mjs +339 -0
- package/plugin-src/host/update-service.mjs +392 -0
- package/plugin-src/management-rpc.mjs +87 -0
- package/src/channels/dingtalk/config-store.mjs +284 -0
- package/src/channels/dingtalk/connection-error.mjs +292 -0
- package/src/channels/dingtalk/device-auth.mjs +240 -0
- package/src/channels/dingtalk/dingtalk-api.mjs +1140 -0
- package/src/channels/dingtalk/dingtalk-bridge.mjs +1889 -0
- package/src/channels/dingtalk/dingtalk-card-stream.mjs +242 -0
- package/src/channels/dingtalk/dingtalk-controller.mjs +852 -0
- package/src/channels/dingtalk/dingtalk-menu.mjs +95 -0
- package/src/channels/dingtalk/dingtalk-runtime.mjs +482 -0
- package/src/channels/dingtalk/harness-client.mjs +19 -0
- package/src/channels/dingtalk/state-store.mjs +325 -0
- package/src/channels/discord/config-store.mjs +25 -0
- package/src/channels/discord/discord-api.mjs +347 -0
- package/src/channels/discord/discord-bridge.mjs +16 -0
- package/src/channels/discord/discord-controller.mjs +16 -0
- package/src/channels/discord/discord-runtime.mjs +974 -0
- package/src/channels/discord/harness-client.mjs +11 -0
- package/src/channels/discord/state-store.mjs +3 -0
- package/src/channels/email/config-store.mjs +194 -0
- package/src/channels/email/email-api.mjs +20 -0
- package/src/channels/email/email-bridge.mjs +17 -0
- package/src/channels/email/email-controller.mjs +824 -0
- package/src/channels/email/email-runtime.mjs +699 -0
- package/src/channels/email/harness-client.mjs +7 -0
- package/src/channels/email/mail-format.mjs +91 -0
- package/src/channels/email/state-store.mjs +176 -0
- package/src/channels/email/transport.mjs +64 -0
- package/src/channels/email/transports/agent-mail.mjs +604 -0
- package/src/channels/email/transports/agently-cli.mjs +288 -0
- package/src/channels/email/transports/imap-smtp.mjs +165 -0
- package/src/channels/feishu/bridge.mjs +6286 -0
- package/src/channels/feishu/config.mjs +71 -0
- package/src/channels/feishu/external-consumer.mjs +77 -0
- package/src/channels/feishu/external-files.mjs +111 -0
- package/src/channels/feishu/feishu-app.mjs +54 -0
- package/src/channels/feishu/feishu-cards.mjs +1285 -0
- package/src/channels/feishu/feishu-channel.mjs +651 -0
- package/src/channels/feishu/feishu-runtime.mjs +950 -0
- package/src/channels/feishu/group-message-permission-manager.mjs +72 -0
- package/src/channels/feishu/group-response-mode.mjs +15 -0
- package/src/channels/feishu/harness-client.mjs +19 -0
- package/src/channels/feishu/history-reader.mjs +77 -0
- package/src/channels/feishu/live-cot.mjs +260 -0
- package/src/channels/feishu/message-utils.mjs +613 -0
- package/src/channels/feishu/multi-bot-controller.mjs +1588 -0
- package/src/channels/feishu/nearby-history.mjs +72 -0
- package/src/channels/feishu/plugin-config-store.mjs +216 -0
- package/src/channels/feishu/plugin-controller.mjs +254 -0
- package/src/channels/feishu/registration-manager.mjs +349 -0
- package/src/channels/feishu/repair-manager.mjs +138 -0
- package/src/channels/feishu/reply-context.mjs +22 -0
- package/src/channels/feishu/slash-command-panel.mjs +155 -0
- package/src/channels/feishu/slash-command-registry.mjs +495 -0
- package/src/channels/feishu/state-store.mjs +214 -0
- package/src/channels/feishu/step-push-mode.mjs +25 -0
- package/src/channels/feishu/voice-config.mjs +34 -0
- package/src/channels/feishu/voice.mjs +134 -0
- package/src/channels/imessage/config-store.mjs +24 -0
- package/src/channels/imessage/controller.mjs +37 -0
- package/src/channels/imessage/harness-client.mjs +7 -0
- package/src/channels/imessage/imessage-api.mjs +194 -0
- package/src/channels/imessage/imessage-bridge.mjs +16 -0
- package/src/channels/imessage/runtime.mjs +102 -0
- package/src/channels/imessage/state-store.mjs +3 -0
- package/src/channels/matrix/matrix-api.mjs +696 -0
- package/src/channels/matrix/matrix-bridge.mjs +20 -0
- package/src/channels/matrix/matrix-config-store.mjs +368 -0
- package/src/channels/matrix/matrix-controller.mjs +404 -0
- package/src/channels/matrix/matrix-crypto-store.mjs +279 -0
- package/src/channels/matrix/matrix-crypto.mjs +1014 -0
- package/src/channels/matrix/matrix-harness-client.mjs +11 -0
- package/src/channels/matrix/matrix-normalize.mjs +357 -0
- package/src/channels/matrix/matrix-rich-text.mjs +313 -0
- package/src/channels/matrix/matrix-room-history.mjs +316 -0
- package/src/channels/matrix/matrix-runtime.mjs +1014 -0
- package/src/channels/office/config-store.mjs +107 -0
- package/src/channels/office/office-controller.mjs +178 -0
- package/src/channels/office/office-job-executor.mjs +391 -0
- package/src/channels/office/office-runtime.mjs +175 -0
- package/src/channels/office/office-transport.mjs +171 -0
- package/src/channels/office/protocol.mjs +43 -0
- package/src/channels/qq/config-store.mjs +173 -0
- package/src/channels/qq/harness-client.mjs +11 -0
- package/src/channels/qq/markdown-reply.mjs +446 -0
- package/src/channels/qq/qq-bridge.mjs +1507 -0
- package/src/channels/qq/qq-controller.mjs +514 -0
- package/src/channels/qq/qq-menu.mjs +208 -0
- package/src/channels/qq/qq-runtime.mjs +303 -0
- package/src/channels/qq/qr-auth.mjs +24 -0
- package/src/channels/qq/state-error.mjs +17 -0
- package/src/channels/qq/state-store.mjs +143 -0
- package/src/channels/shared/access-policy.mjs +210 -0
- package/src/channels/shared/agent-preset.mjs +76 -0
- package/src/channels/shared/batch-input.mjs +229 -0
- package/src/channels/shared/bot-alias.mjs +29 -0
- package/src/channels/shared/bot-workspace-store.mjs +2383 -0
- package/src/channels/shared/command-catalog.mjs +107 -0
- package/src/channels/shared/command-permission.mjs +32 -0
- package/src/channels/shared/compact-command.mjs +109 -0
- package/src/channels/shared/config-read-error.mjs +24 -0
- package/src/channels/shared/connection-error.mjs +191 -0
- package/src/channels/shared/connection-test.mjs +58 -0
- package/src/channels/shared/context-enhancement.mjs +372 -0
- package/src/channels/shared/control-command.mjs +111 -0
- package/src/channels/shared/conversation-state-store.mjs +165 -0
- package/src/channels/shared/default-workspace.mjs +31 -0
- package/src/channels/shared/deferred-delivery-coordinator.mjs +241 -0
- package/src/channels/shared/deferred-delivery.mjs +161 -0
- package/src/channels/shared/deferred-state.mjs +53 -0
- package/src/channels/shared/diagnostic-details.mjs +95 -0
- package/src/channels/shared/editable-message-stream.mjs +100 -0
- package/src/channels/shared/exclusive-inbound-consumers.mjs +71 -0
- package/src/channels/shared/file-download.mjs +64 -0
- package/src/channels/shared/harness-approval.mjs +508 -0
- package/src/channels/shared/harness-client.mjs +2143 -0
- package/src/channels/shared/harness-mux.mjs +123 -0
- package/src/channels/shared/harness-question.mjs +95 -0
- package/src/channels/shared/harness-session-binding.mjs +119 -0
- package/src/channels/shared/history-command.mjs +193 -0
- package/src/channels/shared/i18n-en/diagnostics.mjs +55 -0
- package/src/channels/shared/i18n-en/dingtalk.mjs +81 -0
- package/src/channels/shared/i18n-en/discord.mjs +10 -0
- package/src/channels/shared/i18n-en/email.mjs +25 -0
- package/src/channels/shared/i18n-en/feishu.mjs +404 -0
- package/src/channels/shared/i18n-en/image-input.mjs +18 -0
- package/src/channels/shared/i18n-en/matrix.mjs +85 -0
- package/src/channels/shared/i18n-en/office.mjs +23 -0
- package/src/channels/shared/i18n-en/qq.mjs +96 -0
- package/src/channels/shared/i18n-en/shared-a.mjs +241 -0
- package/src/channels/shared/i18n-en/shared-b.mjs +263 -0
- package/src/channels/shared/i18n-en/shared-c.mjs +203 -0
- package/src/channels/shared/i18n-en/slack.mjs +27 -0
- package/src/channels/shared/i18n-en/telegram.mjs +27 -0
- package/src/channels/shared/i18n-en/wecom-app.mjs +33 -0
- package/src/channels/shared/i18n-en/wecom.mjs +62 -0
- package/src/channels/shared/i18n-en/weixin.mjs +88 -0
- package/src/channels/shared/i18n-en/whatsapp.mjs +17 -0
- package/src/channels/shared/i18n-en.mjs +45 -0
- package/src/channels/shared/i18n.mjs +78 -0
- package/src/channels/shared/im-source-guidance.mjs +65 -0
- package/src/channels/shared/image-input-policy.mjs +35 -0
- package/src/channels/shared/image-input-settings-store.mjs +60 -0
- package/src/channels/shared/image-input.mjs +124 -0
- package/src/channels/shared/image-prompt.mjs +360 -0
- package/src/channels/shared/inbound-access.mjs +43 -0
- package/src/channels/shared/inbound-file.mjs +323 -0
- package/src/channels/shared/inbound-ttl-store.mjs +110 -0
- package/src/channels/shared/inbound-ttl.mjs +22 -0
- package/src/channels/shared/injected-context.mjs +362 -0
- package/src/channels/shared/interface-language-store.mjs +127 -0
- package/src/channels/shared/interface-language.mjs +51 -0
- package/src/channels/shared/message-failure.mjs +257 -0
- package/src/channels/shared/model-command.mjs +741 -0
- package/src/channels/shared/model-setting.mjs +145 -0
- package/src/channels/shared/preset-command.mjs +308 -0
- package/src/channels/shared/semantic/artifact-delivery.mjs +177 -0
- package/src/channels/shared/semantic/artifact.mjs +750 -0
- package/src/channels/shared/semantic/delivery.mjs +193 -0
- package/src/channels/shared/semantic/reply-reference.mjs +148 -0
- package/src/channels/shared/session-binding-lock.mjs +40 -0
- package/src/channels/shared/session-channel-labels.mjs +28 -0
- package/src/channels/shared/session-reply-recovery.mjs +104 -0
- package/src/channels/shared/session-sync-registry.mjs +22 -0
- package/src/channels/shared/session-title.mjs +74 -0
- package/src/channels/shared/status-reaction.mjs +107 -0
- package/src/channels/shared/text-harness-bridge.mjs +1623 -0
- package/src/channels/shared/token-bot-controller.mjs +417 -0
- package/src/channels/shared/token-config-store.mjs +208 -0
- package/src/channels/shared/workspace-command.mjs +532 -0
- package/src/channels/shared/workspace-session.mjs +196 -0
- package/src/channels/slack/config-store.mjs +177 -0
- package/src/channels/slack/external-consumer.mjs +80 -0
- package/src/channels/slack/external-files.mjs +90 -0
- package/src/channels/slack/harness-client.mjs +11 -0
- package/src/channels/slack/history-reader.mjs +203 -0
- package/src/channels/slack/manifest.mjs +37 -0
- package/src/channels/slack/slack-api.mjs +636 -0
- package/src/channels/slack/slack-bridge.mjs +20 -0
- package/src/channels/slack/slack-controller.mjs +468 -0
- package/src/channels/slack/slack-runtime.mjs +879 -0
- package/src/channels/slack/state-store.mjs +3 -0
- package/src/channels/telegram/config-store.mjs +89 -0
- package/src/channels/telegram/harness-client.mjs +11 -0
- package/src/channels/telegram/state-store.mjs +3 -0
- package/src/channels/telegram/telegram-api.mjs +486 -0
- package/src/channels/telegram/telegram-bridge.mjs +81 -0
- package/src/channels/telegram/telegram-controller.mjs +52 -0
- package/src/channels/telegram/telegram-http.mjs +21 -0
- package/src/channels/telegram/telegram-rich-message.mjs +149 -0
- package/src/channels/telegram/telegram-runtime.mjs +1471 -0
- package/src/channels/wecom/config-store.mjs +172 -0
- package/src/channels/wecom/harness-client.mjs +11 -0
- package/src/channels/wecom/qr-auth.mjs +95 -0
- package/src/channels/wecom/send-error.mjs +31 -0
- package/src/channels/wecom/state-store.mjs +107 -0
- package/src/channels/wecom/wecom-bridge.mjs +1833 -0
- package/src/channels/wecom/wecom-cards.mjs +101 -0
- package/src/channels/wecom/wecom-controller.mjs +530 -0
- package/src/channels/wecom/wecom-runtime.mjs +269 -0
- package/src/channels/wecom-app/callback-server.mjs +471 -0
- package/src/channels/wecom-app/config-store.mjs +242 -0
- package/src/channels/wecom-app/harness-client.mjs +11 -0
- package/src/channels/wecom-app/state-store.mjs +107 -0
- package/src/channels/wecom-app/wecom-app-api.mjs +432 -0
- package/src/channels/wecom-app/wecom-app-bridge.mjs +1072 -0
- package/src/channels/wecom-app/wecom-app-controller.mjs +453 -0
- package/src/channels/wecom-app/wecom-app-runtime.mjs +222 -0
- package/src/channels/weixin/config-store.mjs +192 -0
- package/src/channels/weixin/connection-error.en.mjs +137 -0
- package/src/channels/weixin/connection-error.mjs +153 -0
- package/src/channels/weixin/diagnostic-details.mjs +1 -0
- package/src/channels/weixin/harness-client.mjs +19 -0
- package/src/channels/weixin/state-store.mjs +291 -0
- package/src/channels/weixin/weixin-api.mjs +949 -0
- package/src/channels/weixin/weixin-bridge.mjs +1537 -0
- package/src/channels/weixin/weixin-controller.mjs +669 -0
- package/src/channels/weixin/weixin-runtime.mjs +416 -0
- package/src/channels/whatsapp/config-store.mjs +210 -0
- package/src/channels/whatsapp/harness-client.mjs +11 -0
- package/src/channels/whatsapp/state-store.mjs +3 -0
- package/src/channels/whatsapp/whatsapp-bridge.mjs +18 -0
- package/src/channels/whatsapp/whatsapp-controller.mjs +470 -0
- package/src/channels/whatsapp/whatsapp-runtime.mjs +917 -0
- package/src/channels/whatsapp/whatsapp-web-session.mjs +214 -0
|
@@ -0,0 +1,974 @@
|
|
|
1
|
+
import { extractConnectionEvidence, createConnectionDiagnostics, atConnectionStage } from '../shared/connection-error.mjs';
|
|
2
|
+
import { createEditableMessageStream, splitMessageText } from '../shared/editable-message-stream.mjs';
|
|
3
|
+
import { fetchFileStream } from '../shared/file-download.mjs';
|
|
4
|
+
import { fetchImageBuffer } from '../shared/image-prompt.mjs';
|
|
5
|
+
import { t } from '../shared/i18n.mjs';
|
|
6
|
+
import { captureContextEnhancement } from '../shared/context-enhancement.mjs';
|
|
7
|
+
import { evaluateInboundAccess } from '../shared/inbound-access.mjs';
|
|
8
|
+
import { DiscordApi } from './discord-api.mjs';
|
|
9
|
+
import { createDiscordBridgeStatus, DiscordHarnessBridge } from './discord-bridge.mjs';
|
|
10
|
+
|
|
11
|
+
const DISCORD_GATEWAY_INTENTS = (1 << 0) | (1 << 9) | (1 << 12) | (1 << 15);
|
|
12
|
+
const THREAD_RECOVERY_TIMEOUT_MS = 5_000;
|
|
13
|
+
const RECONNECT_DELAYS_MS = Object.freeze([1_000, 3_000, 5_000, 10_000, 30_000]);
|
|
14
|
+
const GUILD_TEXT = 0;
|
|
15
|
+
const GUILD_ANNOUNCEMENT = 5;
|
|
16
|
+
const ANNOUNCEMENT_THREAD = 10;
|
|
17
|
+
const PUBLIC_THREAD = 11;
|
|
18
|
+
const PRIVATE_THREAD = 12;
|
|
19
|
+
const THREAD_TYPES = new Set([ANNOUNCEMENT_THREAD, PUBLIC_THREAD, PRIVATE_THREAD]);
|
|
20
|
+
const IMAGE_MEDIA_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
|
|
21
|
+
const IMAGE_FILE_TYPES = new Map([
|
|
22
|
+
['.jpg', 'image/jpeg'],
|
|
23
|
+
['.jpeg', 'image/jpeg'],
|
|
24
|
+
['.png', 'image/png'],
|
|
25
|
+
['.webp', 'image/webp'],
|
|
26
|
+
['.gif', 'image/gif'],
|
|
27
|
+
]);
|
|
28
|
+
const DISCORD_IMAGE_HOSTS = Object.freeze(['cdn.discordapp.com']);
|
|
29
|
+
|
|
30
|
+
function socketUrl(value) {
|
|
31
|
+
const url = new URL(value);
|
|
32
|
+
if (url.protocol !== 'wss:') throw new Error('Discord returned an insecure Gateway URL');
|
|
33
|
+
url.searchParams.set('v', '10');
|
|
34
|
+
url.searchParams.set('encoding', 'json');
|
|
35
|
+
return url.href;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function addSocketListener(socket, event, listener) {
|
|
39
|
+
if (typeof socket.addEventListener === 'function') socket.addEventListener(event, listener);
|
|
40
|
+
else if (typeof socket.on === 'function') socket.on(event, listener);
|
|
41
|
+
else throw new TypeError('Discord WebSocket does not support events');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function eventData(event) {
|
|
45
|
+
if (typeof event === 'string') return event;
|
|
46
|
+
if (typeof event?.data === 'string') return event.data;
|
|
47
|
+
if (Buffer.isBuffer(event)) return event.toString('utf8');
|
|
48
|
+
if (Buffer.isBuffer(event?.data)) return event.data.toString('utf8');
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function gatewayCloseError(code) {
|
|
53
|
+
if (code === 4004) {
|
|
54
|
+
const error = new Error(t('Discord Bot Token 无效,请重新填写。'));
|
|
55
|
+
error.code = 'discord-401';
|
|
56
|
+
return error;
|
|
57
|
+
}
|
|
58
|
+
if (code === 4013 || code === 4014) {
|
|
59
|
+
const error = new Error(t('Discord Gateway Intents 配置不正确,请检查 Developer Portal 的 Bot 设置。'));
|
|
60
|
+
error.code = 'discord-intents';
|
|
61
|
+
return error;
|
|
62
|
+
}
|
|
63
|
+
const error = new Error(`Discord Gateway closed (${code || 'unknown'})`);
|
|
64
|
+
error.code = 'discord-gateway-closed';
|
|
65
|
+
return error;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function stripBotMention(text, botId) {
|
|
69
|
+
if (typeof text !== 'string') return '';
|
|
70
|
+
return text
|
|
71
|
+
.split(`<@${botId}>`).join('')
|
|
72
|
+
.split(`<@!${botId}>`).join('')
|
|
73
|
+
.trim();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function cleanThreadName(message, botId) {
|
|
77
|
+
const name = stripBotMention(message?.content ?? '', botId).replace(/\s+/g, ' ').trim()
|
|
78
|
+
|| 'DeepSeek Harness';
|
|
79
|
+
return [...name].slice(0, 100).join('');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function isThreadChannel(channel) {
|
|
83
|
+
return THREAD_TYPES.has(Number(channel?.type));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function isThreadFromMessage(channel, message) {
|
|
87
|
+
return isThreadChannel(channel)
|
|
88
|
+
&& String(channel?.id ?? '') === String(message?.id ?? '')
|
|
89
|
+
&& String(channel?.parent_id ?? '') === String(message?.channel_id ?? '');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function rememberChannel(channel, callback) {
|
|
93
|
+
if (channel?.id) callback?.(channel);
|
|
94
|
+
return channel;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function withConversationRoute(normalized, channel, botId, {
|
|
98
|
+
fromSourceMessage = false,
|
|
99
|
+
fallback = null,
|
|
100
|
+
notice = null,
|
|
101
|
+
} = {}) {
|
|
102
|
+
const channelId = String(channel?.id ?? normalized.conversationId);
|
|
103
|
+
const thread = isThreadChannel(channel);
|
|
104
|
+
const managed = thread && String(channel?.owner_id ?? '') === String(botId);
|
|
105
|
+
const parentId = thread && channel?.parent_id ? String(channel.parent_id) : channelId;
|
|
106
|
+
return {
|
|
107
|
+
...normalized,
|
|
108
|
+
conversationId: channelId,
|
|
109
|
+
addressed: normalized.addressed || managed,
|
|
110
|
+
requiresMention: thread ? !managed : normalized.kind === 'group',
|
|
111
|
+
replyTarget: {
|
|
112
|
+
channelId,
|
|
113
|
+
...(!fromSourceMessage && normalized.replyTarget?.replyToMessageId
|
|
114
|
+
? { replyToMessageId: normalized.replyTarget.replyToMessageId }
|
|
115
|
+
: {}),
|
|
116
|
+
...(notice ? { notice } : {}),
|
|
117
|
+
},
|
|
118
|
+
connectionTestTarget: { channelId },
|
|
119
|
+
conversationRoute: {
|
|
120
|
+
peerId: parentId,
|
|
121
|
+
...(thread ? { threadId: channelId, managed } : {}),
|
|
122
|
+
...(fallback ? { fallback } : {}),
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function uncertainThreadCreate(error) {
|
|
128
|
+
const status = Number(error?.status);
|
|
129
|
+
return !Number.isInteger(status) || status >= 500;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function threadCreateUncertain(cause) {
|
|
133
|
+
const error = new Error('Discord Thread creation result is uncertain', { cause });
|
|
134
|
+
error.code = 'discord-thread-create-uncertain';
|
|
135
|
+
return error;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function findCreatedThread(api, message, { signal, onChannel } = {}) {
|
|
139
|
+
try {
|
|
140
|
+
const channel = rememberChannel(await api.getChannel({
|
|
141
|
+
channelId: String(message.id),
|
|
142
|
+
signal,
|
|
143
|
+
}), onChannel);
|
|
144
|
+
return isThreadFromMessage(channel, message) ? channel : null;
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (error?.status === 404) return null;
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function sendThreadUncertainNotice(api, normalized, signal) {
|
|
152
|
+
try {
|
|
153
|
+
await api.createMessage({
|
|
154
|
+
channelId: normalized.replyTarget.channelId,
|
|
155
|
+
replyToMessageId: normalized.replyTarget.replyToMessageId,
|
|
156
|
+
content: t('Thread 创建结果暂时无法确认。若已创建,请在对应 Thread 中重试;若未创建,请稍后重新 @机器人。'),
|
|
157
|
+
signal,
|
|
158
|
+
});
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (signal?.aborted) throw signal.reason ?? error;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function attachmentMediaType(attachment) {
|
|
165
|
+
const value = typeof attachment?.content_type === 'string'
|
|
166
|
+
? attachment.content_type.split(';', 1)[0].trim().toLowerCase() : '';
|
|
167
|
+
if (IMAGE_MEDIA_TYPES.has(value)) return value;
|
|
168
|
+
const filename = typeof attachment?.filename === 'string' ? attachment.filename.toLowerCase() : '';
|
|
169
|
+
for (const [extension, mediaType] of IMAGE_FILE_TYPES) {
|
|
170
|
+
if (filename.endsWith(extension)) return mediaType;
|
|
171
|
+
}
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function attachmentSize(value) {
|
|
176
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function discordImageSource(attachment, fetchImpl) {
|
|
180
|
+
const mediaType = attachmentMediaType(attachment);
|
|
181
|
+
if (!mediaType || typeof attachment?.url !== 'string') return null;
|
|
182
|
+
return {
|
|
183
|
+
name: typeof attachment.filename === 'string' ? attachment.filename : undefined,
|
|
184
|
+
mediaType,
|
|
185
|
+
size: attachmentSize(attachment.size),
|
|
186
|
+
load: (options) => fetchImageBuffer(attachment.url, {
|
|
187
|
+
...options,
|
|
188
|
+
fetchImpl,
|
|
189
|
+
allowedHosts: DISCORD_IMAGE_HOSTS,
|
|
190
|
+
}),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function discordFileSource(attachment, fetchImpl) {
|
|
195
|
+
if (attachmentMediaType(attachment) || typeof attachment?.url !== 'string' || !attachment.url) {
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
const mediaType = typeof attachment.content_type === 'string' && attachment.content_type
|
|
199
|
+
? attachment.content_type.split(';', 1)[0].trim().toLowerCase() : undefined;
|
|
200
|
+
return {
|
|
201
|
+
name: typeof attachment.filename === 'string' && attachment.filename
|
|
202
|
+
? attachment.filename : String(attachment.id ?? 'discord-file'),
|
|
203
|
+
...(mediaType ? { mediaType } : {}),
|
|
204
|
+
size: attachmentSize(attachment.size),
|
|
205
|
+
load: ({ signal } = {}) => fetchFileStream(attachment.url, {
|
|
206
|
+
fetchImpl,
|
|
207
|
+
signal,
|
|
208
|
+
allowedHosts: DISCORD_IMAGE_HOSTS,
|
|
209
|
+
}),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function discordReplyAttachment(attachment) {
|
|
214
|
+
if (!attachment || typeof attachment !== 'object') return null;
|
|
215
|
+
const mediaType = typeof attachment.content_type === 'string'
|
|
216
|
+
? attachment.content_type.split(';', 1)[0].trim().toLowerCase() : '';
|
|
217
|
+
const kind = mediaType.startsWith('image/') ? 'image'
|
|
218
|
+
: mediaType.startsWith('audio/') ? 'audio'
|
|
219
|
+
: mediaType.startsWith('video/') ? 'video' : 'file';
|
|
220
|
+
const name = typeof attachment.filename === 'string' && attachment.filename
|
|
221
|
+
? attachment.filename : undefined;
|
|
222
|
+
return { kind, ...(name ? { name } : {}) };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function discordReplySnapshot(message, fallbackMessageId) {
|
|
226
|
+
if (!message || typeof message !== 'object') return null;
|
|
227
|
+
const messageId = typeof message.id === 'string' && message.id
|
|
228
|
+
? message.id : fallbackMessageId;
|
|
229
|
+
const authorId = typeof message.author?.id === 'string' && message.author.id
|
|
230
|
+
? message.author.id : undefined;
|
|
231
|
+
const authorName = [message.member?.nick, message.author?.global_name, message.author?.username]
|
|
232
|
+
.find((value) => typeof value === 'string' && value.trim());
|
|
233
|
+
const attachments = Array.isArray(message.attachments)
|
|
234
|
+
? message.attachments.map(discordReplyAttachment).filter(Boolean)
|
|
235
|
+
: [];
|
|
236
|
+
if (Array.isArray(message.sticker_items)) {
|
|
237
|
+
attachments.push(...message.sticker_items.map((sticker) => ({
|
|
238
|
+
kind: 'image',
|
|
239
|
+
...(typeof sticker?.name === 'string' && sticker.name ? { name: sticker.name } : {}),
|
|
240
|
+
})));
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
...(messageId ? { messageId: String(messageId) } : {}),
|
|
244
|
+
...(authorId ? { authorId } : {}),
|
|
245
|
+
...(authorName ? { authorName } : {}),
|
|
246
|
+
content: typeof message.content === 'string' ? message.content : '',
|
|
247
|
+
attachments,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function discordReplyReference(message, loadReply) {
|
|
252
|
+
const channelId = String(message?.channel_id ?? '');
|
|
253
|
+
const referenceId = typeof message?.message_reference?.message_id === 'string'
|
|
254
|
+
&& message.message_reference.message_id
|
|
255
|
+
? message.message_reference.message_id : undefined;
|
|
256
|
+
const referenceChannelId = message?.message_reference?.channel_id;
|
|
257
|
+
if (referenceChannelId !== undefined && String(referenceChannelId) !== channelId) {
|
|
258
|
+
return {
|
|
259
|
+
...(referenceId ? { messageId: referenceId } : {}),
|
|
260
|
+
unavailableReason: 'not-found',
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
if (Object.hasOwn(message ?? {}, 'referenced_message')) {
|
|
264
|
+
if (message.referenced_message === null) {
|
|
265
|
+
return {
|
|
266
|
+
...(referenceId ? { messageId: referenceId } : {}),
|
|
267
|
+
unavailableReason: 'deleted',
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
if (message.referenced_message && typeof message.referenced_message === 'object') {
|
|
271
|
+
const snapshotId = typeof message.referenced_message.id === 'string'
|
|
272
|
+
&& message.referenced_message.id ? message.referenced_message.id : undefined;
|
|
273
|
+
if (String(message.referenced_message.channel_id ?? '') !== channelId
|
|
274
|
+
|| !snapshotId || (referenceId && snapshotId !== referenceId)) {
|
|
275
|
+
return {
|
|
276
|
+
...(referenceId ? { messageId: referenceId } : {}),
|
|
277
|
+
unavailableReason: 'not-found',
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
return discordReplySnapshot(message.referenced_message, referenceId) ?? undefined;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (!referenceId) return undefined;
|
|
284
|
+
if (typeof loadReply !== 'function') {
|
|
285
|
+
return { messageId: referenceId, unavailableReason: 'not-delivered' };
|
|
286
|
+
}
|
|
287
|
+
return {
|
|
288
|
+
messageId: referenceId,
|
|
289
|
+
load: async ({ signal } = {}) => {
|
|
290
|
+
const referenced = await loadReply({ channelId, messageId: referenceId, signal });
|
|
291
|
+
if (!referenced || String(referenced.id ?? '') !== referenceId
|
|
292
|
+
|| String(referenced.channel_id ?? '') !== channelId) return null;
|
|
293
|
+
return discordReplySnapshot(referenced, referenceId);
|
|
294
|
+
},
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export function normalizeDiscordMessage(message, botId, {
|
|
299
|
+
fetchImpl = fetch,
|
|
300
|
+
loadReply,
|
|
301
|
+
} = {}) {
|
|
302
|
+
if (!message?.id || !message?.channel_id || !message?.author?.id
|
|
303
|
+
|| Number(message.type) === 21) return null;
|
|
304
|
+
const direct = !message.guild_id;
|
|
305
|
+
const addressed = direct
|
|
306
|
+
|| message.mentions?.some((mention) => String(mention?.id) === String(botId));
|
|
307
|
+
const replyTo = discordReplyReference(message, loadReply);
|
|
308
|
+
return {
|
|
309
|
+
messageId: String(message.id),
|
|
310
|
+
senderId: String(message.author.id),
|
|
311
|
+
contextSource: () => ({
|
|
312
|
+
senderName: [message.member?.nick, message.author.global_name, message.author.username]
|
|
313
|
+
.find((value) => typeof value === 'string' && value.trim()),
|
|
314
|
+
}),
|
|
315
|
+
senderIsBot: message.author.bot === true,
|
|
316
|
+
kind: direct ? 'direct' : 'group',
|
|
317
|
+
conversationId: String(message.channel_id),
|
|
318
|
+
content: stripBotMention(message.content ?? '', botId),
|
|
319
|
+
plainText: (!Array.isArray(message.attachments) || message.attachments.length === 0)
|
|
320
|
+
&& (!Array.isArray(message.sticker_items) || message.sticker_items.length === 0)
|
|
321
|
+
&& !message.poll,
|
|
322
|
+
images: Array.isArray(message.attachments)
|
|
323
|
+
? message.attachments.map((attachment) => discordImageSource(attachment, fetchImpl)).filter(Boolean)
|
|
324
|
+
: [],
|
|
325
|
+
files: Array.isArray(message.attachments)
|
|
326
|
+
? message.attachments.map((attachment) => discordFileSource(attachment, fetchImpl)).filter(Boolean)
|
|
327
|
+
: [],
|
|
328
|
+
...(replyTo ? { replyTo } : {}),
|
|
329
|
+
addressed,
|
|
330
|
+
replyTarget: {
|
|
331
|
+
channelId: String(message.channel_id),
|
|
332
|
+
replyToMessageId: String(message.id),
|
|
333
|
+
},
|
|
334
|
+
reactionTarget: {
|
|
335
|
+
channelId: String(message.channel_id),
|
|
336
|
+
messageId: String(message.id),
|
|
337
|
+
},
|
|
338
|
+
connectionTestTarget: { channelId: String(message.channel_id) },
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export async function resolveDiscordMessageRoute(message, botId, {
|
|
343
|
+
api,
|
|
344
|
+
channel,
|
|
345
|
+
fetchImpl = fetch,
|
|
346
|
+
signal,
|
|
347
|
+
onChannel,
|
|
348
|
+
} = {}) {
|
|
349
|
+
const normalized = normalizeDiscordMessage(message, botId, {
|
|
350
|
+
fetchImpl,
|
|
351
|
+
loadReply: typeof api?.getMessage === 'function'
|
|
352
|
+
? (options) => api.getMessage(options)
|
|
353
|
+
: undefined,
|
|
354
|
+
});
|
|
355
|
+
if (!normalized || normalized.senderIsBot) return normalized;
|
|
356
|
+
signal?.throwIfAborted();
|
|
357
|
+
if (normalized.kind === 'direct') {
|
|
358
|
+
return withConversationRoute(normalized, { id: normalized.conversationId, type: 1 }, botId);
|
|
359
|
+
}
|
|
360
|
+
if (!api || typeof api.getChannel !== 'function') {
|
|
361
|
+
throw new TypeError('Discord route resolution requires the Discord API');
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const sourceChannel = rememberChannel(channel ?? await api.getChannel({
|
|
365
|
+
channelId: normalized.conversationId,
|
|
366
|
+
signal,
|
|
367
|
+
}), onChannel);
|
|
368
|
+
if (isThreadChannel(sourceChannel)) {
|
|
369
|
+
return withConversationRoute(normalized, sourceChannel, botId);
|
|
370
|
+
}
|
|
371
|
+
if (!normalized.addressed) return withConversationRoute(normalized, sourceChannel, botId);
|
|
372
|
+
|
|
373
|
+
const sourceType = Number(sourceChannel?.type);
|
|
374
|
+
if (sourceType !== GUILD_TEXT && sourceType !== GUILD_ANNOUNCEMENT) {
|
|
375
|
+
return withConversationRoute(normalized, sourceChannel, botId, {
|
|
376
|
+
fallback: 'unsupported-channel',
|
|
377
|
+
notice: '当前频道不支持自动创建 Thread,已直接在当前频道回复。',
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
signal?.throwIfAborted();
|
|
382
|
+
let created;
|
|
383
|
+
try {
|
|
384
|
+
created = rememberChannel(await api.startThreadFromMessage({
|
|
385
|
+
channelId: normalized.conversationId,
|
|
386
|
+
messageId: normalized.messageId,
|
|
387
|
+
name: cleanThreadName(message, botId),
|
|
388
|
+
signal,
|
|
389
|
+
}), onChannel);
|
|
390
|
+
if (!isThreadFromMessage(created, message)) {
|
|
391
|
+
throw new Error('Discord returned an invalid thread for the source message');
|
|
392
|
+
}
|
|
393
|
+
} catch (error) {
|
|
394
|
+
let recovered;
|
|
395
|
+
try {
|
|
396
|
+
recovered = await findCreatedThread(api, message, {
|
|
397
|
+
signal: AbortSignal.timeout(THREAD_RECOVERY_TIMEOUT_MS),
|
|
398
|
+
onChannel,
|
|
399
|
+
});
|
|
400
|
+
} catch (recoveryError) {
|
|
401
|
+
if (signal?.aborted) throw signal.reason ?? error;
|
|
402
|
+
await sendThreadUncertainNotice(api, normalized, signal);
|
|
403
|
+
throw threadCreateUncertain(recoveryError);
|
|
404
|
+
}
|
|
405
|
+
if (recovered) {
|
|
406
|
+
return withConversationRoute(normalized, recovered, botId, { fromSourceMessage: true });
|
|
407
|
+
}
|
|
408
|
+
if (signal?.aborted) throw signal.reason ?? error;
|
|
409
|
+
if (uncertainThreadCreate(error)) {
|
|
410
|
+
await sendThreadUncertainNotice(api, normalized, signal);
|
|
411
|
+
throw threadCreateUncertain(error);
|
|
412
|
+
}
|
|
413
|
+
return withConversationRoute(normalized, sourceChannel, botId, {
|
|
414
|
+
fallback: 'thread-create-failed',
|
|
415
|
+
notice: '无法创建 Thread,已直接在当前频道回复。',
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
return withConversationRoute(normalized, created, botId, { fromSourceMessage: true });
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
export class DiscordBotClient {
|
|
422
|
+
#api;
|
|
423
|
+
#signal;
|
|
424
|
+
#deliveredNotices = new WeakSet();
|
|
425
|
+
|
|
426
|
+
constructor({ api, signal }) {
|
|
427
|
+
this.#api = api;
|
|
428
|
+
this.#signal = signal;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async sendText(target, text) {
|
|
432
|
+
const notice = !this.#deliveredNotices.has(target) && target?.notice
|
|
433
|
+
? String(target.notice) : null;
|
|
434
|
+
const chunks = splitMessageText(notice ? `${notice}\n\n${text}` : text, 1_900);
|
|
435
|
+
const providerMessageIds = [];
|
|
436
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
437
|
+
const result = await this.#api.createMessage({
|
|
438
|
+
channelId: target.channelId,
|
|
439
|
+
content: chunk,
|
|
440
|
+
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
|
|
441
|
+
signal: this.#signal,
|
|
442
|
+
});
|
|
443
|
+
if (notice && index === 0) this.#deliveredNotices.add(target);
|
|
444
|
+
if (typeof result?.id === 'string' && result.id) providerMessageIds.push(result.id);
|
|
445
|
+
}
|
|
446
|
+
return { providerMessageIds };
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
sendTyping(target) {
|
|
450
|
+
return this.#api.sendTyping({ channelId: target.channelId, signal: this.#signal });
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
sendFile(target, file) {
|
|
454
|
+
return this.#api.createFileMessage({
|
|
455
|
+
channelId: target.channelId,
|
|
456
|
+
file,
|
|
457
|
+
replyToMessageId: target.replyToMessageId,
|
|
458
|
+
signal: this.#signal,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
addReaction(target, emoji, { signal } = {}) {
|
|
463
|
+
return this.#api.addOwnReaction({
|
|
464
|
+
channelId: target.channelId,
|
|
465
|
+
messageId: target.messageId,
|
|
466
|
+
emoji,
|
|
467
|
+
signal: this.#operationSignal(signal),
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
removeReaction(target, reactionKey, { signal } = {}) {
|
|
472
|
+
return this.#api.removeOwnReaction({
|
|
473
|
+
channelId: target.channelId,
|
|
474
|
+
messageId: target.messageId,
|
|
475
|
+
emoji: reactionKey,
|
|
476
|
+
signal: this.#operationSignal(signal),
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
async openStream(target) {
|
|
481
|
+
const notice = !this.#deliveredNotices.has(target) && target?.notice
|
|
482
|
+
? String(target.notice) : null;
|
|
483
|
+
const decorate = (content) => notice ? `${notice}\n\n${content}` : content;
|
|
484
|
+
const stream = createEditableMessageStream({
|
|
485
|
+
limit: notice ? 1_800 : 1_900,
|
|
486
|
+
create: async (content) => {
|
|
487
|
+
const message = await this.#api.createMessage({
|
|
488
|
+
channelId: target.channelId,
|
|
489
|
+
content: decorate(content),
|
|
490
|
+
replyToMessageId: target.replyToMessageId,
|
|
491
|
+
signal: this.#signal,
|
|
492
|
+
});
|
|
493
|
+
if (notice) this.#deliveredNotices.add(target);
|
|
494
|
+
return message.id;
|
|
495
|
+
},
|
|
496
|
+
edit: (messageId, content) => this.#api.editMessage({
|
|
497
|
+
channelId: target.channelId,
|
|
498
|
+
messageId,
|
|
499
|
+
content: decorate(content),
|
|
500
|
+
signal: this.#signal,
|
|
501
|
+
}),
|
|
502
|
+
sendRemainder: (content) => this.#api.createMessage({
|
|
503
|
+
channelId: target.channelId,
|
|
504
|
+
content,
|
|
505
|
+
signal: this.#signal,
|
|
506
|
+
}),
|
|
507
|
+
messageIdForResult: (message) => message?.id,
|
|
508
|
+
});
|
|
509
|
+
return stream.start();
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
#operationSignal(signal) {
|
|
513
|
+
return signal ?? this.#signal;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
export function createDiscordRuntimeStatus() {
|
|
518
|
+
return {
|
|
519
|
+
startedAt: null,
|
|
520
|
+
ready: false,
|
|
521
|
+
connectionState: 'idle',
|
|
522
|
+
harnessReachable: false,
|
|
523
|
+
lastCheckedAt: null,
|
|
524
|
+
lastConnectedAt: null,
|
|
525
|
+
lastError: null,
|
|
526
|
+
...createDiscordBridgeStatus(),
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
export class DiscordRuntime {
|
|
531
|
+
#config;
|
|
532
|
+
#token;
|
|
533
|
+
#harness;
|
|
534
|
+
#state;
|
|
535
|
+
#contextEnhancement;
|
|
536
|
+
#accessPolicy;
|
|
537
|
+
#logger;
|
|
538
|
+
#diagnostics;
|
|
539
|
+
#replyTimeoutMs;
|
|
540
|
+
#connectTimeoutMs;
|
|
541
|
+
#createApi;
|
|
542
|
+
#createWebSocket;
|
|
543
|
+
#random;
|
|
544
|
+
#status = createDiscordRuntimeStatus();
|
|
545
|
+
#api = null;
|
|
546
|
+
#bridge = null;
|
|
547
|
+
#abortController = null;
|
|
548
|
+
#socket = null;
|
|
549
|
+
#gatewayUrl = null;
|
|
550
|
+
#resumeUrl = null;
|
|
551
|
+
#sessionId = null;
|
|
552
|
+
#sequence = null;
|
|
553
|
+
#heartbeatTimer = null;
|
|
554
|
+
#heartbeatAcked = true;
|
|
555
|
+
#reconnectTimer = null;
|
|
556
|
+
#reconnectAttempt = 0;
|
|
557
|
+
#generation = 0;
|
|
558
|
+
#stopped = true;
|
|
559
|
+
#starting = null;
|
|
560
|
+
#channels = new Map();
|
|
561
|
+
#routing = new Map();
|
|
562
|
+
|
|
563
|
+
constructor({
|
|
564
|
+
config,
|
|
565
|
+
token,
|
|
566
|
+
harness,
|
|
567
|
+
state,
|
|
568
|
+
contextEnhancement,
|
|
569
|
+
accessPolicy,
|
|
570
|
+
logger = console,
|
|
571
|
+
replyTimeoutMs = 600_000,
|
|
572
|
+
connectTimeoutMs = 20_000,
|
|
573
|
+
createApi = (options) => new DiscordApi(options),
|
|
574
|
+
createWebSocket = (url) => new WebSocket(url),
|
|
575
|
+
random = Math.random,
|
|
576
|
+
}) {
|
|
577
|
+
if (!config || !token || !harness || !state) {
|
|
578
|
+
throw new TypeError('DiscordRuntime requires config, token, Harness, and state');
|
|
579
|
+
}
|
|
580
|
+
if (typeof createWebSocket !== 'function') throw new TypeError('DiscordRuntime requires WebSocket');
|
|
581
|
+
this.#config = config;
|
|
582
|
+
this.#token = token;
|
|
583
|
+
this.#harness = harness;
|
|
584
|
+
this.#state = state;
|
|
585
|
+
this.#contextEnhancement = contextEnhancement;
|
|
586
|
+
this.#accessPolicy = accessPolicy;
|
|
587
|
+
this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'discord', logger });
|
|
588
|
+
this.#replyTimeoutMs = replyTimeoutMs;
|
|
589
|
+
this.#connectTimeoutMs = connectTimeoutMs;
|
|
590
|
+
this.#createApi = createApi;
|
|
591
|
+
this.#createWebSocket = createWebSocket;
|
|
592
|
+
this.#random = random;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
get status() {
|
|
596
|
+
return structuredClone(this.#status);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
async sendConnectionTest(text) {
|
|
600
|
+
if (!this.#status.ready || !this.#bridge) {
|
|
601
|
+
const error = new Error('Discord bot is not connected');
|
|
602
|
+
error.code = 'test-target-unavailable';
|
|
603
|
+
throw error;
|
|
604
|
+
}
|
|
605
|
+
return this.#bridge.sendConnectionTest(text);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
async sendProactiveText(target, text, options = {}) {
|
|
609
|
+
if (!this.#status.ready || !this.#bridge) {
|
|
610
|
+
const error = new Error('Discord bot is not connected');
|
|
611
|
+
error.code = 'bot-not-connected';
|
|
612
|
+
throw error;
|
|
613
|
+
}
|
|
614
|
+
const channelId = typeof target?.route?.channelId === 'string'
|
|
615
|
+
? target.route.channelId.trim() : '';
|
|
616
|
+
if (target?.kind !== 'channel' || !channelId) {
|
|
617
|
+
const error = new TypeError('Invalid Discord proactive delivery target');
|
|
618
|
+
error.code = 'invalid-target';
|
|
619
|
+
throw error;
|
|
620
|
+
}
|
|
621
|
+
return this.#bridge.sendProactiveText({ channelId }, text, options);
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
async start() {
|
|
625
|
+
if (this.#status.ready && this.#socket) return this.status;
|
|
626
|
+
if (this.#starting) return this.#starting;
|
|
627
|
+
this.#starting = this.#start().finally(() => {
|
|
628
|
+
this.#starting = null;
|
|
629
|
+
});
|
|
630
|
+
return this.#starting;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
async #start() {
|
|
634
|
+
await this.stop();
|
|
635
|
+
this.#stopped = false;
|
|
636
|
+
this.#sessionId = null;
|
|
637
|
+
this.#resumeUrl = null;
|
|
638
|
+
this.#sequence = null;
|
|
639
|
+
this.#reconnectAttempt = 0;
|
|
640
|
+
this.#channels.clear();
|
|
641
|
+
this.#routing.clear();
|
|
642
|
+
this.#status.startedAt = new Date().toISOString();
|
|
643
|
+
this.#status.connectionState = 'connecting';
|
|
644
|
+
this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
|
|
645
|
+
await atConnectionStage('harness.check', () => this.#harness.ensureRunning());
|
|
646
|
+
this.#status.harnessReachable = true;
|
|
647
|
+
const controller = new AbortController();
|
|
648
|
+
this.#abortController = controller;
|
|
649
|
+
const api = this.#createApi({ token: this.#token });
|
|
650
|
+
this.#api = api;
|
|
651
|
+
try {
|
|
652
|
+
const [bot, gateway] = await Promise.all([
|
|
653
|
+
api.getCurrentUser({ signal: controller.signal }),
|
|
654
|
+
api.getGatewayBot({ signal: controller.signal }),
|
|
655
|
+
]);
|
|
656
|
+
if (String(bot?.id ?? '') !== this.#config.platformId || bot?.bot !== true) {
|
|
657
|
+
throw new Error('Discord token identity does not match the saved bot');
|
|
658
|
+
}
|
|
659
|
+
this.#gatewayUrl = gateway?.url;
|
|
660
|
+
const client = new DiscordBotClient({ api, signal: controller.signal });
|
|
661
|
+
this.#bridge = new DiscordHarnessBridge({
|
|
662
|
+
bot: client,
|
|
663
|
+
harness: this.#harness,
|
|
664
|
+
state: this.#state,
|
|
665
|
+
contextEnhancement: this.#contextEnhancement,
|
|
666
|
+
accessPolicy: this.#accessPolicy,
|
|
667
|
+
status: this.#status,
|
|
668
|
+
logger: this.#logger,
|
|
669
|
+
replyTimeoutMs: this.#replyTimeoutMs,
|
|
670
|
+
signal: controller.signal,
|
|
671
|
+
});
|
|
672
|
+
let timer;
|
|
673
|
+
try {
|
|
674
|
+
await Promise.race([
|
|
675
|
+
this.#openSocket(false),
|
|
676
|
+
new Promise((_, reject) => {
|
|
677
|
+
timer = setTimeout(() => reject(Object.assign(new Error('Discord Gateway did not become ready in time'), { code: 'ETIMEDOUT', timeoutMs: this.#connectTimeoutMs })), this.#connectTimeoutMs);
|
|
678
|
+
}),
|
|
679
|
+
]);
|
|
680
|
+
} finally {
|
|
681
|
+
clearTimeout(timer);
|
|
682
|
+
}
|
|
683
|
+
return this.status;
|
|
684
|
+
} catch (error) {
|
|
685
|
+
this.#status.ready = false;
|
|
686
|
+
this.#status.connectionState = 'failed';
|
|
687
|
+
this.#status.error = this.#diagnostics.report(error, { operation: 'connection.restore', reuse: true, botId: this.#config?.botId, automatic: true }).publicError;
|
|
688
|
+
this.#status.lastError = this.#status.error.message;
|
|
689
|
+
await this.stop();
|
|
690
|
+
throw error;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
#openSocket(resume) {
|
|
695
|
+
if (this.#stopped) return Promise.reject(new Error('Discord runtime is stopped'));
|
|
696
|
+
const generation = ++this.#generation;
|
|
697
|
+
const url = socketUrl(resume && this.#resumeUrl ? this.#resumeUrl : this.#gatewayUrl);
|
|
698
|
+
const socket = this.#createWebSocket(url);
|
|
699
|
+
this.#socket = socket;
|
|
700
|
+
let settled = false;
|
|
701
|
+
return new Promise((resolve, reject) => {
|
|
702
|
+
const markReady = () => {
|
|
703
|
+
if (settled || generation !== this.#generation) return;
|
|
704
|
+
settled = true;
|
|
705
|
+
this.#reconnectAttempt = 0;
|
|
706
|
+
const now = Date.now();
|
|
707
|
+
this.#status.ready = true;
|
|
708
|
+
this.#status.connectionState = 'connected';
|
|
709
|
+
this.#status.lastCheckedAt = now;
|
|
710
|
+
this.#status.lastConnectedAt = now;
|
|
711
|
+
this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
|
|
712
|
+
resolve();
|
|
713
|
+
};
|
|
714
|
+
addSocketListener(socket, 'message', (event) => {
|
|
715
|
+
if (generation !== this.#generation || this.#stopped) return;
|
|
716
|
+
const raw = eventData(event);
|
|
717
|
+
if (!raw) return;
|
|
718
|
+
let packet;
|
|
719
|
+
try {
|
|
720
|
+
packet = JSON.parse(raw);
|
|
721
|
+
} catch {
|
|
722
|
+
this.#logger.warn?.('[dsh-im:discord] ignored malformed Gateway JSON');
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
if (Number.isSafeInteger(packet.s)) this.#sequence = packet.s;
|
|
726
|
+
if (packet.op === 10) {
|
|
727
|
+
this.#startHeartbeat(packet.d?.heartbeat_interval, socket, generation);
|
|
728
|
+
if (resume && this.#sessionId) {
|
|
729
|
+
this.#sendGateway(socket, {
|
|
730
|
+
op: 6,
|
|
731
|
+
d: { token: this.#token, session_id: this.#sessionId, seq: this.#sequence },
|
|
732
|
+
});
|
|
733
|
+
} else {
|
|
734
|
+
this.#sendGateway(socket, {
|
|
735
|
+
op: 2,
|
|
736
|
+
d: {
|
|
737
|
+
token: this.#token,
|
|
738
|
+
intents: DISCORD_GATEWAY_INTENTS,
|
|
739
|
+
properties: {
|
|
740
|
+
os: process.platform,
|
|
741
|
+
browser: 'dsh-im',
|
|
742
|
+
device: 'dsh-im',
|
|
743
|
+
},
|
|
744
|
+
},
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
if (packet.op === 11) {
|
|
750
|
+
this.#heartbeatAcked = true;
|
|
751
|
+
this.#status.lastCheckedAt = Date.now();
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
if (packet.op === 1) {
|
|
755
|
+
this.#heartbeat(socket);
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
if (packet.op === 7) {
|
|
759
|
+
socket.close(4000, 'Reconnect requested');
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
if (packet.op === 9) {
|
|
763
|
+
if (packet.d !== true) {
|
|
764
|
+
this.#sessionId = null;
|
|
765
|
+
this.#resumeUrl = null;
|
|
766
|
+
this.#sequence = null;
|
|
767
|
+
}
|
|
768
|
+
socket.close(4000, 'Invalid session');
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
if (packet.op !== 0) return;
|
|
772
|
+
if (packet.t === 'READY') {
|
|
773
|
+
this.#sessionId = packet.d?.session_id ?? null;
|
|
774
|
+
this.#resumeUrl = packet.d?.resume_gateway_url ?? null;
|
|
775
|
+
markReady();
|
|
776
|
+
} else if (packet.t === 'RESUMED') {
|
|
777
|
+
markReady();
|
|
778
|
+
} else if (packet.t === 'GUILD_CREATE') {
|
|
779
|
+
for (const channel of [...(packet.d?.channels ?? []), ...(packet.d?.threads ?? [])]) {
|
|
780
|
+
this.#rememberChannel(channel);
|
|
781
|
+
}
|
|
782
|
+
} else if (packet.t === 'CHANNEL_CREATE' || packet.t === 'CHANNEL_UPDATE'
|
|
783
|
+
|| packet.t === 'THREAD_CREATE' || packet.t === 'THREAD_UPDATE') {
|
|
784
|
+
this.#rememberChannel(packet.d);
|
|
785
|
+
} else if (packet.t === 'CHANNEL_DELETE' || packet.t === 'THREAD_DELETE') {
|
|
786
|
+
if (packet.d?.id) this.#channels.delete(String(packet.d.id));
|
|
787
|
+
} else if (packet.t === 'THREAD_LIST_SYNC') {
|
|
788
|
+
for (const channel of packet.d?.threads ?? []) this.#rememberChannel(channel);
|
|
789
|
+
} else if (packet.t === 'MESSAGE_CREATE') {
|
|
790
|
+
const bridge = this.#bridge;
|
|
791
|
+
if (packet.d && bridge) {
|
|
792
|
+
void this.#acceptMessage(packet.d, bridge).catch((error) => {
|
|
793
|
+
if (generation !== this.#generation || this.#stopped) return;
|
|
794
|
+
this.#logger.error?.(
|
|
795
|
+
`[dsh-im:discord] bot ${this.#config.botId} message handling failed:`,
|
|
796
|
+
extractConnectionEvidence(error).details,
|
|
797
|
+
);
|
|
798
|
+
});
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
});
|
|
802
|
+
addSocketListener(socket, 'close', (event = {}) => {
|
|
803
|
+
if (generation !== this.#generation) return;
|
|
804
|
+
this.#clearHeartbeat();
|
|
805
|
+
if (this.#socket === socket) this.#socket = null;
|
|
806
|
+
if (this.#stopped) {
|
|
807
|
+
if (!settled) reject(new DOMException('Stopped', 'AbortError'));
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
const error = gatewayCloseError(Number(event.code) || 0);
|
|
811
|
+
this.#status.ready = false;
|
|
812
|
+
this.#status.connectionState = 'connecting';
|
|
813
|
+
this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#config?.botId, automatic: true }).publicError;
|
|
814
|
+
this.#status.lastError = this.#status.error.message;
|
|
815
|
+
if (!settled) {
|
|
816
|
+
settled = true;
|
|
817
|
+
reject(error);
|
|
818
|
+
}
|
|
819
|
+
if (error.code === 'discord-401' || error.code === 'discord-intents') {
|
|
820
|
+
this.#status.connectionState = 'failed';
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
this.#scheduleReconnect();
|
|
824
|
+
});
|
|
825
|
+
addSocketListener(socket, 'error', (event) => {
|
|
826
|
+
const error = event?.error ?? new Error('WebSocket error');
|
|
827
|
+
if (generation !== this.#generation || this.#stopped) return;
|
|
828
|
+
this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#config?.botId, automatic: true }).publicError;
|
|
829
|
+
this.#status.lastError = this.#status.error.message;
|
|
830
|
+
});
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
#rememberChannel(channel) {
|
|
835
|
+
if (!channel?.id) return;
|
|
836
|
+
this.#channels.set(String(channel.id), channel);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
async #acceptMessage(message, bridge) {
|
|
840
|
+
const messageId = String(message?.id ?? '');
|
|
841
|
+
if (!messageId || this.#state.hasSeen(messageId)) return;
|
|
842
|
+
const preflight = normalizeDiscordMessage(message, this.#config.platformId);
|
|
843
|
+
let accessDecision;
|
|
844
|
+
if (preflight?.kind === 'group' && preflight.addressed === true
|
|
845
|
+
&& preflight.senderIsBot !== true) {
|
|
846
|
+
accessDecision = evaluateInboundAccess(this.#accessPolicy, {
|
|
847
|
+
conversationType: 'group',
|
|
848
|
+
senderIds: [preflight.senderId],
|
|
849
|
+
text: preflight.content,
|
|
850
|
+
hasImages: preflight.images.length > 0,
|
|
851
|
+
hasFiles: preflight.files.length > 0,
|
|
852
|
+
});
|
|
853
|
+
if (!accessDecision.allowed) {
|
|
854
|
+
// Let the shared bridge apply its normal silent/command-denial behavior,
|
|
855
|
+
// but do so against the source channel before creating a Thread.
|
|
856
|
+
await bridge.accept(preflight, { accessDecision });
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
let route = this.#routing.get(messageId);
|
|
861
|
+
if (!route) {
|
|
862
|
+
const contextSnapshot = captureContextEnhancement(
|
|
863
|
+
this.#contextEnhancement,
|
|
864
|
+
message.guild_id ? 'group' : 'direct',
|
|
865
|
+
);
|
|
866
|
+
const pendingRoute = resolveDiscordMessageRoute(message, this.#config.platformId, {
|
|
867
|
+
api: this.#api,
|
|
868
|
+
channel: this.#channels.get(String(message.channel_id)),
|
|
869
|
+
signal: this.#abortController?.signal,
|
|
870
|
+
onChannel: (resolved) => this.#rememberChannel(resolved),
|
|
871
|
+
});
|
|
872
|
+
route = { pendingRoute, contextSnapshot };
|
|
873
|
+
this.#routing.set(messageId, route);
|
|
874
|
+
void pendingRoute.finally(() => {
|
|
875
|
+
if (this.#routing.get(messageId) === route) this.#routing.delete(messageId);
|
|
876
|
+
}).catch(() => undefined);
|
|
877
|
+
}
|
|
878
|
+
try {
|
|
879
|
+
const normalized = await route.pendingRoute;
|
|
880
|
+
if (normalized) {
|
|
881
|
+
await bridge.accept(normalized, {
|
|
882
|
+
contextSnapshot: route.contextSnapshot,
|
|
883
|
+
...(accessDecision ? { accessDecision } : {}),
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
} catch (error) {
|
|
887
|
+
if (error?.code === 'discord-thread-create-uncertain') {
|
|
888
|
+
await this.#state.markSeen(messageId);
|
|
889
|
+
}
|
|
890
|
+
throw error;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
#sendGateway(socket, payload) {
|
|
895
|
+
if (socket.readyState !== 1) return;
|
|
896
|
+
socket.send(JSON.stringify(payload));
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
#startHeartbeat(interval, socket, generation) {
|
|
900
|
+
this.#clearHeartbeat();
|
|
901
|
+
if (!Number.isFinite(interval) || interval < 1_000) {
|
|
902
|
+
socket.close(4000, 'Invalid heartbeat interval');
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
this.#heartbeatAcked = true;
|
|
906
|
+
const schedule = (delay) => {
|
|
907
|
+
this.#heartbeatTimer = setTimeout(() => {
|
|
908
|
+
if (this.#stopped || generation !== this.#generation || this.#socket !== socket) return;
|
|
909
|
+
if (!this.#heartbeatAcked) {
|
|
910
|
+
socket.close(4000, 'Heartbeat was not acknowledged');
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
this.#heartbeat(socket);
|
|
914
|
+
schedule(interval);
|
|
915
|
+
}, delay);
|
|
916
|
+
this.#heartbeatTimer?.unref?.();
|
|
917
|
+
};
|
|
918
|
+
schedule(Math.floor(interval * this.#random()));
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
#heartbeat(socket) {
|
|
922
|
+
this.#heartbeatAcked = false;
|
|
923
|
+
this.#sendGateway(socket, { op: 1, d: this.#sequence });
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
#clearHeartbeat() {
|
|
927
|
+
if (this.#heartbeatTimer !== null) clearTimeout(this.#heartbeatTimer);
|
|
928
|
+
this.#heartbeatTimer = null;
|
|
929
|
+
this.#heartbeatAcked = true;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
#scheduleReconnect() {
|
|
933
|
+
if (this.#stopped || this.#reconnectTimer !== null) return;
|
|
934
|
+
const delay = RECONNECT_DELAYS_MS[Math.min(this.#reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)];
|
|
935
|
+
this.#reconnectAttempt += 1;
|
|
936
|
+
this.#reconnectTimer = setTimeout(() => {
|
|
937
|
+
this.#reconnectTimer = null;
|
|
938
|
+
void this.#openSocket(Boolean(this.#sessionId)).catch((error) => {
|
|
939
|
+
if (this.#stopped) return;
|
|
940
|
+
this.#logger.warn?.('[dsh-im:discord] Gateway reconnect failed:', extractConnectionEvidence(error).details);
|
|
941
|
+
this.#scheduleReconnect();
|
|
942
|
+
});
|
|
943
|
+
}, delay);
|
|
944
|
+
this.#reconnectTimer?.unref?.();
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
async stop() {
|
|
948
|
+
this.#stopped = true;
|
|
949
|
+
this.#generation += 1;
|
|
950
|
+
this.#abortController?.abort();
|
|
951
|
+
this.#abortController = null;
|
|
952
|
+
if (this.#reconnectTimer !== null) clearTimeout(this.#reconnectTimer);
|
|
953
|
+
this.#reconnectTimer = null;
|
|
954
|
+
this.#clearHeartbeat();
|
|
955
|
+
const socket = this.#socket;
|
|
956
|
+
const bridge = this.#bridge;
|
|
957
|
+
this.#socket = null;
|
|
958
|
+
this.#bridge = null;
|
|
959
|
+
this.#api = null;
|
|
960
|
+
this.#routing.clear();
|
|
961
|
+
try {
|
|
962
|
+
if (socket && socket.readyState < 2) socket.close(1000, 'Plugin stopped');
|
|
963
|
+
} catch (error) {
|
|
964
|
+
this.#logger.warn?.(`[dsh-im:discord] bot ${this.#config.botId} failed to close Gateway:`, extractConnectionEvidence(error).details);
|
|
965
|
+
}
|
|
966
|
+
await Promise.race([
|
|
967
|
+
bridge?.waitForIdle() ?? Promise.resolve(),
|
|
968
|
+
new Promise((resolve) => setTimeout(resolve, 2_000)),
|
|
969
|
+
]);
|
|
970
|
+
this.#status.ready = false;
|
|
971
|
+
this.#status.connectionState = 'idle';
|
|
972
|
+
return this.status;
|
|
973
|
+
}
|
|
974
|
+
}
|