@botharness/im-provider 4.32.0-botharness.15
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 +604 -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 +18 -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 +319 -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 +239 -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 +258 -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 +411 -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 +618 -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 +229 -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 +28 -0
- package/src/channels/discord/discord-api.mjs +423 -0
- package/src/channels/discord/discord-bridge.mjs +16 -0
- package/src/channels/discord/discord-controller.mjs +29 -0
- package/src/channels/discord/discord-runtime.mjs +1091 -0
- package/src/channels/discord/external-consumer.mjs +199 -0
- package/src/channels/discord/external-files.mjs +97 -0
- package/src/channels/discord/harness-client.mjs +11 -0
- package/src/channels/discord/history-reader.mjs +142 -0
- package/src/channels/discord/nearby-history.mjs +112 -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-cards.mjs +87 -0
- package/src/channels/feishu/external-consumer.mjs +89 -0
- package/src/channels/feishu/external-files.mjs +115 -0
- package/src/channels/feishu/external-images.mjs +50 -0
- package/src/channels/feishu/external-names.mjs +99 -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 +982 -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 +1619 -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 +91 -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 +529 -0
- package/src/channels/shared/token-config-store.mjs +208 -0
- package/src/channels/shared/video-media.mjs +9 -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 +93 -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 +644 -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 +895 -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 +194 -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/external-consumer.mjs +160 -0
- package/src/channels/weixin/external-files.mjs +84 -0
- package/src/channels/weixin/external-typing.mjs +120 -0
- package/src/channels/weixin/harness-client.mjs +19 -0
- package/src/channels/weixin/state-store.mjs +316 -0
- package/src/channels/weixin/weixin-api.mjs +1009 -0
- package/src/channels/weixin/weixin-bridge.mjs +1537 -0
- package/src/channels/weixin/weixin-controller.mjs +779 -0
- package/src/channels/weixin/weixin-runtime.mjs +507 -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,1537 @@
|
|
|
1
|
+
import { createDeferredDeliveryCoordinator, deferredOutcomeText } from '../shared/deferred-delivery-coordinator.mjs';
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_WEIXIN_MAX_MESSAGE_CHARS,
|
|
4
|
+
extractWeixinFiles,
|
|
5
|
+
extractWeixinImages,
|
|
6
|
+
extractWeixinReplyReference,
|
|
7
|
+
extractWeixinText,
|
|
8
|
+
splitWeixinText,
|
|
9
|
+
weixinMessageId,
|
|
10
|
+
weixinMessageTimestampMs,
|
|
11
|
+
} from './weixin-api.mjs';
|
|
12
|
+
import {
|
|
13
|
+
harnessAnswerForQuestion,
|
|
14
|
+
harnessQuestionText,
|
|
15
|
+
validHarnessQuestion,
|
|
16
|
+
} from '../shared/harness-question.mjs';
|
|
17
|
+
import { HarnessApprovalQueue } from '../shared/harness-approval.mjs';
|
|
18
|
+
import {
|
|
19
|
+
BatchInputManager,
|
|
20
|
+
batchInputBusyMessage,
|
|
21
|
+
isBatchInputCommand,
|
|
22
|
+
} from '../shared/batch-input.mjs';
|
|
23
|
+
import { runCompactCommand } from '../shared/compact-command.mjs';
|
|
24
|
+
import { isHistoryCommand, runHistoryCommand } from '../shared/history-command.mjs';
|
|
25
|
+
import {
|
|
26
|
+
isControlCommand,
|
|
27
|
+
runControlCommand,
|
|
28
|
+
} from '../shared/control-command.mjs';
|
|
29
|
+
import {
|
|
30
|
+
isModelCommand,
|
|
31
|
+
runModelCommand,
|
|
32
|
+
} from '../shared/model-command.mjs';
|
|
33
|
+
import {
|
|
34
|
+
isPresetCommand,
|
|
35
|
+
runPresetCommand,
|
|
36
|
+
} from '../shared/preset-command.mjs';
|
|
37
|
+
import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
|
|
38
|
+
import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
|
|
39
|
+
import {
|
|
40
|
+
captureContextEnhancement,
|
|
41
|
+
captureContextEnhancementSource,
|
|
42
|
+
enhanceContextContent,
|
|
43
|
+
withSentAt,
|
|
44
|
+
} from '../shared/context-enhancement.mjs';
|
|
45
|
+
import {
|
|
46
|
+
hasInboundImages,
|
|
47
|
+
imagePromptDiagnostic,
|
|
48
|
+
imagePromptUserMessage,
|
|
49
|
+
} from '../shared/image-prompt.mjs';
|
|
50
|
+
import {
|
|
51
|
+
hasInboundFiles,
|
|
52
|
+
inboundFileUserMessage,
|
|
53
|
+
prefetchInboundFiles,
|
|
54
|
+
} from '../shared/inbound-file.mjs';
|
|
55
|
+
import { rememberConnectionTestTarget } from '../shared/connection-test.mjs';
|
|
56
|
+
import { deliverOutboundArtifacts } from '../shared/semantic/artifact-delivery.mjs';
|
|
57
|
+
import {
|
|
58
|
+
hasReplyReference,
|
|
59
|
+
promptContentForInboundMessage,
|
|
60
|
+
} from '../shared/semantic/reply-reference.mjs';
|
|
61
|
+
import {
|
|
62
|
+
createDeliveryReceipt,
|
|
63
|
+
providerMessageIdsFor,
|
|
64
|
+
} from '../shared/semantic/delivery.mjs';
|
|
65
|
+
import { recoverAssistantTextByTimestamp } from '../shared/session-reply-recovery.mjs';
|
|
66
|
+
import {
|
|
67
|
+
messageFailureDiagnostic,
|
|
68
|
+
channelDeliveryFailure,
|
|
69
|
+
clearLastMessageFailure,
|
|
70
|
+
messageFailureText,
|
|
71
|
+
setLastMessageFailure,
|
|
72
|
+
} from '../shared/message-failure.mjs';
|
|
73
|
+
import {
|
|
74
|
+
COMMAND_PERMISSION_DENIED_MESSAGE,
|
|
75
|
+
evaluateInboundAccess,
|
|
76
|
+
} from '../shared/inbound-access.mjs';
|
|
77
|
+
import { t } from '../shared/i18n.mjs';
|
|
78
|
+
|
|
79
|
+
const INTERACTION_RESOLVED_TEXT = () => t('这个问题已在其他客户端处理,无需再次回答。');
|
|
80
|
+
const DEFAULT_TYPING_KEEPALIVE_MS = 5_000;
|
|
81
|
+
const TYPING_RETRY_DELAY_MS = 60_000;
|
|
82
|
+
const WEIXIN_SEND_DIAGNOSTIC = Symbol('weixin-send-diagnostic');
|
|
83
|
+
const WEIXIN_REPLY_HISTORY_PAGE_SIZE = 100;
|
|
84
|
+
const WEIXIN_REPLY_HISTORY_MAX_PAGES = 3;
|
|
85
|
+
const WEIXIN_REPLY_HISTORY_TIMEOUT_MS = 5_000;
|
|
86
|
+
const WEIXIN_REPLY_HISTORY_MATCH_TOLERANCE_MS = 15_000;
|
|
87
|
+
|
|
88
|
+
const HELP_TEXT = () => [
|
|
89
|
+
t('微信已连接 DeepSeek Harness。'),
|
|
90
|
+
'',
|
|
91
|
+
t('直接发送文字、图片、文件或带文字识别结果的语音即可继续当前会话。'),
|
|
92
|
+
t('/new 开启一个全新会话'),
|
|
93
|
+
t('/compact 压缩当前会话的较早上下文'),
|
|
94
|
+
t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'),
|
|
95
|
+
t('/workspace 工作区序号或绝对路径 切换工作区'),
|
|
96
|
+
t('/workspacelist 列出工作区绝对路径'),
|
|
97
|
+
t('/ws、/wsl、/workspaces 工作区命令别名'),
|
|
98
|
+
t('/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题'),
|
|
99
|
+
t('/sessionlist --limit N 仅列出当前工作区前 N 个会话'),
|
|
100
|
+
t('/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话'),
|
|
101
|
+
t('/models 按序号列出所有可用模型'),
|
|
102
|
+
t('/reasoninglist 或 /reasonings 按序号列出当前模型可用推理等级'),
|
|
103
|
+
t('/reasoning [序号、等级ID或 --default] 查看或切换当前推理等级'),
|
|
104
|
+
t('/model [序号或完整模型ID] [推理等级ID] 查看或切换当前会话模型'),
|
|
105
|
+
t('示例:先发 /models,再发 /model 2 [推理等级ID]'),
|
|
106
|
+
t('/presetlist 或 /presets 按序号列出可用 Agent Preset'),
|
|
107
|
+
t('/preset [序号或完整ID] 查看或设置当前机器人 Agent Preset'),
|
|
108
|
+
t('纯数字 ID:/preset id:<ID>'),
|
|
109
|
+
t('/preset --default 跟随 Host 默认'),
|
|
110
|
+
t('/stop 停止当前任务'),
|
|
111
|
+
t('/steer 补充指令 纠偏当前任务'),
|
|
112
|
+
t('/batch 开始批量输入(仅私聊,最多 10 条文字)'),
|
|
113
|
+
t('/send 提交当前批次'),
|
|
114
|
+
t('/cancel 取消当前批次'),
|
|
115
|
+
t('/status 检查连接状态'),
|
|
116
|
+
t('/version 查看插件版本'),
|
|
117
|
+
t('/help 显示本帮助'),
|
|
118
|
+
].join('\n');
|
|
119
|
+
|
|
120
|
+
function conversationKey(userId) {
|
|
121
|
+
return `p2p:${userId}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function nonEmptyString(value) {
|
|
125
|
+
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function safeDiagnosticToken(value) {
|
|
129
|
+
const token = value === undefined || value === null ? '' : String(value).trim();
|
|
130
|
+
return /^-?[A-Za-z0-9_.:-]{1,160}$/u.test(token) ? token : '-';
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function weixinApiHost(baseUrl) {
|
|
134
|
+
try {
|
|
135
|
+
return safeDiagnosticToken(new URL(baseUrl).hostname.toLowerCase());
|
|
136
|
+
} catch {
|
|
137
|
+
return '-';
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function createWeixinSendDiagnostic({
|
|
142
|
+
baseUrl,
|
|
143
|
+
text,
|
|
144
|
+
chunk,
|
|
145
|
+
chunkIndex,
|
|
146
|
+
chunkCount,
|
|
147
|
+
maxMessageChars,
|
|
148
|
+
contextToken,
|
|
149
|
+
runId,
|
|
150
|
+
error,
|
|
151
|
+
}) {
|
|
152
|
+
const status = Number(error?.status ?? error?.httpStatus);
|
|
153
|
+
const http = Number.isInteger(status)
|
|
154
|
+
? String(status)
|
|
155
|
+
: error?.code === 'send-rejected' ? '2xx' : '-';
|
|
156
|
+
return [
|
|
157
|
+
'endpoint=sendmessage',
|
|
158
|
+
`host=${weixinApiHost(baseUrl)}`,
|
|
159
|
+
`chunk=${chunkIndex + 1}/${chunkCount}`,
|
|
160
|
+
`chunkChars=${chunk.length}`,
|
|
161
|
+
`chunkUtf8Bytes=${Buffer.byteLength(chunk, 'utf8')}`,
|
|
162
|
+
`totalChars=${text.length}`,
|
|
163
|
+
`totalUtf8Bytes=${Buffer.byteLength(text, 'utf8')}`,
|
|
164
|
+
`limitChars=${maxMessageChars}`,
|
|
165
|
+
`contextToken=${contextToken ? 'yes' : 'no'}`,
|
|
166
|
+
`runId=${runId ? 'yes' : 'no'}`,
|
|
167
|
+
`http=${http}`,
|
|
168
|
+
`provider=${safeDiagnosticToken(error?.providerCode)}`,
|
|
169
|
+
`cause=${safeDiagnosticToken(error?.code ?? error?.name)}`,
|
|
170
|
+
].join(' ');
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function weixinSendError(error, details) {
|
|
174
|
+
const diagnostic = createWeixinSendDiagnostic({ ...details, error });
|
|
175
|
+
const wrapped = new Error(`Weixin text delivery failed (${diagnostic})`, { cause: error });
|
|
176
|
+
const code = safeDiagnosticToken(error?.code);
|
|
177
|
+
wrapped.code = code === '-' ? 'weixin-send-failed' : code;
|
|
178
|
+
const status = Number(error?.status ?? error?.httpStatus);
|
|
179
|
+
if (Number.isInteger(status)) wrapped.status = status;
|
|
180
|
+
const providerCode = safeDiagnosticToken(error?.providerCode);
|
|
181
|
+
if (providerCode !== '-') wrapped.providerCode = providerCode;
|
|
182
|
+
wrapped[WEIXIN_SEND_DIAGNOSTIC] = diagnostic;
|
|
183
|
+
return wrapped;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function weixinSendFailureOptions(error, { proactive = false } = {}) {
|
|
187
|
+
let current = error;
|
|
188
|
+
for (let depth = 0; current && depth < 5; depth += 1) {
|
|
189
|
+
const diagnostic = current[WEIXIN_SEND_DIAGNOSTIC];
|
|
190
|
+
if (typeof diagnostic === 'string' && diagnostic) {
|
|
191
|
+
return {
|
|
192
|
+
reason: 'weixin-send-failed',
|
|
193
|
+
userMessage: [
|
|
194
|
+
proactive
|
|
195
|
+
? t('微信主动消息发送失败。长轮询在线不代表消息可以发送。')
|
|
196
|
+
: t('回复已经生成,但微信发送失败,可能只收到部分内容。请将下面的诊断信息完整反馈给管理员。'),
|
|
197
|
+
...(String(current.providerCode) === '-2' ? [
|
|
198
|
+
t('iLink 拒绝发送,可能涉及会话有效期、发送额度或消息内容。可让接收者发一条消息后重试;不要通过反复发送心跳尝试续期。'),
|
|
199
|
+
] : []),
|
|
200
|
+
t('微信发送诊断:{diagnostic}', { diagnostic }),
|
|
201
|
+
].join('\n'),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
current = current.cause;
|
|
205
|
+
}
|
|
206
|
+
return undefined;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function weixinInboundMessage(message, api, state, { loadReplyContent } = {}) {
|
|
210
|
+
const toUserId = nonEmptyString(message?.from_user_id);
|
|
211
|
+
const replyTo = extractWeixinReplyReference(message, {
|
|
212
|
+
resolveContent: (reference) => state?.recentOutboundTextFor?.({
|
|
213
|
+
toUserId,
|
|
214
|
+
...reference,
|
|
215
|
+
}),
|
|
216
|
+
...(typeof loadReplyContent === 'function' ? {
|
|
217
|
+
loadContent: (reference, options) => loadReplyContent({
|
|
218
|
+
toUserId,
|
|
219
|
+
...reference,
|
|
220
|
+
}, options),
|
|
221
|
+
} : {}),
|
|
222
|
+
});
|
|
223
|
+
return {
|
|
224
|
+
content: extractWeixinText(message) ?? '',
|
|
225
|
+
images: typeof api?.inboundImages === 'function'
|
|
226
|
+
? api.inboundImages(message)
|
|
227
|
+
: extractWeixinImages(message),
|
|
228
|
+
files: typeof api?.inboundFiles === 'function'
|
|
229
|
+
? api.inboundFiles(message)
|
|
230
|
+
: extractWeixinFiles(message),
|
|
231
|
+
...(replyTo ? { replyTo } : {}),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function hasWeixinImageItems(message) {
|
|
236
|
+
return Array.isArray(message?.item_list)
|
|
237
|
+
&& message.item_list.some((item) => item?.image_item && typeof item.image_item === 'object');
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function hasWeixinFileItems(message) {
|
|
241
|
+
return Array.isArray(message?.item_list)
|
|
242
|
+
&& message.item_list.some((item) => item?.file_item && typeof item.file_item === 'object');
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function isNativeWeixinText(message) {
|
|
246
|
+
return Array.isArray(message?.item_list)
|
|
247
|
+
&& message.item_list.length > 0
|
|
248
|
+
&& message.item_list.every((item) => (
|
|
249
|
+
item?.type === 1 && typeof item.text_item?.text === 'string'
|
|
250
|
+
))
|
|
251
|
+
&& Boolean(nonEmptyString(extractWeixinText(message)));
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function canClaimInteractionReply(message, pending) {
|
|
255
|
+
return pending.questions[pending.index]
|
|
256
|
+
&& nonEmptyString(message?.from_user_id) === pending.actor
|
|
257
|
+
&& !hasWeixinImageItems(message)
|
|
258
|
+
&& !hasWeixinFileItems(message)
|
|
259
|
+
&& nonEmptyString(extractWeixinText(message));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function artifactFailureText(fileName, error) {
|
|
263
|
+
const name = String(fileName ?? t('结果文件')).replace(/[\r\n]+/g, ' ').trim() || t('结果文件');
|
|
264
|
+
switch (error?.code) {
|
|
265
|
+
case 'artifact-delivery-uncertain':
|
|
266
|
+
return t('结果文件「{name}」发送结果未能确认,请先检查聊天内是否已收到,不要立即重试。', { name });
|
|
267
|
+
case 'artifact-permission-required':
|
|
268
|
+
return t('结果文件「{name}」已生成,但微信机器人当前没有文件消息发送权限,请检查机器人文件消息能力。', { name });
|
|
269
|
+
case 'artifact-too-large':
|
|
270
|
+
return t('结果文件「{name}」超过当前微信会话可发送的文件大小,未发送。', { name });
|
|
271
|
+
case 'artifact-upload-timeout':
|
|
272
|
+
return t('结果文件「{name}」上传微信时长时间没有进展,已超时,文件尚未发送。请检查网络后重试,或压缩、拆分文件后发送。', { name });
|
|
273
|
+
case 'artifact-rate-limited':
|
|
274
|
+
return t('结果文件「{name}」暂时被微信限流,未能发送,请稍后重试。', { name });
|
|
275
|
+
case 'artifact-provider-rejected':
|
|
276
|
+
return t('结果文件「{name}」已生成,但微信拒绝了该文件消息。', { name });
|
|
277
|
+
case 'artifact-invalid':
|
|
278
|
+
case 'artifact-changed':
|
|
279
|
+
case 'artifact-unavailable':
|
|
280
|
+
return t('结果文件「{name}」暂时无法读取或准备发送,请确认文件仍可访问后重试。', { name });
|
|
281
|
+
default:
|
|
282
|
+
return t('结果文件「{name}」已生成,但暂时未能通过微信发送,请稍后重试。', { name });
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export function createWeixinBridgeStatus() {
|
|
287
|
+
return {
|
|
288
|
+
messagesReceived: 0,
|
|
289
|
+
messagesReplied: 0,
|
|
290
|
+
messagesRejected: 0,
|
|
291
|
+
lastMessageAt: null,
|
|
292
|
+
lastReplyAt: null,
|
|
293
|
+
lastRejectedAt: null,
|
|
294
|
+
lastError: null,
|
|
295
|
+
lastMessageError: null,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export class WeixinHarnessBridge {
|
|
300
|
+
#api;
|
|
301
|
+
#baseUrl;
|
|
302
|
+
#token;
|
|
303
|
+
#ownerUserId;
|
|
304
|
+
#harness;
|
|
305
|
+
#state;
|
|
306
|
+
#deferred;
|
|
307
|
+
#contextEnhancement;
|
|
308
|
+
#accessPolicy;
|
|
309
|
+
#status;
|
|
310
|
+
#logger;
|
|
311
|
+
#replyTimeoutMs;
|
|
312
|
+
#maxMessageChars;
|
|
313
|
+
#typingKeepaliveMs;
|
|
314
|
+
#signal;
|
|
315
|
+
#queues = new Map();
|
|
316
|
+
#pendingInteractions = new Map();
|
|
317
|
+
#interactionKeys = new Map();
|
|
318
|
+
// Keep the accepted configuration through the existing queue/reply lifecycle.
|
|
319
|
+
#acceptedMessageIds = new Map();
|
|
320
|
+
#approvalTasks = new Set();
|
|
321
|
+
#commandTasks = new Set();
|
|
322
|
+
#approvals;
|
|
323
|
+
#batchInputs = new BatchInputManager();
|
|
324
|
+
#typingTicket = null;
|
|
325
|
+
#typingTarget = null;
|
|
326
|
+
#typingTimer = null;
|
|
327
|
+
#typingGeneration = 0;
|
|
328
|
+
#typingTail = Promise.resolve();
|
|
329
|
+
#typingClosed = false;
|
|
330
|
+
#typingRetryAt = 0;
|
|
331
|
+
#typingTicketStale = false;
|
|
332
|
+
|
|
333
|
+
constructor({
|
|
334
|
+
api,
|
|
335
|
+
baseUrl,
|
|
336
|
+
token,
|
|
337
|
+
ownerUserId,
|
|
338
|
+
harness,
|
|
339
|
+
state,
|
|
340
|
+
contextEnhancement,
|
|
341
|
+
accessPolicy,
|
|
342
|
+
status = createWeixinBridgeStatus(),
|
|
343
|
+
logger = console,
|
|
344
|
+
replyTimeoutMs = 600_000,
|
|
345
|
+
maxMessageChars = DEFAULT_WEIXIN_MAX_MESSAGE_CHARS,
|
|
346
|
+
typingKeepaliveMs = DEFAULT_TYPING_KEEPALIVE_MS,
|
|
347
|
+
signal,
|
|
348
|
+
}) {
|
|
349
|
+
if (!api || typeof api.sendText !== 'function') throw new TypeError('Weixin API is required');
|
|
350
|
+
if (!baseUrl || !token || !ownerUserId) throw new TypeError('Weixin account credentials are required');
|
|
351
|
+
if (!harness || !state) throw new TypeError('Harness client and state store are required');
|
|
352
|
+
if (!Number.isFinite(typingKeepaliveMs) || typingKeepaliveMs <= 0) {
|
|
353
|
+
throw new TypeError('typingKeepaliveMs must be a positive number');
|
|
354
|
+
}
|
|
355
|
+
this.#api = api;
|
|
356
|
+
this.#baseUrl = baseUrl;
|
|
357
|
+
this.#token = token;
|
|
358
|
+
this.#ownerUserId = ownerUserId;
|
|
359
|
+
this.#harness = harness;
|
|
360
|
+
this.#state = state;
|
|
361
|
+
this.#contextEnhancement = contextEnhancement;
|
|
362
|
+
this.#accessPolicy = accessPolicy;
|
|
363
|
+
this.#status = status;
|
|
364
|
+
this.#logger = logger;
|
|
365
|
+
this.#replyTimeoutMs = replyTimeoutMs;
|
|
366
|
+
this.#maxMessageChars = maxMessageChars;
|
|
367
|
+
this.#typingKeepaliveMs = typingKeepaliveMs;
|
|
368
|
+
this.#signal = signal;
|
|
369
|
+
this.#deferred = createDeferredDeliveryCoordinator({ harness, state, signal, logger,
|
|
370
|
+
deliver: (entry, outcome) => this.#deliverDeferredOutcome(entry, outcome),
|
|
371
|
+
});
|
|
372
|
+
this.#approvals = new HarnessApprovalQueue({ label: 'weixin', logger });
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
get status() {
|
|
376
|
+
return structuredClone(this.#status);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
accept(message) {
|
|
380
|
+
if (this.#signal?.aborted) return Promise.resolve();
|
|
381
|
+
if (message?.message_type === 2) return Promise.resolve();
|
|
382
|
+
const messageId = weixinMessageId(message);
|
|
383
|
+
const sender = nonEmptyString(message?.from_user_id);
|
|
384
|
+
if (!messageId || !sender || this.#state.hasSeen(messageId)
|
|
385
|
+
|| this.#acceptedMessageIds.has(messageId)) return Promise.resolve();
|
|
386
|
+
const commandText = nonEmptyString(extractWeixinText(message)) ?? '';
|
|
387
|
+
const access = this.#accessPolicy
|
|
388
|
+
? evaluateInboundAccess(this.#accessPolicy, {
|
|
389
|
+
conversationType: 'direct',
|
|
390
|
+
senderIds: sender,
|
|
391
|
+
text: commandText,
|
|
392
|
+
hasImages: hasWeixinImageItems(message),
|
|
393
|
+
hasFiles: hasWeixinFileItems(message),
|
|
394
|
+
})
|
|
395
|
+
: sender === this.#ownerUserId
|
|
396
|
+
? { allowed: true, reason: 'legacy-owner' }
|
|
397
|
+
: { allowed: false, reason: 'sender-not-allowed' };
|
|
398
|
+
if (!access.allowed) {
|
|
399
|
+
this.#acceptedMessageIds.set(messageId, null);
|
|
400
|
+
return this.#finishAccessDecision(messageId, sender, message, access);
|
|
401
|
+
}
|
|
402
|
+
// Capture through the *source* entry point, not the bare config snapshot:
|
|
403
|
+
// the enhancement that renders the user message is read back from this map
|
|
404
|
+
// at prompt time, and a rendered `sentAt` selection needs the factory that
|
|
405
|
+
// carries the moment. Nothing is read here; the thunk runs only when that
|
|
406
|
+
// render selects `sentAt`.
|
|
407
|
+
this.#acceptedMessageIds.set(messageId, captureContextEnhancementSource(
|
|
408
|
+
this.#contextEnhancement,
|
|
409
|
+
'direct',
|
|
410
|
+
withSentAt(
|
|
411
|
+
() => ({ channel: 'weixin', senderId: sender, chatId: sender }),
|
|
412
|
+
// A thunk: the platform send time (falling back to the iLink message-id
|
|
413
|
+
// clock) is only decoded when a `sentAt` selection actually renders.
|
|
414
|
+
() => message?.create_time_ms ?? weixinMessageTimestampMs(messageId),
|
|
415
|
+
),
|
|
416
|
+
));
|
|
417
|
+
if (sender === this.#ownerUserId) {
|
|
418
|
+
rememberConnectionTestTarget(this.#state, { toUserId: sender });
|
|
419
|
+
}
|
|
420
|
+
const key = conversationKey(sender);
|
|
421
|
+
const contextToken = nonEmptyString(message?.context_token) ?? undefined;
|
|
422
|
+
void this.#state.rememberContextToken?.({
|
|
423
|
+
userId: sender,
|
|
424
|
+
contextToken,
|
|
425
|
+
seq: message.seq,
|
|
426
|
+
messageTimeMs: message.create_time_ms ?? weixinMessageTimestampMs(messageId),
|
|
427
|
+
}).catch((error) => this.#logger.warn?.('[dsh-weixin] failed to persist conversation context:', error));
|
|
428
|
+
const runId = nonEmptyString(message?.run_id) ?? undefined;
|
|
429
|
+
const pending = this.#pendingInteractions.get(key);
|
|
430
|
+
const batchCommand = isBatchInputCommand(commandText);
|
|
431
|
+
const batchStatus = this.#batchInputs.status(key);
|
|
432
|
+
if (batchCommand || batchStatus.phase === 'collecting') {
|
|
433
|
+
const exactBatchStart = /^\/batch$/iu.test(commandText);
|
|
434
|
+
const result = exactBatchStart
|
|
435
|
+
&& batchStatus.phase === 'idle'
|
|
436
|
+
&& (this.#queues.has(key) || pending || this.#approvals.hasPending(key))
|
|
437
|
+
? { handled: true, kind: 'busy', message: batchInputBusyMessage() }
|
|
438
|
+
: this.#batchInputs.handle(key, commandText, {
|
|
439
|
+
plainText: isNativeWeixinText(message)
|
|
440
|
+
&& !extractWeixinReplyReference(message),
|
|
441
|
+
});
|
|
442
|
+
if (result.handled) {
|
|
443
|
+
if (result.kind === 'submit') {
|
|
444
|
+
return this.#enqueueMessage({
|
|
445
|
+
...message,
|
|
446
|
+
item_list: [{ type: 1, text_item: { text: result.prompt } }],
|
|
447
|
+
}, messageId, key, { batchSubmission: result });
|
|
448
|
+
}
|
|
449
|
+
return this.#finishBatchResult(
|
|
450
|
+
message,
|
|
451
|
+
messageId,
|
|
452
|
+
key,
|
|
453
|
+
sender,
|
|
454
|
+
contextToken,
|
|
455
|
+
runId,
|
|
456
|
+
result,
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
const commandRunner = isHistoryCommand(commandText) ? runHistoryCommand
|
|
461
|
+
: hasWeixinFileItems(message) ? null : isControlCommand(commandText)
|
|
462
|
+
? runControlCommand
|
|
463
|
+
: (isModelCommand(commandText)
|
|
464
|
+
? runModelCommand
|
|
465
|
+
: (isPresetCommand(commandText) ? runPresetCommand : null));
|
|
466
|
+
if (commandRunner) {
|
|
467
|
+
let task;
|
|
468
|
+
task = this.#processFastCommand(
|
|
469
|
+
message,
|
|
470
|
+
messageId,
|
|
471
|
+
key,
|
|
472
|
+
sender,
|
|
473
|
+
contextToken,
|
|
474
|
+
runId,
|
|
475
|
+
commandText,
|
|
476
|
+
commandRunner,
|
|
477
|
+
).catch((error) => {
|
|
478
|
+
if (error?.code === 'turn-stopped' || this.#signal?.aborted) return;
|
|
479
|
+
this.#status.lastError = error?.message ?? String(error);
|
|
480
|
+
const failure = setLastMessageFailure(this.#status, error);
|
|
481
|
+
this.#logger.error?.(
|
|
482
|
+
`[dsh-weixin] failed to process a command [${failure.referenceId}]:`,
|
|
483
|
+
messageFailureDiagnostic(error, failure),
|
|
484
|
+
);
|
|
485
|
+
return this.#sendOutOfBand(key, sender, messageFailureText(failure), contextToken, runId)
|
|
486
|
+
.catch(() => undefined);
|
|
487
|
+
}).finally(() => {
|
|
488
|
+
this.#acceptedMessageIds.delete(messageId);
|
|
489
|
+
this.#commandTasks.delete(task);
|
|
490
|
+
});
|
|
491
|
+
this.#commandTasks.add(task);
|
|
492
|
+
return task;
|
|
493
|
+
}
|
|
494
|
+
const approval = this.#approvals.claimReply({
|
|
495
|
+
key,
|
|
496
|
+
actor: sender,
|
|
497
|
+
messageId,
|
|
498
|
+
text: hasWeixinImageItems(message) || hasWeixinFileItems(message)
|
|
499
|
+
? ''
|
|
500
|
+
: extractWeixinText(message),
|
|
501
|
+
addressed: true,
|
|
502
|
+
hasPendingQuestion: Boolean(pending),
|
|
503
|
+
questionCompletion: pending?.submitting || pending?.claimedReplyMessageId
|
|
504
|
+
? pending.queue
|
|
505
|
+
: null,
|
|
506
|
+
isQuestionPending: () => this.#pendingInteractions.has(key),
|
|
507
|
+
send: (text) => this.#send(sender, text, contextToken, runId),
|
|
508
|
+
});
|
|
509
|
+
if (approval) {
|
|
510
|
+
let task;
|
|
511
|
+
task = approval.process(async () => {
|
|
512
|
+
if (this.#state.hasSeen(messageId)) return false;
|
|
513
|
+
await this.#state.markSeen(messageId);
|
|
514
|
+
this.#status.messagesReceived += 1;
|
|
515
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
516
|
+
return true;
|
|
517
|
+
})
|
|
518
|
+
.finally(() => {
|
|
519
|
+
this.#acceptedMessageIds.delete(messageId);
|
|
520
|
+
this.#approvalTasks.delete(task);
|
|
521
|
+
});
|
|
522
|
+
this.#approvalTasks.add(task);
|
|
523
|
+
return task;
|
|
524
|
+
}
|
|
525
|
+
if (pending?.submitting || pending?.claimedReplyMessageId) {
|
|
526
|
+
return this.#enqueueMessage(message, messageId, key);
|
|
527
|
+
}
|
|
528
|
+
if (pending) {
|
|
529
|
+
if (canClaimInteractionReply(message, pending)) {
|
|
530
|
+
pending.claimedReplyMessageId = messageId;
|
|
531
|
+
}
|
|
532
|
+
const previous = pending.queue ?? Promise.resolve();
|
|
533
|
+
const current = previous
|
|
534
|
+
.catch(() => undefined)
|
|
535
|
+
.then(() => this.#processInteractionReply(message, messageId, key, pending))
|
|
536
|
+
.catch((error) => this.#handleInteractionFailure(message, messageId, error))
|
|
537
|
+
.finally(() => {
|
|
538
|
+
this.#acceptedMessageIds.delete(messageId);
|
|
539
|
+
if (pending.claimedReplyMessageId === messageId) pending.claimedReplyMessageId = null;
|
|
540
|
+
if (pending.queue === current) pending.queue = null;
|
|
541
|
+
});
|
|
542
|
+
pending.queue = current;
|
|
543
|
+
return current;
|
|
544
|
+
}
|
|
545
|
+
return this.#enqueueMessage(message, messageId, key);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
#enqueueMessage(message, messageId, key, {
|
|
549
|
+
releaseMessageId = true,
|
|
550
|
+
alreadyRecorded = false,
|
|
551
|
+
batchSubmission = null,
|
|
552
|
+
} = {}) {
|
|
553
|
+
const preparedMessage = prefetchInboundFiles(
|
|
554
|
+
this.#inboundMessage(message),
|
|
555
|
+
{ signal: this.#signal },
|
|
556
|
+
);
|
|
557
|
+
const previous = this.#queues.get(key) ?? Promise.resolve();
|
|
558
|
+
const current = previous
|
|
559
|
+
.catch(() => undefined)
|
|
560
|
+
.then(() => this.#process(message, key, {
|
|
561
|
+
alreadyRecorded,
|
|
562
|
+
preparedMessage,
|
|
563
|
+
batchSubmission,
|
|
564
|
+
}))
|
|
565
|
+
.finally(() => {
|
|
566
|
+
if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
|
|
567
|
+
if (this.#queues.get(key) === current) this.#queues.delete(key);
|
|
568
|
+
});
|
|
569
|
+
this.#queues.set(key, current);
|
|
570
|
+
return current;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
#inboundMessage(message) {
|
|
574
|
+
return weixinInboundMessage(message, this.#api, this.#state, {
|
|
575
|
+
loadReplyContent: (reference, options) => this.#loadReplyContent(reference, options),
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
async #loadReplyContent(reference, { signal: callerSignal } = {}) {
|
|
580
|
+
const indexed = this.#state.recentOutboundTextFor?.(reference);
|
|
581
|
+
if (indexed) return { content: indexed };
|
|
582
|
+
const quotedAt = [
|
|
583
|
+
weixinMessageTimestampMs(reference?.messageId),
|
|
584
|
+
Number(reference?.createTimeMs),
|
|
585
|
+
Number(reference?.updateTimeMs),
|
|
586
|
+
].find(Number.isSafeInteger);
|
|
587
|
+
if (quotedAt === undefined) return { unavailableReason: 'not-delivered' };
|
|
588
|
+
const sender = nonEmptyString(reference?.toUserId);
|
|
589
|
+
const key = sender ? conversationKey(sender) : null;
|
|
590
|
+
const sessionId = key ? this.#state.sessionFor(key) : null;
|
|
591
|
+
const session = typeof sessionId === 'string' && sessionId
|
|
592
|
+
? this.#harness.workspaceSession?.(sessionId, key)
|
|
593
|
+
: null;
|
|
594
|
+
if (typeof session?.readHistory !== 'function') {
|
|
595
|
+
return { unavailableReason: 'not-delivered' };
|
|
596
|
+
}
|
|
597
|
+
const text = await recoverAssistantTextByTimestamp({
|
|
598
|
+
session,
|
|
599
|
+
quotedAt,
|
|
600
|
+
signal: callerSignal,
|
|
601
|
+
pageSize: WEIXIN_REPLY_HISTORY_PAGE_SIZE,
|
|
602
|
+
maxPages: WEIXIN_REPLY_HISTORY_MAX_PAGES,
|
|
603
|
+
timeoutMs: WEIXIN_REPLY_HISTORY_TIMEOUT_MS,
|
|
604
|
+
toleranceMs: WEIXIN_REPLY_HISTORY_MATCH_TOLERANCE_MS,
|
|
605
|
+
});
|
|
606
|
+
if (!text) return { unavailableReason: 'not-delivered' };
|
|
607
|
+
const messageId = nonEmptyString(reference?.messageId);
|
|
608
|
+
try {
|
|
609
|
+
await this.#state.rememberOutboundMessage?.({
|
|
610
|
+
toUserId: sender,
|
|
611
|
+
text,
|
|
612
|
+
sentAt: quotedAt,
|
|
613
|
+
completedAt: quotedAt,
|
|
614
|
+
providerMessageIds: messageId ? [messageId] : [],
|
|
615
|
+
});
|
|
616
|
+
} catch (error) {
|
|
617
|
+
this.#logger.warn?.('[dsh-weixin] failed to remember a recovered quote:', error);
|
|
618
|
+
}
|
|
619
|
+
return { content: text };
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
#finishBatchResult(message, messageId, key, sender, contextToken, runId, result) {
|
|
623
|
+
let task;
|
|
624
|
+
task = Promise.resolve().then(async () => {
|
|
625
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
626
|
+
await this.#state.markSeen(messageId);
|
|
627
|
+
this.#status.messagesReceived += 1;
|
|
628
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
629
|
+
if (result.message) {
|
|
630
|
+
await this.#sendOutOfBand(key, sender, result.message, contextToken, runId);
|
|
631
|
+
}
|
|
632
|
+
this.#status.lastError = null;
|
|
633
|
+
}).catch(async (error) => {
|
|
634
|
+
if (this.#signal?.aborted) return;
|
|
635
|
+
this.#status.lastError = error?.message ?? String(error);
|
|
636
|
+
const failure = setLastMessageFailure(this.#status, error);
|
|
637
|
+
this.#logger.error?.(
|
|
638
|
+
`[dsh-weixin] failed to process a batch input message [${failure.referenceId}]:`,
|
|
639
|
+
messageFailureDiagnostic(error, failure),
|
|
640
|
+
);
|
|
641
|
+
await this.#sendOutOfBand(key, sender, messageFailureText(failure), contextToken, runId)
|
|
642
|
+
.catch(() => undefined);
|
|
643
|
+
}).finally(() => {
|
|
644
|
+
this.#acceptedMessageIds.delete(messageId);
|
|
645
|
+
this.#commandTasks.delete(task);
|
|
646
|
+
});
|
|
647
|
+
this.#commandTasks.add(task);
|
|
648
|
+
return task;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
#finishAccessDecision(messageId, sender, message, access) {
|
|
652
|
+
const contextToken = nonEmptyString(message?.context_token) ?? undefined;
|
|
653
|
+
const runId = nonEmptyString(message?.run_id) ?? undefined;
|
|
654
|
+
let task;
|
|
655
|
+
task = Promise.resolve().then(async () => {
|
|
656
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
657
|
+
await this.#state.markSeen(messageId);
|
|
658
|
+
if (access.reason === 'command-not-allowed') {
|
|
659
|
+
this.#status.messagesReceived += 1;
|
|
660
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
661
|
+
await this.#send(sender, t(COMMAND_PERMISSION_DENIED_MESSAGE), contextToken, runId);
|
|
662
|
+
this.#status.messagesReplied += 1;
|
|
663
|
+
this.#status.lastReplyAt = new Date().toISOString();
|
|
664
|
+
} else {
|
|
665
|
+
this.#status.messagesRejected += 1;
|
|
666
|
+
this.#status.lastRejectedAt = new Date().toISOString();
|
|
667
|
+
}
|
|
668
|
+
this.#status.lastError = null;
|
|
669
|
+
}).catch((error) => {
|
|
670
|
+
if (this.#signal?.aborted) return;
|
|
671
|
+
this.#status.lastError = error?.message ?? String(error);
|
|
672
|
+
this.#logger.error?.('[dsh-weixin] failed to apply inbound access policy:', error);
|
|
673
|
+
}).finally(() => {
|
|
674
|
+
this.#acceptedMessageIds.delete(messageId);
|
|
675
|
+
this.#commandTasks.delete(task);
|
|
676
|
+
});
|
|
677
|
+
this.#commandTasks.add(task);
|
|
678
|
+
return task;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
async #deliverDeferredOutcome(entry, outcome) {
|
|
682
|
+
await this.#send(entry.target.toUserId, deferredOutcomeText(outcome), undefined, undefined, { stopTyping: false });
|
|
683
|
+
return true;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
async waitForIdle() {
|
|
687
|
+
await Promise.allSettled([
|
|
688
|
+
...this.#queues.values(),
|
|
689
|
+
...[...this.#pendingInteractions.values()].flatMap((pending) => (
|
|
690
|
+
pending.queue ? [pending.queue] : []
|
|
691
|
+
)),
|
|
692
|
+
...this.#approvalTasks,
|
|
693
|
+
...this.#commandTasks,
|
|
694
|
+
this.#typingTail,
|
|
695
|
+
]);
|
|
696
|
+
await this.#deferred.whenIdle();
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
async close() {
|
|
700
|
+
this.#deferred.close();
|
|
701
|
+
this.#typingClosed = true;
|
|
702
|
+
await this.#stopTyping({ signal: AbortSignal.timeout(5_000) });
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
async #processFastCommand(
|
|
706
|
+
message,
|
|
707
|
+
messageId,
|
|
708
|
+
key,
|
|
709
|
+
sender,
|
|
710
|
+
contextToken,
|
|
711
|
+
runId,
|
|
712
|
+
text,
|
|
713
|
+
runner,
|
|
714
|
+
) {
|
|
715
|
+
this.#signal?.throwIfAborted();
|
|
716
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
717
|
+
await this.#state.markSeen(messageId);
|
|
718
|
+
this.#status.messagesReceived += 1;
|
|
719
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
720
|
+
const result = await runner(text, this.#harness, this.#state, key, {
|
|
721
|
+
signal: this.#signal,
|
|
722
|
+
isDirect: true,
|
|
723
|
+
hasImages: hasWeixinImageItems(message),
|
|
724
|
+
hasFiles: hasWeixinFileItems(message),
|
|
725
|
+
pendingInteraction: this.#pendingInteractions.has(key)
|
|
726
|
+
|| this.#approvals.hasPending(key),
|
|
727
|
+
control: { owner: this, key },
|
|
728
|
+
deferredDelivery: this.#deferred,
|
|
729
|
+
enhancement: captureContextEnhancementSource(
|
|
730
|
+
this.#contextEnhancement,
|
|
731
|
+
'direct',
|
|
732
|
+
// The moment rides on the factory as a thunk, so a local command that
|
|
733
|
+
// never renders a source block -- and a scope that is off or does not
|
|
734
|
+
// select `sentAt` -- reads nothing from the inbound message.
|
|
735
|
+
withSentAt(
|
|
736
|
+
() => ({ channel: 'weixin', senderId: sender, chatId: sender }),
|
|
737
|
+
// Platform send time, falling back to the iLink message-id clock.
|
|
738
|
+
() => message?.create_time_ms ?? weixinMessageTimestampMs(messageId),
|
|
739
|
+
),
|
|
740
|
+
),
|
|
741
|
+
});
|
|
742
|
+
if (result?.stopped) {
|
|
743
|
+
await Promise.allSettled([
|
|
744
|
+
this.#cancelPendingInteraction(key),
|
|
745
|
+
this.#approvals.closeRoute(key),
|
|
746
|
+
]);
|
|
747
|
+
}
|
|
748
|
+
for (const reply of result?.messages ?? [result?.message]) {
|
|
749
|
+
if (!reply) continue;
|
|
750
|
+
if (result?.stopped) {
|
|
751
|
+
await this.#send(sender, reply, contextToken, runId);
|
|
752
|
+
} else {
|
|
753
|
+
await this.#sendOutOfBand(key, sender, reply, contextToken, runId);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
this.#status.lastError = null;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
async #process(message, key, {
|
|
760
|
+
alreadyRecorded = false,
|
|
761
|
+
preparedMessage,
|
|
762
|
+
batchSubmission = null,
|
|
763
|
+
} = {}) {
|
|
764
|
+
this.#signal?.throwIfAborted();
|
|
765
|
+
const messageId = weixinMessageId(message);
|
|
766
|
+
const sender = nonEmptyString(message?.from_user_id);
|
|
767
|
+
if (!messageId || !sender) return;
|
|
768
|
+
if (!alreadyRecorded) {
|
|
769
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
770
|
+
this.#status.messagesReceived += 1;
|
|
771
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
772
|
+
}
|
|
773
|
+
const contextToken = typeof message.context_token === 'string' ? message.context_token : undefined;
|
|
774
|
+
const runId = typeof message.run_id === 'string' ? message.run_id : undefined;
|
|
775
|
+
let batchSettled = batchSubmission === null;
|
|
776
|
+
let promptRecorded = false;
|
|
777
|
+
try {
|
|
778
|
+
const promptMessage = preparedMessage ?? this.#inboundMessage(message);
|
|
779
|
+
const text = promptMessage.content;
|
|
780
|
+
const hasImages = hasInboundImages(promptMessage);
|
|
781
|
+
const hasFiles = hasInboundFiles(promptMessage);
|
|
782
|
+
const hasReply = hasReplyReference(promptMessage);
|
|
783
|
+
if (!text && !hasImages && !hasFiles && !hasReply) {
|
|
784
|
+
await this.#send(sender, t('目前支持文字、图片、文件,以及微信已转成文字的语音消息。'), contextToken, runId);
|
|
785
|
+
await this.#state.markSeen(messageId);
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
const command = text.trim().toLowerCase();
|
|
790
|
+
if (!hasImages && !hasFiles && command === '/help') {
|
|
791
|
+
await this.#send(sender, HELP_TEXT(), contextToken, runId);
|
|
792
|
+
await this.#state.markSeen(messageId);
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
if (!hasImages && !hasFiles && command === '/status') {
|
|
796
|
+
await this.#harness.ensureRunning({ signal: this.#signal });
|
|
797
|
+
await this.#send(sender, t('微信与 DeepSeek Harness 连接正常。'), contextToken, runId);
|
|
798
|
+
await this.#state.markSeen(messageId);
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
if (!hasImages && !hasFiles && command === '/new') {
|
|
802
|
+
await this.#state.clearSession(key);
|
|
803
|
+
await this.#send(sender, t('已开启新会话。请发送你的问题。'), contextToken, runId);
|
|
804
|
+
await this.#state.markSeen(messageId);
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
const workspaceCommand = hasImages || hasFiles
|
|
808
|
+
? null
|
|
809
|
+
: await runWorkspaceCommand(text, this.#harness, key);
|
|
810
|
+
if (workspaceCommand) {
|
|
811
|
+
for (const reply of workspaceCommand.messages ?? [workspaceCommand.message]) {
|
|
812
|
+
await this.#send(sender, reply, contextToken, runId);
|
|
813
|
+
}
|
|
814
|
+
await this.#state.markSeen(messageId);
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
const compactCommand = hasImages || hasFiles
|
|
818
|
+
? null
|
|
819
|
+
: await runCompactCommand(
|
|
820
|
+
text,
|
|
821
|
+
this.#harness,
|
|
822
|
+
this.#state,
|
|
823
|
+
key,
|
|
824
|
+
{ signal: this.#signal },
|
|
825
|
+
);
|
|
826
|
+
if (compactCommand) {
|
|
827
|
+
await this.#send(sender, compactCommand.message, contextToken, runId);
|
|
828
|
+
await this.#state.markSeen(messageId);
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
let answer;
|
|
833
|
+
let artifacts = [];
|
|
834
|
+
await this.#startTyping(sender, contextToken);
|
|
835
|
+
try {
|
|
836
|
+
let content = hasImages || hasReply
|
|
837
|
+
? await promptContentForInboundMessage(promptMessage, { signal: this.#signal, deferImages: true })
|
|
838
|
+
: undefined;
|
|
839
|
+
const captured = this.#acceptedMessageIds.get(messageId);
|
|
840
|
+
let contextEnhanced = false;
|
|
841
|
+
if (captured) {
|
|
842
|
+
const originalContent = content ?? text;
|
|
843
|
+
// The capture already carries the moment its own source published, so
|
|
844
|
+
// `enhanceContextContent` accepts it as-is: passing only `.snapshot`
|
|
845
|
+
// here would drop `sentAt` and silently render no block at all.
|
|
846
|
+
content = enhanceContextContent(originalContent, captured);
|
|
847
|
+
contextEnhanced = content !== originalContent;
|
|
848
|
+
}
|
|
849
|
+
await this.#state.markSeen(messageId);
|
|
850
|
+
promptRecorded = true;
|
|
851
|
+
({ answer, artifacts = [] } = await askInWorkspaceSession({
|
|
852
|
+
deferredDelivery: () => ({ coordinator: this.#deferred, target: { toUserId: sender } }),
|
|
853
|
+
harness: this.#harness,
|
|
854
|
+
state: this.#state,
|
|
855
|
+
key,
|
|
856
|
+
text,
|
|
857
|
+
content,
|
|
858
|
+
titleText: batchSubmission?.title,
|
|
859
|
+
sourceGuidance: captured?.snapshot?.config?.guidance,
|
|
860
|
+
contextEnhanced,
|
|
861
|
+
createOptions: { signal: this.#signal },
|
|
862
|
+
existsOptions: { signal: this.#signal },
|
|
863
|
+
askOptions: {
|
|
864
|
+
timeoutMs: this.#replyTimeoutMs,
|
|
865
|
+
signal: this.#signal,
|
|
866
|
+
control: { owner: this, key },
|
|
867
|
+
onUpdate: () => this.#resumeTyping(key, sender, contextToken),
|
|
868
|
+
onInteraction: (interaction) => this.#handleInteraction(interaction, {
|
|
869
|
+
key,
|
|
870
|
+
actor: sender,
|
|
871
|
+
contextToken,
|
|
872
|
+
runId,
|
|
873
|
+
}),
|
|
874
|
+
onInteractionResolved: async (resolution) => {
|
|
875
|
+
await this.#handleInteractionResolved(resolution);
|
|
876
|
+
await this.#resumeTyping(key, sender, contextToken);
|
|
877
|
+
},
|
|
878
|
+
files: promptMessage.files,
|
|
879
|
+
images: promptMessage.images,
|
|
880
|
+
},
|
|
881
|
+
}));
|
|
882
|
+
if (batchSubmission) {
|
|
883
|
+
this.#batchInputs.complete(key, batchSubmission.token);
|
|
884
|
+
batchSettled = true;
|
|
885
|
+
}
|
|
886
|
+
} finally {
|
|
887
|
+
await Promise.allSettled([
|
|
888
|
+
this.#stopTyping(),
|
|
889
|
+
this.#cancelPendingInteraction(key),
|
|
890
|
+
this.#approvals.closeRoute(key),
|
|
891
|
+
]);
|
|
892
|
+
}
|
|
893
|
+
const answerText = typeof answer === 'string' && answer.trim()
|
|
894
|
+
? answer
|
|
895
|
+
: artifacts.length > 0 ? t('结果文件已生成。') : answer;
|
|
896
|
+
let textDeliveryError = null;
|
|
897
|
+
let textReceipt = null;
|
|
898
|
+
try {
|
|
899
|
+
textReceipt = createDeliveryReceipt({
|
|
900
|
+
deliveryId: messageId,
|
|
901
|
+
presentation: 'weixin-text',
|
|
902
|
+
providerMessageIds: await this.#send(sender, answerText, contextToken, runId),
|
|
903
|
+
});
|
|
904
|
+
} catch (error) {
|
|
905
|
+
textDeliveryError = channelDeliveryFailure(error);
|
|
906
|
+
}
|
|
907
|
+
const delivery = await this.#deliverArtifacts(
|
|
908
|
+
sender,
|
|
909
|
+
messageId,
|
|
910
|
+
artifacts,
|
|
911
|
+
contextToken,
|
|
912
|
+
runId,
|
|
913
|
+
textReceipt,
|
|
914
|
+
);
|
|
915
|
+
if (textDeliveryError && !delivery.userVisible) throw textDeliveryError;
|
|
916
|
+
if (textDeliveryError && delivery.artifactSendErrors === 0) {
|
|
917
|
+
setLastMessageFailure(
|
|
918
|
+
this.#status,
|
|
919
|
+
textDeliveryError,
|
|
920
|
+
weixinSendFailureOptions(textDeliveryError),
|
|
921
|
+
);
|
|
922
|
+
}
|
|
923
|
+
if (!promptRecorded) await this.#state.markSeen(messageId);
|
|
924
|
+
this.#status.messagesReplied += 1;
|
|
925
|
+
this.#status.lastReplyAt = new Date().toISOString();
|
|
926
|
+
this.#status.lastError = null;
|
|
927
|
+
if (!textDeliveryError && delivery.artifactSendErrors === 0) {
|
|
928
|
+
clearLastMessageFailure(this.#status);
|
|
929
|
+
}
|
|
930
|
+
return delivery.receipt;
|
|
931
|
+
} catch (error) {
|
|
932
|
+
let batchFailureMessage = null;
|
|
933
|
+
if (!batchSettled && batchSubmission) {
|
|
934
|
+
if (error?.code === 'turn-stopped') {
|
|
935
|
+
this.#batchInputs.complete(key, batchSubmission.token);
|
|
936
|
+
} else {
|
|
937
|
+
batchFailureMessage = this.#batchInputs.fail(key, batchSubmission.token).message ?? null;
|
|
938
|
+
}
|
|
939
|
+
batchSettled = true;
|
|
940
|
+
}
|
|
941
|
+
if (error?.code === 'turn-stopped') {
|
|
942
|
+
if (!promptRecorded) await this.#state.markSeen(messageId);
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
if (this.#signal?.aborted) return;
|
|
946
|
+
this.#status.lastError = error?.message ?? String(error);
|
|
947
|
+
const userMessage = inboundFileUserMessage(error)
|
|
948
|
+
?? imagePromptUserMessage(error);
|
|
949
|
+
const imageDiagnostic = imagePromptDiagnostic(error);
|
|
950
|
+
const sendFailureOptions = weixinSendFailureOptions(error);
|
|
951
|
+
const failure = setLastMessageFailure(this.#status, error, {
|
|
952
|
+
userMessage: userMessage ?? sendFailureOptions?.userMessage,
|
|
953
|
+
reason: imageDiagnostic?.reason ?? sendFailureOptions?.reason,
|
|
954
|
+
});
|
|
955
|
+
this.#logger.error?.(
|
|
956
|
+
`[dsh-weixin] failed to process an inbound message [${failure.referenceId}]:`,
|
|
957
|
+
messageFailureDiagnostic(error, failure),
|
|
958
|
+
);
|
|
959
|
+
try {
|
|
960
|
+
await this.#send(
|
|
961
|
+
sender,
|
|
962
|
+
batchFailureMessage
|
|
963
|
+
? `${messageFailureText(failure)}\n\n${batchFailureMessage}`
|
|
964
|
+
: messageFailureText(failure),
|
|
965
|
+
contextToken,
|
|
966
|
+
runId,
|
|
967
|
+
);
|
|
968
|
+
if (!promptRecorded) await this.#state.markSeen(messageId);
|
|
969
|
+
} catch (sendError) {
|
|
970
|
+
this.#logger.error?.('[dsh-weixin] failed to send the safe error reply:', sendError);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
async #processInteractionReply(message, messageId, key, expected) {
|
|
976
|
+
this.#signal?.throwIfAborted();
|
|
977
|
+
const current = this.#pendingInteractions.get(key);
|
|
978
|
+
const claimed = expected.claimedReplyMessageId === messageId;
|
|
979
|
+
if (!current || current !== expected || current.submitting) {
|
|
980
|
+
if (claimed && (!current || current !== expected)) {
|
|
981
|
+
return this.#discardResolvedInteractionReply(message, messageId);
|
|
982
|
+
}
|
|
983
|
+
return this.#enqueueMessage(message, messageId, key, { releaseMessageId: false });
|
|
984
|
+
}
|
|
985
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
986
|
+
await this.#state.markSeen(messageId);
|
|
987
|
+
this.#status.messagesReceived += 1;
|
|
988
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
989
|
+
|
|
990
|
+
const text = nonEmptyString(extractWeixinText(message));
|
|
991
|
+
const contextToken = nonEmptyString(message?.context_token) ?? undefined;
|
|
992
|
+
const runId = nonEmptyString(message?.run_id) ?? undefined;
|
|
993
|
+
if (!text || hasWeixinImageItems(message)) {
|
|
994
|
+
await this.#send(
|
|
995
|
+
expected.actor,
|
|
996
|
+
t('请用文字回答当前问题。'),
|
|
997
|
+
contextToken,
|
|
998
|
+
runId,
|
|
999
|
+
);
|
|
1000
|
+
return;
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
const pending = this.#pendingInteractions.get(key);
|
|
1004
|
+
if (!pending || pending !== expected || pending.submitting) {
|
|
1005
|
+
if (claimed && (!pending || pending !== expected)) {
|
|
1006
|
+
await this.#send(
|
|
1007
|
+
expected.actor,
|
|
1008
|
+
INTERACTION_RESOLVED_TEXT(),
|
|
1009
|
+
contextToken,
|
|
1010
|
+
runId,
|
|
1011
|
+
);
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
return this.#enqueueMessage(message, messageId, key, {
|
|
1015
|
+
releaseMessageId: false,
|
|
1016
|
+
alreadyRecorded: true,
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
pending.contextToken = contextToken;
|
|
1020
|
+
pending.runId = runId;
|
|
1021
|
+
if (pending.needsPresentation) {
|
|
1022
|
+
try {
|
|
1023
|
+
await this.#presentInteraction(pending);
|
|
1024
|
+
} catch {
|
|
1025
|
+
this.#status.lastError = t('微信交互问题发送失败。');
|
|
1026
|
+
this.#logger.error?.('[dsh-weixin] failed to retry an interaction question');
|
|
1027
|
+
pending.interaction.reconnect?.();
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
const presentedPending = this.#pendingInteractions.get(key);
|
|
1031
|
+
if (!presentedPending || presentedPending !== expected || presentedPending.submitting) {
|
|
1032
|
+
if (claimed && (!presentedPending || presentedPending !== expected)) {
|
|
1033
|
+
await this.#send(
|
|
1034
|
+
expected.actor,
|
|
1035
|
+
INTERACTION_RESOLVED_TEXT(),
|
|
1036
|
+
contextToken,
|
|
1037
|
+
runId,
|
|
1038
|
+
).catch(() => undefined);
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
return this.#enqueueMessage(message, messageId, key, {
|
|
1042
|
+
releaseMessageId: false,
|
|
1043
|
+
alreadyRecorded: true,
|
|
1044
|
+
});
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
const question = pending.questions[pending.index];
|
|
1049
|
+
if (!question) return;
|
|
1050
|
+
pending.answers.push(harnessAnswerForQuestion(question, text));
|
|
1051
|
+
pending.index += 1;
|
|
1052
|
+
if (pending.index < pending.questions.length) {
|
|
1053
|
+
if (pending.claimedReplyMessageId === messageId) {
|
|
1054
|
+
pending.claimedReplyMessageId = null;
|
|
1055
|
+
}
|
|
1056
|
+
pending.needsPresentation = true;
|
|
1057
|
+
try {
|
|
1058
|
+
await this.#presentInteraction(pending);
|
|
1059
|
+
} catch {
|
|
1060
|
+
this.#status.lastError = t('微信交互问题发送失败。');
|
|
1061
|
+
this.#logger.error?.('[dsh-weixin] failed to send the next interaction question');
|
|
1062
|
+
pending.interaction.reconnect?.();
|
|
1063
|
+
}
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
pending.submitting = true;
|
|
1068
|
+
try {
|
|
1069
|
+
await pending.interaction.respond({
|
|
1070
|
+
ok: true,
|
|
1071
|
+
value: {
|
|
1072
|
+
sessionId: pending.sessionId,
|
|
1073
|
+
answer: { answers: pending.answers },
|
|
1074
|
+
},
|
|
1075
|
+
});
|
|
1076
|
+
this.#clearPendingInteraction(key, pending.interactionId);
|
|
1077
|
+
this.#status.lastError = null;
|
|
1078
|
+
} catch (error) {
|
|
1079
|
+
if (this.#signal?.aborted) return;
|
|
1080
|
+
if (error?.code === 'interaction-not-pending') {
|
|
1081
|
+
this.#clearPendingInteraction(key, pending.interactionId);
|
|
1082
|
+
await this.#send(
|
|
1083
|
+
pending.actor,
|
|
1084
|
+
INTERACTION_RESOLVED_TEXT(),
|
|
1085
|
+
pending.contextToken,
|
|
1086
|
+
pending.runId,
|
|
1087
|
+
).catch(() => undefined);
|
|
1088
|
+
return;
|
|
1089
|
+
}
|
|
1090
|
+
if (this.#pendingInteractions.get(key) !== pending) return;
|
|
1091
|
+
pending.submitting = false;
|
|
1092
|
+
pending.answers.pop();
|
|
1093
|
+
pending.index -= 1;
|
|
1094
|
+
this.#status.lastError = t('回答提交失败。');
|
|
1095
|
+
this.#logger.error?.('[dsh-weixin] failed to answer a Harness interaction');
|
|
1096
|
+
await this.#send(
|
|
1097
|
+
pending.actor,
|
|
1098
|
+
t('回答提交失败,请重新发送当前问题的答案。'),
|
|
1099
|
+
pending.contextToken,
|
|
1100
|
+
pending.runId,
|
|
1101
|
+
).catch(() => undefined);
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
async #handleInteraction(interaction, {
|
|
1106
|
+
key,
|
|
1107
|
+
actor,
|
|
1108
|
+
contextToken,
|
|
1109
|
+
runId,
|
|
1110
|
+
}) {
|
|
1111
|
+
if (interaction?.kind === 'approval') {
|
|
1112
|
+
return this.#approvals.handleRequested(interaction, {
|
|
1113
|
+
key,
|
|
1114
|
+
actor,
|
|
1115
|
+
send: (text) => this.#send(actor, text, contextToken, runId),
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
if (interaction?.kind !== 'question') return;
|
|
1119
|
+
const questions = interaction?.payload?.questions;
|
|
1120
|
+
const interactionId = typeof interaction?.interactionId === 'string'
|
|
1121
|
+
? interaction.interactionId
|
|
1122
|
+
: interaction?.rpcId;
|
|
1123
|
+
if (typeof interaction?.rpcId !== 'string'
|
|
1124
|
+
|| typeof interactionId !== 'string'
|
|
1125
|
+
|| typeof interaction.sessionId !== 'string'
|
|
1126
|
+
|| !Array.isArray(questions)
|
|
1127
|
+
|| questions.length === 0
|
|
1128
|
+
|| questions.some((question) => !validHarnessQuestion(question))) {
|
|
1129
|
+
this.#logger.warn?.('[dsh-weixin] ignored an invalid Harness question interaction');
|
|
1130
|
+
return;
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
if (interaction.recovered === true) {
|
|
1134
|
+
await interaction.respond({
|
|
1135
|
+
ok: false,
|
|
1136
|
+
error: {
|
|
1137
|
+
code: 'cancelled',
|
|
1138
|
+
message: 'Weixin safely cancelled an interaction left by an earlier client.',
|
|
1139
|
+
details: {},
|
|
1140
|
+
},
|
|
1141
|
+
});
|
|
1142
|
+
await this.#send(
|
|
1143
|
+
actor,
|
|
1144
|
+
t('检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。'),
|
|
1145
|
+
contextToken,
|
|
1146
|
+
runId,
|
|
1147
|
+
).catch(() => undefined);
|
|
1148
|
+
return;
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
const existing = this.#pendingInteractions.get(key);
|
|
1152
|
+
if (existing?.interactionId === interactionId) {
|
|
1153
|
+
existing.interaction = interaction;
|
|
1154
|
+
if (existing.needsPresentation) await this.#presentInteraction(existing);
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
if (this.#interactionKeys.has(interactionId)) return;
|
|
1158
|
+
if (existing) {
|
|
1159
|
+
await interaction.respond({
|
|
1160
|
+
ok: false,
|
|
1161
|
+
error: {
|
|
1162
|
+
code: 'cancelled',
|
|
1163
|
+
message: 'Weixin is already handling another user interaction.',
|
|
1164
|
+
details: {},
|
|
1165
|
+
},
|
|
1166
|
+
});
|
|
1167
|
+
return;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
const pending = {
|
|
1171
|
+
kind: 'question',
|
|
1172
|
+
interactionId,
|
|
1173
|
+
sessionId: interaction.sessionId,
|
|
1174
|
+
interaction,
|
|
1175
|
+
actor,
|
|
1176
|
+
questions,
|
|
1177
|
+
answers: [],
|
|
1178
|
+
index: 0,
|
|
1179
|
+
contextToken,
|
|
1180
|
+
runId,
|
|
1181
|
+
queue: null,
|
|
1182
|
+
claimedReplyMessageId: null,
|
|
1183
|
+
presentationPromise: null,
|
|
1184
|
+
submitting: false,
|
|
1185
|
+
needsPresentation: true,
|
|
1186
|
+
};
|
|
1187
|
+
this.#pendingInteractions.set(key, pending);
|
|
1188
|
+
this.#interactionKeys.set(interactionId, key);
|
|
1189
|
+
await this.#presentInteraction(pending);
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
async #handleInteractionResolved(resolution) {
|
|
1193
|
+
if (resolution?.kind === 'approval') {
|
|
1194
|
+
await this.#approvals.handleResolved(resolution);
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
const interactionId = resolution?.interactionId;
|
|
1198
|
+
if (resolution?.kind !== 'question' || typeof interactionId !== 'string') return;
|
|
1199
|
+
const key = this.#interactionKeys.get(interactionId);
|
|
1200
|
+
if (!key) return;
|
|
1201
|
+
this.#clearPendingInteraction(key, interactionId);
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
#presentInteraction(pending) {
|
|
1205
|
+
if (!pending.needsPresentation) return Promise.resolve();
|
|
1206
|
+
if (pending.presentationPromise) return pending.presentationPromise;
|
|
1207
|
+
const question = pending.questions[pending.index];
|
|
1208
|
+
if (!question) return Promise.resolve();
|
|
1209
|
+
const presentation = this.#send(
|
|
1210
|
+
pending.actor,
|
|
1211
|
+
harnessQuestionText(question, pending.index, pending.questions.length),
|
|
1212
|
+
pending.contextToken,
|
|
1213
|
+
pending.runId,
|
|
1214
|
+
).then(() => {
|
|
1215
|
+
pending.needsPresentation = false;
|
|
1216
|
+
}).finally(() => {
|
|
1217
|
+
if (pending.presentationPromise === presentation) pending.presentationPromise = null;
|
|
1218
|
+
});
|
|
1219
|
+
pending.presentationPromise = presentation;
|
|
1220
|
+
return presentation;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
async #discardResolvedInteractionReply(message, messageId) {
|
|
1224
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
1225
|
+
await this.#state.markSeen(messageId);
|
|
1226
|
+
this.#status.messagesReceived += 1;
|
|
1227
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
1228
|
+
await this.#send(
|
|
1229
|
+
nonEmptyString(message?.from_user_id),
|
|
1230
|
+
INTERACTION_RESOLVED_TEXT(),
|
|
1231
|
+
nonEmptyString(message?.context_token) ?? undefined,
|
|
1232
|
+
nonEmptyString(message?.run_id) ?? undefined,
|
|
1233
|
+
).catch(() => undefined);
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
#takePendingInteraction(key, interactionId) {
|
|
1237
|
+
const pending = this.#pendingInteractions.get(key);
|
|
1238
|
+
if (!pending
|
|
1239
|
+
|| (interactionId !== undefined && pending.interactionId !== interactionId)) return null;
|
|
1240
|
+
this.#pendingInteractions.delete(key);
|
|
1241
|
+
this.#interactionKeys.delete(pending.interactionId);
|
|
1242
|
+
return pending;
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
#clearPendingInteraction(key, interactionId) {
|
|
1246
|
+
return this.#takePendingInteraction(key, interactionId) !== null;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
async #cancelPendingInteraction(key) {
|
|
1250
|
+
const pending = this.#takePendingInteraction(key);
|
|
1251
|
+
if (!pending || pending.kind !== 'question') return;
|
|
1252
|
+
try {
|
|
1253
|
+
await pending.interaction.respond({
|
|
1254
|
+
ok: false,
|
|
1255
|
+
error: {
|
|
1256
|
+
code: 'cancelled',
|
|
1257
|
+
message: 'The Weixin interaction ended before the user answered.',
|
|
1258
|
+
details: {},
|
|
1259
|
+
},
|
|
1260
|
+
}, { signal: AbortSignal.timeout(5_000) });
|
|
1261
|
+
} catch (error) {
|
|
1262
|
+
if (error?.code !== 'interaction-not-pending') {
|
|
1263
|
+
this.#logger.warn?.('[dsh-weixin] failed to cancel a pending Harness interaction');
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
async #handleInteractionFailure(message, messageId, error) {
|
|
1269
|
+
if (this.#signal?.aborted) return;
|
|
1270
|
+
this.#status.lastError = error?.message ?? String(error);
|
|
1271
|
+
const failure = setLastMessageFailure(this.#status, error);
|
|
1272
|
+
this.#logger.error?.(
|
|
1273
|
+
`[dsh-weixin] failed to process an interaction reply [${failure.referenceId}]:`,
|
|
1274
|
+
messageFailureDiagnostic(error, failure),
|
|
1275
|
+
);
|
|
1276
|
+
if (!this.#state.hasSeen(messageId)) {
|
|
1277
|
+
await this.#state.markSeen(messageId).catch(() => undefined);
|
|
1278
|
+
}
|
|
1279
|
+
await this.#send(
|
|
1280
|
+
nonEmptyString(message?.from_user_id),
|
|
1281
|
+
messageFailureText(failure),
|
|
1282
|
+
nonEmptyString(message?.context_token) ?? undefined,
|
|
1283
|
+
nonEmptyString(message?.run_id) ?? undefined,
|
|
1284
|
+
).catch(() => undefined);
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
async #send(toUserId, text, contextToken, runId, { stopTyping = true } = {}) {
|
|
1288
|
+
if (stopTyping) await this.#stopTyping();
|
|
1289
|
+
contextToken ??= this.#state.contextTokenFor?.(toUserId);
|
|
1290
|
+
const providerMessageIds = [];
|
|
1291
|
+
const chunks = splitWeixinText(text, this.#maxMessageChars);
|
|
1292
|
+
for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex += 1) {
|
|
1293
|
+
const chunk = chunks[chunkIndex];
|
|
1294
|
+
const sentAt = Date.now();
|
|
1295
|
+
try {
|
|
1296
|
+
const result = await this.#api.sendText({
|
|
1297
|
+
baseUrl: this.#baseUrl,
|
|
1298
|
+
token: this.#token,
|
|
1299
|
+
toUserId,
|
|
1300
|
+
text: chunk,
|
|
1301
|
+
contextToken,
|
|
1302
|
+
runId,
|
|
1303
|
+
signal: this.#signal,
|
|
1304
|
+
});
|
|
1305
|
+
const chunkMessageIds = providerMessageIdsFor(result);
|
|
1306
|
+
providerMessageIds.push(...chunkMessageIds);
|
|
1307
|
+
try {
|
|
1308
|
+
await this.#state.rememberOutboundMessage?.({
|
|
1309
|
+
toUserId,
|
|
1310
|
+
text: chunk,
|
|
1311
|
+
sentAt,
|
|
1312
|
+
completedAt: Date.now(),
|
|
1313
|
+
providerMessageIds: chunkMessageIds,
|
|
1314
|
+
});
|
|
1315
|
+
} catch (error) {
|
|
1316
|
+
this.#logger.warn?.('[dsh-weixin] failed to remember an outbound message:', error);
|
|
1317
|
+
}
|
|
1318
|
+
} catch (error) {
|
|
1319
|
+
throw weixinSendError(error, {
|
|
1320
|
+
baseUrl: this.#baseUrl,
|
|
1321
|
+
text,
|
|
1322
|
+
chunk,
|
|
1323
|
+
chunkIndex,
|
|
1324
|
+
chunkCount: chunks.length,
|
|
1325
|
+
maxMessageChars: this.#maxMessageChars,
|
|
1326
|
+
contextToken,
|
|
1327
|
+
runId,
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
return providerMessageIds;
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
async #sendOutOfBand(key, toUserId, text, contextToken, runId) {
|
|
1335
|
+
try {
|
|
1336
|
+
return await this.#send(toUserId, text, contextToken, runId);
|
|
1337
|
+
} finally {
|
|
1338
|
+
if (this.#queues.has(key)) {
|
|
1339
|
+
await this.#resumeTyping(key, toUserId, contextToken);
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
#queueTyping(operation) {
|
|
1345
|
+
const task = this.#typingTail
|
|
1346
|
+
.catch(() => undefined)
|
|
1347
|
+
.then(operation);
|
|
1348
|
+
this.#typingTail = task.catch(() => undefined);
|
|
1349
|
+
return task;
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
async #startTyping(toUserId, contextToken) {
|
|
1353
|
+
const target = nonEmptyString(toUserId);
|
|
1354
|
+
if (!target
|
|
1355
|
+
|| this.#typingClosed
|
|
1356
|
+
|| this.#signal?.aborted
|
|
1357
|
+
|| Date.now() < this.#typingRetryAt
|
|
1358
|
+
|| typeof this.#api.getConfig !== 'function'
|
|
1359
|
+
|| typeof this.#api.sendTyping !== 'function') return false;
|
|
1360
|
+
if (this.#typingTarget === target) return true;
|
|
1361
|
+
|
|
1362
|
+
const generation = ++this.#typingGeneration;
|
|
1363
|
+
try {
|
|
1364
|
+
return await this.#queueTyping(async () => {
|
|
1365
|
+
if (generation !== this.#typingGeneration || this.#typingClosed) return false;
|
|
1366
|
+
let ticket = this.#typingTicket;
|
|
1367
|
+
if (!ticket) {
|
|
1368
|
+
const config = await this.#api.getConfig({
|
|
1369
|
+
baseUrl: this.#baseUrl,
|
|
1370
|
+
token: this.#token,
|
|
1371
|
+
toUserId: target,
|
|
1372
|
+
contextToken,
|
|
1373
|
+
signal: this.#signal,
|
|
1374
|
+
});
|
|
1375
|
+
ticket = nonEmptyString(config?.typingTicket);
|
|
1376
|
+
if (!ticket) {
|
|
1377
|
+
this.#typingRetryAt = Date.now() + TYPING_RETRY_DELAY_MS;
|
|
1378
|
+
return false;
|
|
1379
|
+
}
|
|
1380
|
+
if (generation !== this.#typingGeneration || this.#typingClosed) return false;
|
|
1381
|
+
this.#typingTicket = ticket;
|
|
1382
|
+
this.#typingRetryAt = 0;
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
this.#typingTarget = target;
|
|
1386
|
+
await this.#api.sendTyping({
|
|
1387
|
+
baseUrl: this.#baseUrl,
|
|
1388
|
+
token: this.#token,
|
|
1389
|
+
toUserId: target,
|
|
1390
|
+
typingTicket: ticket,
|
|
1391
|
+
status: 1,
|
|
1392
|
+
signal: this.#signal,
|
|
1393
|
+
});
|
|
1394
|
+
if (generation !== this.#typingGeneration || this.#typingClosed) return false;
|
|
1395
|
+
this.#typingTicketStale = false;
|
|
1396
|
+
this.#typingRetryAt = 0;
|
|
1397
|
+
this.#scheduleTyping(generation);
|
|
1398
|
+
return true;
|
|
1399
|
+
});
|
|
1400
|
+
} catch (error) {
|
|
1401
|
+
if (generation === this.#typingGeneration) {
|
|
1402
|
+
this.#clearTypingTimer();
|
|
1403
|
+
this.#typingTicketStale = Boolean(this.#typingTarget && this.#typingTicket);
|
|
1404
|
+
this.#typingRetryAt = Date.now() + TYPING_RETRY_DELAY_MS;
|
|
1405
|
+
}
|
|
1406
|
+
if (!this.#signal?.aborted && !this.#typingClosed) {
|
|
1407
|
+
this.#logger.warn?.('[dsh-weixin] typing indicator failed:', error);
|
|
1408
|
+
}
|
|
1409
|
+
return false;
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
async #stopTyping({ signal = AbortSignal.timeout(5_000) } = {}) {
|
|
1414
|
+
++this.#typingGeneration;
|
|
1415
|
+
this.#clearTypingTimer();
|
|
1416
|
+
const target = this.#typingTarget;
|
|
1417
|
+
const ticket = this.#typingTicket;
|
|
1418
|
+
const stale = this.#typingTicketStale;
|
|
1419
|
+
this.#typingTarget = null;
|
|
1420
|
+
if (typeof this.#api.sendTyping !== 'function') return false;
|
|
1421
|
+
try {
|
|
1422
|
+
return await this.#queueTyping(async () => {
|
|
1423
|
+
if (!target || !ticket) return false;
|
|
1424
|
+
try {
|
|
1425
|
+
await this.#api.sendTyping({
|
|
1426
|
+
baseUrl: this.#baseUrl,
|
|
1427
|
+
token: this.#token,
|
|
1428
|
+
toUserId: target,
|
|
1429
|
+
typingTicket: ticket,
|
|
1430
|
+
status: 2,
|
|
1431
|
+
signal,
|
|
1432
|
+
});
|
|
1433
|
+
} finally {
|
|
1434
|
+
if (stale && this.#typingTicket === ticket) this.#typingTicket = null;
|
|
1435
|
+
this.#typingTicketStale = false;
|
|
1436
|
+
}
|
|
1437
|
+
return true;
|
|
1438
|
+
});
|
|
1439
|
+
} catch (error) {
|
|
1440
|
+
if (!signal?.aborted) {
|
|
1441
|
+
this.#logger.warn?.('[dsh-weixin] typing cancellation failed:', error);
|
|
1442
|
+
}
|
|
1443
|
+
return false;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
#scheduleTyping(generation) {
|
|
1448
|
+
this.#clearTypingTimer();
|
|
1449
|
+
if (generation !== this.#typingGeneration || !this.#typingTarget || this.#typingClosed) return;
|
|
1450
|
+
const timer = setTimeout(() => {
|
|
1451
|
+
if (this.#typingTimer === timer) this.#typingTimer = null;
|
|
1452
|
+
void this.#queueTyping(async () => {
|
|
1453
|
+
if (generation !== this.#typingGeneration || !this.#typingTarget || this.#typingClosed) {
|
|
1454
|
+
return false;
|
|
1455
|
+
}
|
|
1456
|
+
await this.#api.sendTyping({
|
|
1457
|
+
baseUrl: this.#baseUrl,
|
|
1458
|
+
token: this.#token,
|
|
1459
|
+
toUserId: this.#typingTarget,
|
|
1460
|
+
typingTicket: this.#typingTicket,
|
|
1461
|
+
status: 1,
|
|
1462
|
+
signal: this.#signal,
|
|
1463
|
+
});
|
|
1464
|
+
return true;
|
|
1465
|
+
}).then((sent) => {
|
|
1466
|
+
if (sent) this.#scheduleTyping(generation);
|
|
1467
|
+
}).catch((error) => {
|
|
1468
|
+
if (generation !== this.#typingGeneration) return;
|
|
1469
|
+
this.#typingTicketStale = Boolean(this.#typingTarget && this.#typingTicket);
|
|
1470
|
+
this.#typingRetryAt = Date.now() + TYPING_RETRY_DELAY_MS;
|
|
1471
|
+
if (!this.#signal?.aborted && !this.#typingClosed) {
|
|
1472
|
+
this.#logger.warn?.('[dsh-weixin] typing keepalive failed:', error);
|
|
1473
|
+
}
|
|
1474
|
+
});
|
|
1475
|
+
}, this.#typingKeepaliveMs);
|
|
1476
|
+
timer.unref?.();
|
|
1477
|
+
this.#typingTimer = timer;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
#clearTypingTimer() {
|
|
1481
|
+
if (this.#typingTimer) clearTimeout(this.#typingTimer);
|
|
1482
|
+
this.#typingTimer = null;
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
#resumeTyping(key, toUserId, contextToken) {
|
|
1486
|
+
if (this.#pendingInteractions.has(key) || this.#approvals.hasPending(key)) {
|
|
1487
|
+
return Promise.resolve(false);
|
|
1488
|
+
}
|
|
1489
|
+
return this.#startTyping(toUserId, contextToken);
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
async #deliverArtifacts(toUserId, replyTo, artifacts, contextToken, runId, baseReceipt) {
|
|
1493
|
+
const sendArtifact = (method, file) => this.#api[method]({
|
|
1494
|
+
baseUrl: this.#baseUrl,
|
|
1495
|
+
token: this.#token,
|
|
1496
|
+
toUserId,
|
|
1497
|
+
file,
|
|
1498
|
+
contextToken,
|
|
1499
|
+
runId,
|
|
1500
|
+
signal: this.#signal,
|
|
1501
|
+
});
|
|
1502
|
+
const delivery = await deliverOutboundArtifacts({
|
|
1503
|
+
artifacts,
|
|
1504
|
+
baseReceipt,
|
|
1505
|
+
deliveryId: replyTo,
|
|
1506
|
+
aggregatePresentation: baseReceipt ? 'weixin-text-and-files' : 'weixin-files',
|
|
1507
|
+
channelKey: 'weixin',
|
|
1508
|
+
signal: this.#signal,
|
|
1509
|
+
sendImage: typeof this.#api.sendImage === 'function'
|
|
1510
|
+
? (file) => sendArtifact('sendImage', file)
|
|
1511
|
+
: undefined,
|
|
1512
|
+
sendFile: typeof this.#api.sendFile === 'function'
|
|
1513
|
+
? (file) => sendArtifact('sendFile', file)
|
|
1514
|
+
: undefined,
|
|
1515
|
+
onFailure: (artifact, error) => setLastMessageFailure(this.#status, error, {
|
|
1516
|
+
userMessage: artifactFailureText(artifact?.fileName, error),
|
|
1517
|
+
reason: error?.code,
|
|
1518
|
+
}),
|
|
1519
|
+
sendFailureNotice: (_artifact, _error, failure) => this.#send(
|
|
1520
|
+
toUserId,
|
|
1521
|
+
messageFailureText(failure),
|
|
1522
|
+
contextToken,
|
|
1523
|
+
runId,
|
|
1524
|
+
),
|
|
1525
|
+
logger: this.#logger,
|
|
1526
|
+
});
|
|
1527
|
+
this.#status.artifactsSent = (this.#status.artifactsSent ?? 0)
|
|
1528
|
+
+ delivery.artifactsSent;
|
|
1529
|
+
this.#status.artifactSendErrors = (this.#status.artifactSendErrors ?? 0)
|
|
1530
|
+
+ delivery.artifactSendErrors;
|
|
1531
|
+
return {
|
|
1532
|
+
receipt: delivery.receipt,
|
|
1533
|
+
userVisible: delivery.userVisible,
|
|
1534
|
+
artifactSendErrors: delivery.artifactSendErrors,
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
}
|