@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,1072 @@
|
|
|
1
|
+
import { createDeferredDeliveryCoordinator, deferredOutcomeText } from '../shared/deferred-delivery-coordinator.mjs';
|
|
2
|
+
import {
|
|
3
|
+
harnessAnswerForQuestion,
|
|
4
|
+
harnessQuestionText,
|
|
5
|
+
validHarnessQuestion,
|
|
6
|
+
} from '../shared/harness-question.mjs';
|
|
7
|
+
import { HarnessApprovalQueue } from '../shared/harness-approval.mjs';
|
|
8
|
+
import {
|
|
9
|
+
BatchInputManager,
|
|
10
|
+
batchInputBusyMessage,
|
|
11
|
+
isBatchInputCommand,
|
|
12
|
+
} from '../shared/batch-input.mjs';
|
|
13
|
+
import { runCompactCommand } from '../shared/compact-command.mjs';
|
|
14
|
+
import { isHistoryCommand, runHistoryCommand } from '../shared/history-command.mjs';
|
|
15
|
+
import {
|
|
16
|
+
isControlCommand,
|
|
17
|
+
runControlCommand,
|
|
18
|
+
} from '../shared/control-command.mjs';
|
|
19
|
+
import {
|
|
20
|
+
isModelCommand,
|
|
21
|
+
runModelCommand,
|
|
22
|
+
} from '../shared/model-command.mjs';
|
|
23
|
+
import {
|
|
24
|
+
isPresetCommand,
|
|
25
|
+
runPresetCommand,
|
|
26
|
+
} from '../shared/preset-command.mjs';
|
|
27
|
+
import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
|
|
28
|
+
import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
|
|
29
|
+
import {
|
|
30
|
+
captureContextEnhancement,
|
|
31
|
+
captureContextEnhancementSource,
|
|
32
|
+
enhanceContextContent,
|
|
33
|
+
} from '../shared/context-enhancement.mjs';
|
|
34
|
+
import {
|
|
35
|
+
DEFAULT_IMAGE_PROMPT,
|
|
36
|
+
hasInboundImages,
|
|
37
|
+
imagePromptDiagnostic,
|
|
38
|
+
imagePromptUserMessage,
|
|
39
|
+
} from '../shared/image-prompt.mjs';
|
|
40
|
+
import {
|
|
41
|
+
hasInboundFiles,
|
|
42
|
+
inboundFileUserMessage,
|
|
43
|
+
} from '../shared/inbound-file.mjs';
|
|
44
|
+
import { rememberConnectionTestTarget } from '../shared/connection-test.mjs';
|
|
45
|
+
import { deliverOutboundArtifacts } from '../shared/semantic/artifact-delivery.mjs';
|
|
46
|
+
import {
|
|
47
|
+
createDeliveryReceipt,
|
|
48
|
+
providerMessageIdsFor,
|
|
49
|
+
} from '../shared/semantic/delivery.mjs';
|
|
50
|
+
import {
|
|
51
|
+
hasReplyReference,
|
|
52
|
+
promptContentForInboundMessage,
|
|
53
|
+
} from '../shared/semantic/reply-reference.mjs';
|
|
54
|
+
import {
|
|
55
|
+
messageFailureDiagnostic,
|
|
56
|
+
channelDeliveryFailure,
|
|
57
|
+
clearLastMessageFailure,
|
|
58
|
+
messageFailureText,
|
|
59
|
+
setLastMessageFailure,
|
|
60
|
+
} from '../shared/message-failure.mjs';
|
|
61
|
+
import {
|
|
62
|
+
COMMAND_PERMISSION_DENIED_MESSAGE,
|
|
63
|
+
evaluateInboundAccess,
|
|
64
|
+
} from '../shared/inbound-access.mjs';
|
|
65
|
+
import { t } from '../shared/i18n.mjs';
|
|
66
|
+
import { WECOM_APP_TEXT_MAX_BYTES, splitUtf8ByBytes } from './wecom-app-api.mjs';
|
|
67
|
+
|
|
68
|
+
const INTERACTION_RESOLVED_TEXT = () => t('这个问题已在其他客户端处理,无需再次回答。');
|
|
69
|
+
const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
70
|
+
const UNSUPPORTED_INBOUND_TEXT = () => t('企业微信应用目前支持文字和图片消息。');
|
|
71
|
+
|
|
72
|
+
const HELP_TEXT = () => [
|
|
73
|
+
t('企业微信应用已连接 DeepSeek Harness,可在微信中直接使用。'),
|
|
74
|
+
'',
|
|
75
|
+
t('直接发送文字或图片即可继续当前会话。'),
|
|
76
|
+
t('/new 开启一个全新会话'),
|
|
77
|
+
t('/compact 压缩当前会话的较早上下文'),
|
|
78
|
+
t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'),
|
|
79
|
+
t('/workspace 工作区序号或绝对路径 切换工作区'),
|
|
80
|
+
t('/workspacelist 列出工作区绝对路径'),
|
|
81
|
+
t('/ws、/wsl、/workspaces 工作区命令别名'),
|
|
82
|
+
t('/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题'),
|
|
83
|
+
t('/sessionlist --limit N 仅列出当前工作区前 N 个会话'),
|
|
84
|
+
t('/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话'),
|
|
85
|
+
t('/models 按序号列出所有可用模型'),
|
|
86
|
+
t('/reasoninglist 或 /reasonings 按序号列出当前模型可用推理等级'),
|
|
87
|
+
t('/reasoning [序号、等级ID或 --default] 查看或切换当前推理等级'),
|
|
88
|
+
t('/model [序号或完整模型ID] [推理等级ID] 查看或切换当前会话模型'),
|
|
89
|
+
t('示例:先发 /models,再发 /model 2 [推理等级ID]'),
|
|
90
|
+
t('/presetlist 或 /presets 按序号列出可用 Agent Preset'),
|
|
91
|
+
t('/preset [序号或完整ID] 查看或设置当前机器人 Agent Preset'),
|
|
92
|
+
t('纯数字 ID:/preset id:<ID>'),
|
|
93
|
+
t('/preset --default 跟随 Host 默认'),
|
|
94
|
+
t('/stop 停止当前任务'),
|
|
95
|
+
t('/steer 补充指令 纠偏当前任务'),
|
|
96
|
+
t('/batch 开始批量输入(仅私聊,最多 10 条文字)'),
|
|
97
|
+
t('/send 提交当前批次'),
|
|
98
|
+
t('/cancel 取消当前批次'),
|
|
99
|
+
t('/status 检查连接状态'),
|
|
100
|
+
t('/version 查看插件版本'),
|
|
101
|
+
t('/help 显示本帮助'),
|
|
102
|
+
].join('\n');
|
|
103
|
+
|
|
104
|
+
const WELCOME_TEXT = () => t('企业微信应用已连接 DeepSeek Harness。直接发送文字或图片即可开始,发送 /help 查看可用命令。');
|
|
105
|
+
|
|
106
|
+
function conversationKey(userId) {
|
|
107
|
+
return `p2p:${userId}`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function nonEmptyString(value) {
|
|
111
|
+
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function messageText(message) {
|
|
115
|
+
if (message?.msgtype !== 'text') return '';
|
|
116
|
+
return typeof message.text?.content === 'string' ? message.text.content : '';
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function hasImageItems(message) {
|
|
120
|
+
return message?.msgtype === 'image' && Boolean(message.image?.url || message.mediaId);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function supportedInboundType(message) {
|
|
124
|
+
return message?.msgtype === 'text' || message?.msgtype === 'image';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function answerTextForDelivery(answer, artifacts) {
|
|
128
|
+
return typeof answer === 'string' && answer.trim()
|
|
129
|
+
? answer
|
|
130
|
+
: (Array.isArray(artifacts) && artifacts.length > 0 ? t('结果文件已生成。') : answer);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Inbound image source: WeCom either hands out a directly fetchable PicUrl or
|
|
134
|
+
// a media_id downloadable through the authenticated media API. Loads are cached
|
|
135
|
+
// so an eager prefetch survives the queue wait without a second download.
|
|
136
|
+
function imageSource(api, image) {
|
|
137
|
+
const url = nonEmptyString(image?.url);
|
|
138
|
+
const mediaId = nonEmptyString(image?.mediaId) ?? nonEmptyString(image?.media_id);
|
|
139
|
+
if (!url && !mediaId) return null;
|
|
140
|
+
let cached = null;
|
|
141
|
+
return {
|
|
142
|
+
async load({ signal, maxBytes } = {}) {
|
|
143
|
+
signal?.throwIfAborted();
|
|
144
|
+
if (cached) return cached;
|
|
145
|
+
let data;
|
|
146
|
+
let name;
|
|
147
|
+
if (url) {
|
|
148
|
+
const response = await fetch(url, { signal });
|
|
149
|
+
if (!response.ok) throw new Error(`企业微信图片下载失败(HTTP ${response.status})`);
|
|
150
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
151
|
+
if (Number.isFinite(maxBytes) && buffer.length > maxBytes) {
|
|
152
|
+
const error = new Error(`企业微信图片超过 ${maxBytes} 字节`);
|
|
153
|
+
error.code = 'image-too-large';
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
data = buffer;
|
|
157
|
+
const declared = nonEmptyString(response.headers?.get?.('content-disposition'));
|
|
158
|
+
name = declared?.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/iu)?.[1] ?? 'image';
|
|
159
|
+
} else {
|
|
160
|
+
const result = await api.downloadMedia({ mediaId, signal });
|
|
161
|
+
data = result.data;
|
|
162
|
+
name = result.filename ?? 'image';
|
|
163
|
+
}
|
|
164
|
+
if (Number.isFinite(maxBytes) && data.length > maxBytes) {
|
|
165
|
+
const error = new Error(`企业微信图片超过 ${maxBytes} 字节`);
|
|
166
|
+
error.code = 'image-too-large';
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
cached = { data, name };
|
|
170
|
+
return cached;
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function wecomAppInboundMessage(message, api) {
|
|
176
|
+
return {
|
|
177
|
+
content: messageText(message),
|
|
178
|
+
images: hasImageItems(message)
|
|
179
|
+
? [imageSource(api, { url: message.image?.url, mediaId: message.mediaId })].filter(Boolean)
|
|
180
|
+
: [],
|
|
181
|
+
files: [],
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function canClaimInteractionReply(message, pending) {
|
|
186
|
+
return pending.questions[pending.index]
|
|
187
|
+
&& nonEmptyString(message?.from?.userid) === pending.actor
|
|
188
|
+
&& !hasImageItems(message)
|
|
189
|
+
&& nonEmptyString(messageText(message));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export class WecomAppBridge {
|
|
193
|
+
#api;
|
|
194
|
+
#harness;
|
|
195
|
+
#state;
|
|
196
|
+
#status;
|
|
197
|
+
#contextEnhancement;
|
|
198
|
+
#accessPolicy;
|
|
199
|
+
#logger;
|
|
200
|
+
#replyTimeoutMs;
|
|
201
|
+
#signal;
|
|
202
|
+
#streamRegistry;
|
|
203
|
+
#maxChunkBytes;
|
|
204
|
+
#queues = new Map();
|
|
205
|
+
#acceptedMessageIds = new Map();
|
|
206
|
+
#commandTasks = new Set();
|
|
207
|
+
#approvalTasks = new Set();
|
|
208
|
+
#pendingInteractions = new Map();
|
|
209
|
+
#interactionKeys = new Map();
|
|
210
|
+
#approvals;
|
|
211
|
+
#batchInputs;
|
|
212
|
+
#deferred;
|
|
213
|
+
#closed = false;
|
|
214
|
+
|
|
215
|
+
constructor({
|
|
216
|
+
api,
|
|
217
|
+
harness,
|
|
218
|
+
state,
|
|
219
|
+
status,
|
|
220
|
+
contextEnhancement,
|
|
221
|
+
accessPolicy,
|
|
222
|
+
logger = console,
|
|
223
|
+
replyTimeoutMs = 600_000,
|
|
224
|
+
signal,
|
|
225
|
+
streamRegistry,
|
|
226
|
+
maxChunkBytes = WECOM_APP_TEXT_MAX_BYTES,
|
|
227
|
+
}) {
|
|
228
|
+
if (!api || typeof api.sendText !== 'function') throw new TypeError('WecomAppBridge requires a WecomAppApi');
|
|
229
|
+
if (!harness || !state) throw new TypeError('WecomAppBridge requires Harness and state');
|
|
230
|
+
this.#api = api;
|
|
231
|
+
this.#harness = harness;
|
|
232
|
+
this.#state = state;
|
|
233
|
+
this.#status = status;
|
|
234
|
+
this.#contextEnhancement = contextEnhancement;
|
|
235
|
+
this.#accessPolicy = accessPolicy;
|
|
236
|
+
this.#logger = logger;
|
|
237
|
+
this.#replyTimeoutMs = replyTimeoutMs;
|
|
238
|
+
this.#signal = signal;
|
|
239
|
+
this.#streamRegistry = streamRegistry;
|
|
240
|
+
this.#maxChunkBytes = maxChunkBytes;
|
|
241
|
+
this.#deferred = createDeferredDeliveryCoordinator({
|
|
242
|
+
harness, state, signal, logger,
|
|
243
|
+
deliver: (entry, outcome) => this.#deliverDeferredOutcome(entry, outcome),
|
|
244
|
+
});
|
|
245
|
+
this.#approvals = new HarnessApprovalQueue({ label: 'wecom-app', logger });
|
|
246
|
+
this.#batchInputs = new BatchInputManager();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
get status() {
|
|
250
|
+
return structuredClone(this.#status);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async acceptEvent(message) {
|
|
254
|
+
if (this.#closed || this.#signal?.aborted) return;
|
|
255
|
+
const event = nonEmptyString(message?.event) ?? nonEmptyString(message?.eventtype);
|
|
256
|
+
if (event !== 'subscribe' && event !== 'enter_chat') return;
|
|
257
|
+
const sender = nonEmptyString(message?.from?.userid) ?? nonEmptyString(message?.FromUserName);
|
|
258
|
+
if (!sender) return;
|
|
259
|
+
try {
|
|
260
|
+
await this.#send(sender, WELCOME_TEXT());
|
|
261
|
+
} catch (error) {
|
|
262
|
+
this.#logger.warn?.('[dsh-im:wecom-app] failed to send the welcome message:', error);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
accept(message, { sink } = {}) {
|
|
267
|
+
if (this.#closed || this.#signal?.aborted) return Promise.resolve();
|
|
268
|
+
const messageId = nonEmptyString(message?.msgid);
|
|
269
|
+
const sender = nonEmptyString(message?.from?.userid);
|
|
270
|
+
if (!messageId || !sender || !supportedInboundType(message)
|
|
271
|
+
|| this.#state.hasSeen(messageId) || this.#acceptedMessageIds.has(messageId)) {
|
|
272
|
+
return Promise.resolve();
|
|
273
|
+
}
|
|
274
|
+
const commandText = nonEmptyString(messageText(message)) ?? '';
|
|
275
|
+
const hasImages = hasImageItems(message);
|
|
276
|
+
const access = evaluateInboundAccess(this.#accessPolicy, {
|
|
277
|
+
conversationType: 'direct',
|
|
278
|
+
senderIds: sender,
|
|
279
|
+
text: commandText,
|
|
280
|
+
hasImages,
|
|
281
|
+
hasFiles: false,
|
|
282
|
+
});
|
|
283
|
+
if (!access.allowed) {
|
|
284
|
+
this.#acceptedMessageIds.set(messageId, null);
|
|
285
|
+
return this.#finishAccessDecision(messageId, sender, access);
|
|
286
|
+
}
|
|
287
|
+
this.#acceptedMessageIds.set(messageId, captureContextEnhancement(
|
|
288
|
+
this.#contextEnhancement,
|
|
289
|
+
'direct',
|
|
290
|
+
));
|
|
291
|
+
rememberConnectionTestTarget(this.#state, { toUserId: sender });
|
|
292
|
+
const key = conversationKey(sender);
|
|
293
|
+
const pending = this.#pendingInteractions.get(key);
|
|
294
|
+
const batchCommand = isBatchInputCommand(commandText);
|
|
295
|
+
const batchStatus = this.#batchInputs.status(key);
|
|
296
|
+
if (batchCommand || batchStatus.phase === 'collecting') {
|
|
297
|
+
const exactBatchStart = /^\/batch$/iu.test(commandText);
|
|
298
|
+
const result = exactBatchStart
|
|
299
|
+
&& batchStatus.phase === 'idle'
|
|
300
|
+
&& (this.#queues.has(key) || pending || this.#approvals.hasPending(key))
|
|
301
|
+
? { handled: true, kind: 'busy', message: batchInputBusyMessage() }
|
|
302
|
+
: this.#batchInputs.handle(key, commandText, { plainText: !hasImages });
|
|
303
|
+
if (result.handled) {
|
|
304
|
+
if (result.kind === 'submit') {
|
|
305
|
+
return this.#enqueueMessage({
|
|
306
|
+
...message,
|
|
307
|
+
msgtype: 'text',
|
|
308
|
+
text: { content: result.prompt },
|
|
309
|
+
}, messageId, key, { batchSubmission: result, sink: null });
|
|
310
|
+
}
|
|
311
|
+
return this.#finishBatchResult(messageId, key, sender, result);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const commandRunner = isHistoryCommand(commandText) ? runHistoryCommand
|
|
315
|
+
: isControlCommand(commandText)
|
|
316
|
+
? runControlCommand
|
|
317
|
+
: (isModelCommand(commandText)
|
|
318
|
+
? runModelCommand
|
|
319
|
+
: (isPresetCommand(commandText) ? runPresetCommand : null));
|
|
320
|
+
if (commandRunner) {
|
|
321
|
+
let task;
|
|
322
|
+
task = this.#processFastCommand(message, messageId, key, sender, commandText, commandRunner)
|
|
323
|
+
.catch((error) => {
|
|
324
|
+
if (error?.code === 'turn-stopped' || this.#signal?.aborted) return;
|
|
325
|
+
this.#status.lastError = error?.message ?? String(error);
|
|
326
|
+
const failure = setLastMessageFailure(this.#status, error);
|
|
327
|
+
this.#logger.error?.(
|
|
328
|
+
`[dsh-im:wecom-app] failed to process a command [${failure.referenceId}]:`,
|
|
329
|
+
messageFailureDiagnostic(error, failure),
|
|
330
|
+
);
|
|
331
|
+
return this.#send(sender, messageFailureText(failure)).catch(() => undefined);
|
|
332
|
+
})
|
|
333
|
+
.finally(() => {
|
|
334
|
+
this.#acceptedMessageIds.delete(messageId);
|
|
335
|
+
this.#commandTasks.delete(task);
|
|
336
|
+
});
|
|
337
|
+
this.#commandTasks.add(task);
|
|
338
|
+
return task;
|
|
339
|
+
}
|
|
340
|
+
const approval = this.#approvals.claimReply({
|
|
341
|
+
key,
|
|
342
|
+
actor: sender,
|
|
343
|
+
messageId,
|
|
344
|
+
text: hasImages ? '' : commandText,
|
|
345
|
+
addressed: true,
|
|
346
|
+
hasPendingQuestion: Boolean(pending),
|
|
347
|
+
questionCompletion: pending?.submitting || pending?.claimedReplyMessageId
|
|
348
|
+
? pending.queue
|
|
349
|
+
: null,
|
|
350
|
+
isQuestionPending: () => this.#pendingInteractions.has(key),
|
|
351
|
+
send: (text) => this.#send(sender, text),
|
|
352
|
+
});
|
|
353
|
+
if (approval) {
|
|
354
|
+
let task;
|
|
355
|
+
task = approval.process(async () => {
|
|
356
|
+
if (this.#state.hasSeen(messageId)) return false;
|
|
357
|
+
await this.#state.markSeen(messageId);
|
|
358
|
+
this.#status.messagesReceived += 1;
|
|
359
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
360
|
+
return true;
|
|
361
|
+
}).finally(() => {
|
|
362
|
+
this.#acceptedMessageIds.delete(messageId);
|
|
363
|
+
this.#approvalTasks.delete(task);
|
|
364
|
+
});
|
|
365
|
+
this.#approvalTasks.add(task);
|
|
366
|
+
return task;
|
|
367
|
+
}
|
|
368
|
+
if (pending?.submitting || pending?.claimedReplyMessageId) {
|
|
369
|
+
return this.#enqueueMessage(message, messageId, key, { sink: null });
|
|
370
|
+
}
|
|
371
|
+
if (pending) {
|
|
372
|
+
if (canClaimInteractionReply(message, pending)) {
|
|
373
|
+
pending.claimedReplyMessageId = messageId;
|
|
374
|
+
}
|
|
375
|
+
const previous = pending.queue ?? Promise.resolve();
|
|
376
|
+
const current = previous
|
|
377
|
+
.catch(() => undefined)
|
|
378
|
+
.then(() => this.#processInteractionReply(message, messageId, key, pending))
|
|
379
|
+
.catch((error) => this.#handleInteractionFailure(message, messageId, error))
|
|
380
|
+
.finally(() => {
|
|
381
|
+
this.#acceptedMessageIds.delete(messageId);
|
|
382
|
+
if (pending.claimedReplyMessageId === messageId) pending.claimedReplyMessageId = null;
|
|
383
|
+
if (pending.queue === current) pending.queue = null;
|
|
384
|
+
});
|
|
385
|
+
pending.queue = current;
|
|
386
|
+
return current;
|
|
387
|
+
}
|
|
388
|
+
return this.#enqueueMessage(message, messageId, key, { sink });
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
#enqueueMessage(message, messageId, key, {
|
|
392
|
+
releaseMessageId = true,
|
|
393
|
+
alreadyRecorded = false,
|
|
394
|
+
batchSubmission = null,
|
|
395
|
+
sink = null,
|
|
396
|
+
} = {}) {
|
|
397
|
+
const preparedMessage = wecomAppInboundMessage(message, this.#api);
|
|
398
|
+
const previous = this.#queues.get(key) ?? Promise.resolve();
|
|
399
|
+
const current = previous
|
|
400
|
+
.catch(() => undefined)
|
|
401
|
+
.then(() => this.#process(message, key, {
|
|
402
|
+
alreadyRecorded,
|
|
403
|
+
preparedMessage,
|
|
404
|
+
batchSubmission,
|
|
405
|
+
sink,
|
|
406
|
+
}))
|
|
407
|
+
.finally(() => {
|
|
408
|
+
if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
|
|
409
|
+
if (this.#queues.get(key) === current) this.#queues.delete(key);
|
|
410
|
+
});
|
|
411
|
+
this.#queues.set(key, current);
|
|
412
|
+
return current;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
#finishBatchResult(messageId, key, sender, result) {
|
|
416
|
+
let task;
|
|
417
|
+
task = Promise.resolve().then(async () => {
|
|
418
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
419
|
+
await this.#state.markSeen(messageId);
|
|
420
|
+
this.#status.messagesReceived += 1;
|
|
421
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
422
|
+
if (result.message) await this.#send(sender, result.message);
|
|
423
|
+
this.#status.lastError = null;
|
|
424
|
+
}).catch(async (error) => {
|
|
425
|
+
if (this.#signal?.aborted) return;
|
|
426
|
+
this.#status.lastError = error?.message ?? String(error);
|
|
427
|
+
const failure = setLastMessageFailure(this.#status, error);
|
|
428
|
+
this.#logger.error?.(
|
|
429
|
+
`[dsh-im:wecom-app] failed to process a batch input message [${failure.referenceId}]:`,
|
|
430
|
+
messageFailureDiagnostic(error, failure),
|
|
431
|
+
);
|
|
432
|
+
await this.#send(sender, messageFailureText(failure)).catch(() => undefined);
|
|
433
|
+
}).finally(() => {
|
|
434
|
+
this.#acceptedMessageIds.delete(messageId);
|
|
435
|
+
this.#commandTasks.delete(task);
|
|
436
|
+
});
|
|
437
|
+
this.#commandTasks.add(task);
|
|
438
|
+
return task;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
#finishAccessDecision(messageId, sender, access) {
|
|
442
|
+
let task;
|
|
443
|
+
task = Promise.resolve().then(async () => {
|
|
444
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
445
|
+
await this.#state.markSeen(messageId);
|
|
446
|
+
if (access.reason === 'command-not-allowed') {
|
|
447
|
+
this.#status.messagesReceived += 1;
|
|
448
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
449
|
+
await this.#send(sender, t(COMMAND_PERMISSION_DENIED_MESSAGE));
|
|
450
|
+
this.#status.messagesReplied += 1;
|
|
451
|
+
this.#status.lastReplyAt = new Date().toISOString();
|
|
452
|
+
} else {
|
|
453
|
+
this.#status.messagesRejected = (this.#status.messagesRejected ?? 0) + 1;
|
|
454
|
+
this.#status.lastRejectedAt = new Date().toISOString();
|
|
455
|
+
}
|
|
456
|
+
this.#status.lastError = null;
|
|
457
|
+
}).catch((error) => {
|
|
458
|
+
if (this.#signal?.aborted) return;
|
|
459
|
+
this.#status.lastError = error?.message ?? String(error);
|
|
460
|
+
this.#logger.error?.('[dsh-im:wecom-app] failed to apply inbound access policy:', error);
|
|
461
|
+
}).finally(() => {
|
|
462
|
+
this.#acceptedMessageIds.delete(messageId);
|
|
463
|
+
this.#commandTasks.delete(task);
|
|
464
|
+
});
|
|
465
|
+
this.#commandTasks.add(task);
|
|
466
|
+
return task;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async #deliverDeferredOutcome(entry, outcome) {
|
|
470
|
+
await this.#send(entry.target.toUserId, deferredOutcomeText(outcome));
|
|
471
|
+
return true;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
async waitForIdle() {
|
|
475
|
+
await Promise.allSettled([
|
|
476
|
+
...this.#queues.values(),
|
|
477
|
+
...[...this.#pendingInteractions.values()].flatMap((pending) => (
|
|
478
|
+
pending.queue ? [pending.queue] : []
|
|
479
|
+
)),
|
|
480
|
+
...this.#approvalTasks,
|
|
481
|
+
...this.#commandTasks,
|
|
482
|
+
]);
|
|
483
|
+
await this.#deferred.whenIdle();
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
async close() {
|
|
487
|
+
this.#closed = true;
|
|
488
|
+
this.#deferred.close();
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
async #processFastCommand(message, messageId, key, sender, text, runner) {
|
|
492
|
+
this.#signal?.throwIfAborted();
|
|
493
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
494
|
+
await this.#state.markSeen(messageId);
|
|
495
|
+
this.#status.messagesReceived += 1;
|
|
496
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
497
|
+
const result = await runner(text, this.#harness, this.#state, key, {
|
|
498
|
+
signal: this.#signal,
|
|
499
|
+
isDirect: true,
|
|
500
|
+
hasImages: hasImageItems(message),
|
|
501
|
+
hasFiles: false,
|
|
502
|
+
pendingInteraction: this.#pendingInteractions.has(key)
|
|
503
|
+
|| this.#approvals.hasPending(key),
|
|
504
|
+
control: { owner: this, key },
|
|
505
|
+
deferredDelivery: this.#deferred,
|
|
506
|
+
enhancement: captureContextEnhancementSource(
|
|
507
|
+
this.#contextEnhancement,
|
|
508
|
+
'direct',
|
|
509
|
+
() => ({ channel: 'wecom-app', senderId: sender, chatId: sender }),
|
|
510
|
+
),
|
|
511
|
+
});
|
|
512
|
+
if (result?.stopped) {
|
|
513
|
+
await Promise.allSettled([
|
|
514
|
+
this.#cancelPendingInteraction(key),
|
|
515
|
+
this.#approvals.closeRoute(key),
|
|
516
|
+
]);
|
|
517
|
+
}
|
|
518
|
+
for (const reply of result?.messages ?? [result?.message]) {
|
|
519
|
+
if (!reply) continue;
|
|
520
|
+
await this.#send(sender, reply);
|
|
521
|
+
}
|
|
522
|
+
this.#status.lastError = null;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
async #process(message, key, {
|
|
526
|
+
alreadyRecorded = false,
|
|
527
|
+
preparedMessage,
|
|
528
|
+
batchSubmission = null,
|
|
529
|
+
sink = null,
|
|
530
|
+
} = {}) {
|
|
531
|
+
this.#signal?.throwIfAborted();
|
|
532
|
+
const messageId = nonEmptyString(message?.msgid);
|
|
533
|
+
const sender = nonEmptyString(message?.from?.userid);
|
|
534
|
+
if (!messageId || !sender) return;
|
|
535
|
+
if (!alreadyRecorded) {
|
|
536
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
537
|
+
this.#status.messagesReceived += 1;
|
|
538
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
539
|
+
}
|
|
540
|
+
let batchSettled = batchSubmission === null;
|
|
541
|
+
let promptRecorded = false;
|
|
542
|
+
let streamActive = Boolean(sink && !sink.finished());
|
|
543
|
+
let streamedText = '';
|
|
544
|
+
try {
|
|
545
|
+
const promptMessage = preparedMessage ?? wecomAppInboundMessage(message, this.#api);
|
|
546
|
+
const text = promptMessage.content;
|
|
547
|
+
const hasImages = hasInboundImages(promptMessage);
|
|
548
|
+
const hasFiles = hasInboundFiles(promptMessage);
|
|
549
|
+
const hasReply = hasReplyReference(promptMessage);
|
|
550
|
+
if (!text && !hasImages && !hasFiles && !hasReply) {
|
|
551
|
+
await this.#send(sender, UNSUPPORTED_INBOUND_TEXT());
|
|
552
|
+
await this.#state.markSeen(messageId);
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
const command = text.trim().toLowerCase();
|
|
556
|
+
if (!hasImages && !hasFiles && command === '/help') {
|
|
557
|
+
await this.#send(sender, HELP_TEXT());
|
|
558
|
+
await this.#state.markSeen(messageId);
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
if (!hasImages && !hasFiles && command === '/status') {
|
|
562
|
+
await this.#harness.ensureRunning({ signal: this.#signal });
|
|
563
|
+
await this.#send(sender, t('企业微信应用与 DeepSeek Harness 连接正常。'));
|
|
564
|
+
await this.#state.markSeen(messageId);
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
if (!hasImages && !hasFiles && command === '/new') {
|
|
568
|
+
await this.#state.clearSession(key);
|
|
569
|
+
await this.#send(sender, t('已开启新会话。请发送你的问题。'));
|
|
570
|
+
await this.#state.markSeen(messageId);
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
const workspaceCommand = hasImages || hasFiles
|
|
574
|
+
? null
|
|
575
|
+
: await runWorkspaceCommand(text, this.#harness, key);
|
|
576
|
+
if (workspaceCommand) {
|
|
577
|
+
for (const reply of workspaceCommand.messages ?? [workspaceCommand.message]) {
|
|
578
|
+
await this.#send(sender, reply);
|
|
579
|
+
}
|
|
580
|
+
await this.#state.markSeen(messageId);
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
const compactCommand = hasImages || hasFiles
|
|
584
|
+
? null
|
|
585
|
+
: await runCompactCommand(text, this.#harness, this.#state, key, { signal: this.#signal });
|
|
586
|
+
if (compactCommand) {
|
|
587
|
+
await this.#send(sender, compactCommand.message);
|
|
588
|
+
await this.#state.markSeen(messageId);
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
let answer;
|
|
593
|
+
let artifacts = [];
|
|
594
|
+
try {
|
|
595
|
+
let content = hasImages || hasReply
|
|
596
|
+
? await promptContentForInboundMessage(promptMessage, { signal: this.#signal, deferImages: true })
|
|
597
|
+
: undefined;
|
|
598
|
+
const snapshot = this.#acceptedMessageIds.get(messageId);
|
|
599
|
+
let contextEnhanced = false;
|
|
600
|
+
if (snapshot) {
|
|
601
|
+
const originalContent = content ?? text;
|
|
602
|
+
content = enhanceContextContent(originalContent, snapshot, () => ({
|
|
603
|
+
channel: 'wecom-app',
|
|
604
|
+
senderId: sender,
|
|
605
|
+
chatId: sender,
|
|
606
|
+
}));
|
|
607
|
+
contextEnhanced = content !== originalContent;
|
|
608
|
+
}
|
|
609
|
+
await this.#state.markSeen(messageId);
|
|
610
|
+
promptRecorded = true;
|
|
611
|
+
({ answer, artifacts = [] } = await askInWorkspaceSession({
|
|
612
|
+
deferredDelivery: () => ({ coordinator: this.#deferred, target: { toUserId: sender } }),
|
|
613
|
+
harness: this.#harness,
|
|
614
|
+
state: this.#state,
|
|
615
|
+
key,
|
|
616
|
+
text,
|
|
617
|
+
content,
|
|
618
|
+
titleText: batchSubmission?.title,
|
|
619
|
+
sourceGuidance: snapshot?.config?.guidance,
|
|
620
|
+
contextEnhanced,
|
|
621
|
+
createOptions: { signal: this.#signal },
|
|
622
|
+
existsOptions: { signal: this.#signal },
|
|
623
|
+
askOptions: {
|
|
624
|
+
timeoutMs: this.#replyTimeoutMs,
|
|
625
|
+
signal: this.#signal,
|
|
626
|
+
control: { owner: this, key },
|
|
627
|
+
onUpdate: streamActive
|
|
628
|
+
? async (update) => {
|
|
629
|
+
if (update?.type !== 'text') return;
|
|
630
|
+
streamedText = update.text;
|
|
631
|
+
this.#streamRegistry.appendStream(sink.streamId, streamedText, { replace: true });
|
|
632
|
+
}
|
|
633
|
+
: undefined,
|
|
634
|
+
onInteraction: (interaction) => this.#handleInteraction(interaction, {
|
|
635
|
+
key,
|
|
636
|
+
actor: sender,
|
|
637
|
+
}),
|
|
638
|
+
onInteractionResolved: async (resolution) => {
|
|
639
|
+
await this.#handleInteractionResolved(resolution);
|
|
640
|
+
},
|
|
641
|
+
files: promptMessage.files,
|
|
642
|
+
images: promptMessage.images,
|
|
643
|
+
},
|
|
644
|
+
}));
|
|
645
|
+
if (batchSubmission) {
|
|
646
|
+
this.#batchInputs.complete(key, batchSubmission.token);
|
|
647
|
+
batchSettled = true;
|
|
648
|
+
}
|
|
649
|
+
} catch (error) {
|
|
650
|
+
if (streamActive && !sink.finished()) {
|
|
651
|
+
const diagnostic = imagePromptDiagnostic(error);
|
|
652
|
+
if (diagnostic?.userMessage) {
|
|
653
|
+
this.#streamRegistry.appendStream(sink.streamId, `\n${diagnostic.userMessage}`);
|
|
654
|
+
}
|
|
655
|
+
this.#streamRegistry.finishStream(sink.streamId);
|
|
656
|
+
}
|
|
657
|
+
throw error;
|
|
658
|
+
}
|
|
659
|
+
const displayAnswer = answerTextForDelivery(answer, artifacts);
|
|
660
|
+
if (streamActive && !sink.finished()) {
|
|
661
|
+
if (displayAnswer && displayAnswer !== streamedText) {
|
|
662
|
+
this.#streamRegistry.appendStream(sink.streamId, displayAnswer, { replace: true });
|
|
663
|
+
}
|
|
664
|
+
this.#streamRegistry.finishStream(sink.streamId);
|
|
665
|
+
}
|
|
666
|
+
const answerText = displayAnswer ?? t('结果文件已生成。');
|
|
667
|
+
let textDeliveryError = null;
|
|
668
|
+
let textReceipt = null;
|
|
669
|
+
try {
|
|
670
|
+
if (streamActive && sink.refreshes() > 0) {
|
|
671
|
+
textReceipt = createDeliveryReceipt({
|
|
672
|
+
deliveryId: messageId,
|
|
673
|
+
presentation: 'wecom-app-stream',
|
|
674
|
+
providerMessageIds: [sink.streamId],
|
|
675
|
+
});
|
|
676
|
+
} else {
|
|
677
|
+
// The client never consumed the stream (or streaming is disabled):
|
|
678
|
+
// fall back to explicit text messages so the answer still arrives.
|
|
679
|
+
textReceipt = createDeliveryReceipt({
|
|
680
|
+
deliveryId: messageId,
|
|
681
|
+
presentation: 'wecom-app-text',
|
|
682
|
+
providerMessageIds: await this.#send(sender, answerText),
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
} catch (error) {
|
|
686
|
+
textDeliveryError = channelDeliveryFailure(error);
|
|
687
|
+
}
|
|
688
|
+
const delivery = await this.#deliverArtifacts(sender, messageId, artifacts, textReceipt);
|
|
689
|
+
if (textDeliveryError && !delivery.userVisible) throw textDeliveryError;
|
|
690
|
+
if (textDeliveryError && delivery.artifactSendErrors === 0) {
|
|
691
|
+
setLastMessageFailure(this.#status, textDeliveryError);
|
|
692
|
+
}
|
|
693
|
+
if (!promptRecorded) await this.#state.markSeen(messageId);
|
|
694
|
+
this.#status.messagesReplied += 1;
|
|
695
|
+
this.#status.lastReplyAt = new Date().toISOString();
|
|
696
|
+
this.#status.lastError = null;
|
|
697
|
+
if (!textDeliveryError && delivery.artifactSendErrors === 0) {
|
|
698
|
+
clearLastMessageFailure(this.#status);
|
|
699
|
+
}
|
|
700
|
+
return delivery.receipt;
|
|
701
|
+
} catch (error) {
|
|
702
|
+
let batchFailureMessage = null;
|
|
703
|
+
if (!batchSettled && batchSubmission) {
|
|
704
|
+
if (error?.code === 'turn-stopped') {
|
|
705
|
+
this.#batchInputs.complete(key, batchSubmission.token);
|
|
706
|
+
} else {
|
|
707
|
+
batchFailureMessage = this.#batchInputs.fail(key, batchSubmission.token).message ?? null;
|
|
708
|
+
}
|
|
709
|
+
batchSettled = true;
|
|
710
|
+
}
|
|
711
|
+
if (error?.code === 'turn-stopped') {
|
|
712
|
+
if (!promptRecorded) await this.#state.markSeen(messageId);
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
if (this.#signal?.aborted) return;
|
|
716
|
+
this.#status.lastError = error?.message ?? String(error);
|
|
717
|
+
const userMessage = inboundFileUserMessage(error) ?? imagePromptUserMessage(error);
|
|
718
|
+
const imageDiagnostic = imagePromptDiagnostic(error);
|
|
719
|
+
const failure = setLastMessageFailure(this.#status, error, {
|
|
720
|
+
userMessage: userMessage ?? undefined,
|
|
721
|
+
reason: imageDiagnostic?.reason ?? undefined,
|
|
722
|
+
});
|
|
723
|
+
this.#logger.error?.(
|
|
724
|
+
`[dsh-im:wecom-app] failed to process an inbound message [${failure.referenceId}]:`,
|
|
725
|
+
messageFailureDiagnostic(error, failure),
|
|
726
|
+
);
|
|
727
|
+
try {
|
|
728
|
+
await this.#send(
|
|
729
|
+
sender,
|
|
730
|
+
batchFailureMessage
|
|
731
|
+
? `${messageFailureText(failure)}\n\n${batchFailureMessage}`
|
|
732
|
+
: messageFailureText(failure),
|
|
733
|
+
);
|
|
734
|
+
if (!promptRecorded) await this.#state.markSeen(messageId);
|
|
735
|
+
} catch (sendError) {
|
|
736
|
+
this.#logger.error?.('[dsh-im:wecom-app] failed to send the safe error reply:', sendError);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
async #send(sender, text) {
|
|
742
|
+
const target = nonEmptyString(sender);
|
|
743
|
+
const value = typeof text === 'string' ? text : '';
|
|
744
|
+
if (!target || !value) return [];
|
|
745
|
+
const providerMessageIds = [];
|
|
746
|
+
const chunks = splitUtf8ByBytes(value, this.#maxChunkBytes);
|
|
747
|
+
for (const chunk of chunks) {
|
|
748
|
+
if (!chunk) continue;
|
|
749
|
+
const result = await this.#api.sendText({ userId: target, content: chunk, signal: this.#signal });
|
|
750
|
+
providerMessageIds.push(...providerMessageIdsFor(result));
|
|
751
|
+
}
|
|
752
|
+
return providerMessageIds;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
async #processInteractionReply(message, messageId, key, expected) {
|
|
756
|
+
this.#signal?.throwIfAborted();
|
|
757
|
+
const current = this.#pendingInteractions.get(key);
|
|
758
|
+
const claimed = expected.claimedReplyMessageId === messageId;
|
|
759
|
+
if (!current || current !== expected || current.submitting) {
|
|
760
|
+
if (claimed && (!current || current !== expected)) {
|
|
761
|
+
return this.#discardResolvedInteractionReply(message, messageId);
|
|
762
|
+
}
|
|
763
|
+
return this.#enqueueMessage(message, messageId, key, { releaseMessageId: false, sink: null });
|
|
764
|
+
}
|
|
765
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
766
|
+
await this.#state.markSeen(messageId);
|
|
767
|
+
this.#status.messagesReceived += 1;
|
|
768
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
769
|
+
|
|
770
|
+
const text = nonEmptyString(messageText(message));
|
|
771
|
+
if (!text || hasImageItems(message)) {
|
|
772
|
+
await this.#send(expected.actor, t('请用文字回答当前问题。'));
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const pending = this.#pendingInteractions.get(key);
|
|
777
|
+
if (!pending || pending !== expected || pending.submitting) {
|
|
778
|
+
if (claimed && (!pending || pending !== expected)) {
|
|
779
|
+
await this.#send(expected.actor, INTERACTION_RESOLVED_TEXT());
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
return this.#enqueueMessage(message, messageId, key, {
|
|
783
|
+
releaseMessageId: false,
|
|
784
|
+
alreadyRecorded: true,
|
|
785
|
+
sink: null,
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
if (pending.needsPresentation) {
|
|
789
|
+
try {
|
|
790
|
+
await this.#presentInteraction(pending);
|
|
791
|
+
} catch {
|
|
792
|
+
this.#status.lastError = t('企业微信应用交互问题发送失败。');
|
|
793
|
+
this.#logger.error?.('[dsh-im:wecom-app] failed to retry an interaction question');
|
|
794
|
+
pending.interaction.reconnect?.();
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
const presentedPending = this.#pendingInteractions.get(key);
|
|
798
|
+
if (!presentedPending || presentedPending !== expected || presentedPending.submitting) {
|
|
799
|
+
if (claimed && (!presentedPending || presentedPending !== expected)) {
|
|
800
|
+
await this.#send(expected.actor, INTERACTION_RESOLVED_TEXT()).catch(() => undefined);
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
return this.#enqueueMessage(message, messageId, key, {
|
|
804
|
+
releaseMessageId: false,
|
|
805
|
+
alreadyRecorded: true,
|
|
806
|
+
sink: null,
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
const question = pending.questions[pending.index];
|
|
812
|
+
if (!question) return;
|
|
813
|
+
pending.answers.push(harnessAnswerForQuestion(question, text));
|
|
814
|
+
pending.index += 1;
|
|
815
|
+
if (pending.index < pending.questions.length) {
|
|
816
|
+
if (pending.claimedReplyMessageId === messageId) {
|
|
817
|
+
pending.claimedReplyMessageId = null;
|
|
818
|
+
}
|
|
819
|
+
pending.needsPresentation = true;
|
|
820
|
+
try {
|
|
821
|
+
await this.#presentInteraction(pending);
|
|
822
|
+
} catch {
|
|
823
|
+
this.#status.lastError = t('企业微信应用交互问题发送失败。');
|
|
824
|
+
this.#logger.error?.('[dsh-im:wecom-app] failed to send the next interaction question');
|
|
825
|
+
pending.interaction.reconnect?.();
|
|
826
|
+
}
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
pending.submitting = true;
|
|
831
|
+
try {
|
|
832
|
+
await pending.interaction.respond({
|
|
833
|
+
ok: true,
|
|
834
|
+
value: {
|
|
835
|
+
sessionId: pending.sessionId,
|
|
836
|
+
answer: { answers: pending.answers },
|
|
837
|
+
},
|
|
838
|
+
});
|
|
839
|
+
this.#clearPendingInteraction(key, pending.interactionId);
|
|
840
|
+
this.#status.lastError = null;
|
|
841
|
+
} catch (error) {
|
|
842
|
+
if (this.#signal?.aborted) return;
|
|
843
|
+
if (error?.code === 'interaction-not-pending') {
|
|
844
|
+
this.#clearPendingInteraction(key, pending.interactionId);
|
|
845
|
+
await this.#send(pending.actor, INTERACTION_RESOLVED_TEXT()).catch(() => undefined);
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
if (this.#pendingInteractions.get(key) !== pending) return;
|
|
849
|
+
pending.submitting = false;
|
|
850
|
+
pending.answers.pop();
|
|
851
|
+
pending.index -= 1;
|
|
852
|
+
this.#status.lastError = t('回答提交失败。');
|
|
853
|
+
this.#logger.error?.('[dsh-im:wecom-app] failed to answer a Harness interaction');
|
|
854
|
+
await this.#send(pending.actor, t('回答提交失败,请重新发送当前问题的答案。')).catch(() => undefined);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
async #handleInteraction(interaction, { key, actor }) {
|
|
859
|
+
if (interaction?.kind === 'approval') {
|
|
860
|
+
return this.#approvals.handleRequested(interaction, {
|
|
861
|
+
key,
|
|
862
|
+
actor,
|
|
863
|
+
send: (text) => this.#send(actor, text),
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
if (interaction?.kind !== 'question') return;
|
|
867
|
+
const questions = interaction?.payload?.questions;
|
|
868
|
+
const interactionId = typeof interaction?.interactionId === 'string'
|
|
869
|
+
? interaction.interactionId
|
|
870
|
+
: interaction?.rpcId;
|
|
871
|
+
if (typeof interaction?.rpcId !== 'string'
|
|
872
|
+
|| typeof interactionId !== 'string'
|
|
873
|
+
|| typeof interaction.sessionId !== 'string'
|
|
874
|
+
|| !Array.isArray(questions)
|
|
875
|
+
|| questions.length === 0
|
|
876
|
+
|| questions.some((question) => !validHarnessQuestion(question))) {
|
|
877
|
+
this.#logger.warn?.('[dsh-im:wecom-app] ignored an invalid Harness question interaction');
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
if (interaction.recovered === true) {
|
|
882
|
+
await interaction.respond({
|
|
883
|
+
ok: false,
|
|
884
|
+
error: {
|
|
885
|
+
code: 'cancelled',
|
|
886
|
+
message: 'Wecom-app safely cancelled an interaction left by an earlier client.',
|
|
887
|
+
details: {},
|
|
888
|
+
},
|
|
889
|
+
});
|
|
890
|
+
await this.#send(actor, t('检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。')).catch(() => undefined);
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
const existing = this.#pendingInteractions.get(key);
|
|
895
|
+
if (existing?.interactionId === interactionId) {
|
|
896
|
+
existing.interaction = interaction;
|
|
897
|
+
if (existing.needsPresentation) await this.#presentInteraction(existing);
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
if (this.#interactionKeys.has(interactionId)) return;
|
|
901
|
+
if (existing) {
|
|
902
|
+
await interaction.respond({
|
|
903
|
+
ok: false,
|
|
904
|
+
error: {
|
|
905
|
+
code: 'cancelled',
|
|
906
|
+
message: 'Wecom-app is already handling another user interaction.',
|
|
907
|
+
details: {},
|
|
908
|
+
},
|
|
909
|
+
});
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
const pending = {
|
|
914
|
+
kind: 'question',
|
|
915
|
+
interactionId,
|
|
916
|
+
sessionId: interaction.sessionId,
|
|
917
|
+
interaction,
|
|
918
|
+
actor,
|
|
919
|
+
questions,
|
|
920
|
+
answers: [],
|
|
921
|
+
index: 0,
|
|
922
|
+
queue: null,
|
|
923
|
+
claimedReplyMessageId: null,
|
|
924
|
+
presentationPromise: null,
|
|
925
|
+
submitting: false,
|
|
926
|
+
needsPresentation: true,
|
|
927
|
+
};
|
|
928
|
+
this.#pendingInteractions.set(key, pending);
|
|
929
|
+
this.#interactionKeys.set(interactionId, key);
|
|
930
|
+
await this.#presentInteraction(pending);
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
async #handleInteractionResolved(resolution) {
|
|
934
|
+
if (resolution?.kind === 'approval') {
|
|
935
|
+
await this.#approvals.handleResolved(resolution);
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
const interactionId = resolution?.interactionId;
|
|
939
|
+
if (resolution?.kind !== 'question' || typeof interactionId !== 'string') return;
|
|
940
|
+
const key = this.#interactionKeys.get(interactionId);
|
|
941
|
+
if (!key) return;
|
|
942
|
+
this.#clearPendingInteraction(key, interactionId);
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
#presentInteraction(pending) {
|
|
946
|
+
if (!pending.needsPresentation) return Promise.resolve();
|
|
947
|
+
if (pending.presentationPromise) return pending.presentationPromise;
|
|
948
|
+
const question = pending.questions[pending.index];
|
|
949
|
+
if (!question) return Promise.resolve();
|
|
950
|
+
const presentation = this.#send(
|
|
951
|
+
pending.actor,
|
|
952
|
+
harnessQuestionText(question, pending.index, pending.questions.length),
|
|
953
|
+
).then(() => {
|
|
954
|
+
pending.needsPresentation = false;
|
|
955
|
+
}).finally(() => {
|
|
956
|
+
if (pending.presentationPromise === presentation) pending.presentationPromise = null;
|
|
957
|
+
});
|
|
958
|
+
pending.presentationPromise = presentation;
|
|
959
|
+
return presentation;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
async #discardResolvedInteractionReply(message, messageId) {
|
|
963
|
+
if (this.#state.hasSeen(messageId)) return;
|
|
964
|
+
await this.#state.markSeen(messageId);
|
|
965
|
+
this.#status.messagesReceived += 1;
|
|
966
|
+
this.#status.lastMessageAt = new Date().toISOString();
|
|
967
|
+
await this.#send(
|
|
968
|
+
nonEmptyString(message?.from?.userid),
|
|
969
|
+
INTERACTION_RESOLVED_TEXT(),
|
|
970
|
+
).catch(() => undefined);
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
#takePendingInteraction(key, interactionId) {
|
|
974
|
+
const pending = this.#pendingInteractions.get(key);
|
|
975
|
+
if (!pending
|
|
976
|
+
|| (interactionId !== undefined && pending.interactionId !== interactionId)) return null;
|
|
977
|
+
this.#pendingInteractions.delete(key);
|
|
978
|
+
this.#interactionKeys.delete(pending.interactionId);
|
|
979
|
+
return pending;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
#clearPendingInteraction(key, interactionId) {
|
|
983
|
+
return this.#takePendingInteraction(key, interactionId) !== null;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
async #cancelPendingInteraction(key) {
|
|
987
|
+
const pending = this.#takePendingInteraction(key);
|
|
988
|
+
if (!pending || pending.kind !== 'question') return;
|
|
989
|
+
try {
|
|
990
|
+
await pending.interaction.respond({
|
|
991
|
+
ok: false,
|
|
992
|
+
error: {
|
|
993
|
+
code: 'cancelled',
|
|
994
|
+
message: 'The Enterprise WeChat app interaction ended before the user answered.',
|
|
995
|
+
details: {},
|
|
996
|
+
},
|
|
997
|
+
}, { signal: AbortSignal.timeout(5_000) });
|
|
998
|
+
} catch (error) {
|
|
999
|
+
if (error?.code !== 'interaction-not-pending') {
|
|
1000
|
+
this.#logger.warn?.('[dsh-im:wecom-app] failed to cancel a pending Harness interaction');
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
async #handleInteractionFailure(message, messageId, error) {
|
|
1006
|
+
if (this.#signal?.aborted) return;
|
|
1007
|
+
this.#status.lastError = error?.message ?? String(error);
|
|
1008
|
+
const failure = setLastMessageFailure(this.#status, error);
|
|
1009
|
+
this.#logger.error?.(
|
|
1010
|
+
`[dsh-im:wecom-app] failed to process an interaction reply [${failure.referenceId}]:`,
|
|
1011
|
+
messageFailureDiagnostic(error, failure),
|
|
1012
|
+
);
|
|
1013
|
+
if (!this.#state.hasSeen(messageId)) {
|
|
1014
|
+
await this.#state.markSeen(messageId).catch(() => undefined);
|
|
1015
|
+
}
|
|
1016
|
+
await this.#send(
|
|
1017
|
+
nonEmptyString(message?.from?.userid),
|
|
1018
|
+
messageFailureText(failure),
|
|
1019
|
+
).catch(() => undefined);
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
async #deliverArtifacts(sender, replyTo, artifacts, baseReceipt) {
|
|
1023
|
+
const sendArtifact = (kind) => (file) => this.#api.sendArtifactFile({
|
|
1024
|
+
userId: sender,
|
|
1025
|
+
kind,
|
|
1026
|
+
bytes: file.bytes,
|
|
1027
|
+
filename: file.fileName,
|
|
1028
|
+
signal: this.#signal,
|
|
1029
|
+
});
|
|
1030
|
+
const delivery = await deliverOutboundArtifacts({
|
|
1031
|
+
artifacts,
|
|
1032
|
+
baseReceipt,
|
|
1033
|
+
deliveryId: replyTo,
|
|
1034
|
+
aggregatePresentation: baseReceipt ? 'wecom-app-text-and-files' : 'wecom-app-files',
|
|
1035
|
+
channelKey: 'wecom-app',
|
|
1036
|
+
signal: this.#signal,
|
|
1037
|
+
sendImage: (file) => sendArtifact('image')(file),
|
|
1038
|
+
sendFile: (file) => sendArtifact('file')(file),
|
|
1039
|
+
onFailure: (artifact, error) => setLastMessageFailure(this.#status, error, {
|
|
1040
|
+
userMessage: artifactFailureText(artifact?.fileName, error),
|
|
1041
|
+
reason: error?.code,
|
|
1042
|
+
}),
|
|
1043
|
+
sendFailureNotice: (_artifact, _error, failure) => this.#send(sender, messageFailureText(failure)),
|
|
1044
|
+
logger: this.#logger,
|
|
1045
|
+
});
|
|
1046
|
+
this.#status.artifactsSent = (this.#status.artifactsSent ?? 0) + delivery.artifactsSent;
|
|
1047
|
+
this.#status.artifactSendErrors = (this.#status.artifactSendErrors ?? 0) + delivery.artifactSendErrors;
|
|
1048
|
+
return {
|
|
1049
|
+
receipt: delivery.receipt,
|
|
1050
|
+
userVisible: delivery.userVisible,
|
|
1051
|
+
artifactSendErrors: delivery.artifactSendErrors,
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
function artifactFailureText(fileName, error) {
|
|
1057
|
+
const name = String(fileName ?? t('结果文件')).replace(/[\r\n]+/g, ' ').trim() || t('结果文件');
|
|
1058
|
+
switch (error?.code) {
|
|
1059
|
+
case 'artifact-delivery-uncertain':
|
|
1060
|
+
return t('结果文件「{name}」发送结果未能确认,请先检查聊天内是否已收到,不要立即重试。', { name });
|
|
1061
|
+
case 'artifact-permission-required':
|
|
1062
|
+
return t('结果文件「{name}」已生成,但企业微信应用当前没有文件消息发送权限,请检查应用的文件发送能力。', { name });
|
|
1063
|
+
case 'artifact-too-large':
|
|
1064
|
+
return t('结果文件「{name}」超过企业微信可发送的文件大小,未发送。', { name });
|
|
1065
|
+
case 'artifact-rate-limited':
|
|
1066
|
+
return t('结果文件「{name}」暂时被企业微信限流,未能发送,请稍后重试。', { name });
|
|
1067
|
+
case 'artifact-provider-rejected':
|
|
1068
|
+
return t('结果文件「{name}」已生成,但企业微信拒绝了该文件消息。', { name });
|
|
1069
|
+
default:
|
|
1070
|
+
return t('结果文件「{name}」发送失败,请稍后重试。', { name });
|
|
1071
|
+
}
|
|
1072
|
+
}
|