@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,1471 @@
|
|
|
1
|
+
import { extractConnectionEvidence, createConnectionDiagnostics, atConnectionStage } from '../shared/connection-error.mjs';
|
|
2
|
+
import { randomInt } from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
import { createEditableMessageStream } from '../shared/editable-message-stream.mjs';
|
|
5
|
+
import { createTextDeliveryBlock } from '../shared/semantic/delivery.mjs';
|
|
6
|
+
import { t } from '../shared/i18n.mjs';
|
|
7
|
+
import { captureContextEnhancement } from '../shared/context-enhancement.mjs';
|
|
8
|
+
import { recoverAssistantTextByTimestamp } from '../shared/session-reply-recovery.mjs';
|
|
9
|
+
import { SHARED_COMMAND_CATALOG, commandsForChannel } from '../shared/command-catalog.mjs';
|
|
10
|
+
import { COMMANDS_MENU_BUTTON, TelegramApi, validateTelegramCommands } from './telegram-api.mjs';
|
|
11
|
+
import { createTelegramHttpTransport } from './telegram-http.mjs';
|
|
12
|
+
import { createTelegramBridgeStatus, TelegramHarnessBridge } from './telegram-bridge.mjs';
|
|
13
|
+
import {
|
|
14
|
+
splitTelegramRegularText,
|
|
15
|
+
splitTelegramRichMarkdown,
|
|
16
|
+
toTelegramRichMarkdown,
|
|
17
|
+
} from './telegram-rich-message.mjs';
|
|
18
|
+
import {
|
|
19
|
+
TELEGRAM_ACCESS_MODES,
|
|
20
|
+
} from './config-store.mjs';
|
|
21
|
+
|
|
22
|
+
function commandMenuEntries(catalog, translate) {
|
|
23
|
+
return commandsForChannel('telegram', catalog)
|
|
24
|
+
.filter((item) => item.menuVisible !== false)
|
|
25
|
+
.flatMap((item) => [item, ...(item.aliases ?? [])]
|
|
26
|
+
.filter((entry) => entry.menuVisible !== false && entry.enabled !== false
|
|
27
|
+
&& (!entry.channels || entry.channels.includes('telegram')))
|
|
28
|
+
.map((entry) => ({
|
|
29
|
+
command: entry.name,
|
|
30
|
+
description: translate(entry.description ?? item.description),
|
|
31
|
+
})));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function telegramCommandMenu(catalog = SHARED_COMMAND_CATALOG) {
|
|
35
|
+
const commands = commandMenuEntries(catalog, t);
|
|
36
|
+
validateTelegramCommands(commands, { allowEmpty: true });
|
|
37
|
+
return commands;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Retain the source-language export for existing consumers, derived from the
|
|
41
|
+
// catalog. Runtime synchronization always generates a fresh, localized list.
|
|
42
|
+
export const TELEGRAM_COMMAND_MENU = Object.freeze(
|
|
43
|
+
commandMenuEntries(SHARED_COMMAND_CATALOG, (text) => text).map((item) => Object.freeze(item)),
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
function mentionedUsername(message, username) {
|
|
47
|
+
if (!username) return false;
|
|
48
|
+
return [
|
|
49
|
+
[message?.text, message?.entities],
|
|
50
|
+
[message?.caption, message?.caption_entities],
|
|
51
|
+
].some(([text, entities]) => typeof text === 'string' && Array.isArray(entities)
|
|
52
|
+
&& entities.some((entity) => {
|
|
53
|
+
if (entity?.type !== 'mention' || !Number.isInteger(entity.offset)
|
|
54
|
+
|| !Number.isInteger(entity.length)) return false;
|
|
55
|
+
return text.slice(entity.offset, entity.offset + entity.length).toLowerCase()
|
|
56
|
+
=== `@${username.toLowerCase()}`;
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isUsernameBoundary(character) {
|
|
61
|
+
return character === undefined || !(/[a-z0-9_]/i).test(character);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function withoutBotMention(text, username) {
|
|
65
|
+
if (!username || typeof text !== 'string') return text;
|
|
66
|
+
const target = `@${username}`.toLowerCase();
|
|
67
|
+
let result = '';
|
|
68
|
+
let offset = 0;
|
|
69
|
+
while (offset < text.length) {
|
|
70
|
+
// Case-fold only the candidate: Unicode casing can change the full text's length.
|
|
71
|
+
if (text[offset] === '@'
|
|
72
|
+
&& text.slice(offset, offset + target.length).toLowerCase() === target
|
|
73
|
+
&& isUsernameBoundary(text[offset + target.length])) {
|
|
74
|
+
offset += target.length;
|
|
75
|
+
} else {
|
|
76
|
+
result += text[offset];
|
|
77
|
+
offset += 1;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return result.trim();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const IMAGE_MEDIA_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
|
|
84
|
+
const IMAGE_FILE_TYPES = new Map([
|
|
85
|
+
['.jpg', 'image/jpeg'],
|
|
86
|
+
['.jpeg', 'image/jpeg'],
|
|
87
|
+
['.png', 'image/png'],
|
|
88
|
+
['.webp', 'image/webp'],
|
|
89
|
+
['.gif', 'image/gif'],
|
|
90
|
+
]);
|
|
91
|
+
|
|
92
|
+
function imageTypeForDocument(document) {
|
|
93
|
+
const declaredType = document?.mime_type ?? document?.mimetype;
|
|
94
|
+
const type = typeof declaredType === 'string' ? declaredType.toLowerCase() : '';
|
|
95
|
+
if (IMAGE_MEDIA_TYPES.has(type)) return type;
|
|
96
|
+
const filename = typeof document?.file_name === 'string' ? document.file_name.toLowerCase() : '';
|
|
97
|
+
for (const [extension, mediaType] of IMAGE_FILE_TYPES) {
|
|
98
|
+
if (filename.endsWith(extension)) return mediaType;
|
|
99
|
+
}
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function fileSize(value) {
|
|
104
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function photoScore(photo) {
|
|
108
|
+
return fileSize(photo?.file_size) ?? ((Number(photo?.width) || 0) * (Number(photo?.height) || 0));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function telegramImageSource(message, loadFile) {
|
|
112
|
+
let file;
|
|
113
|
+
let mediaType;
|
|
114
|
+
let name;
|
|
115
|
+
if (Array.isArray(message?.photo) && message.photo.length > 0) {
|
|
116
|
+
file = message.photo.reduce((largest, candidate) => (
|
|
117
|
+
photoScore(candidate) > photoScore(largest) ? candidate : largest
|
|
118
|
+
));
|
|
119
|
+
mediaType = 'image/jpeg';
|
|
120
|
+
name = `${file.file_unique_id ?? file.file_id ?? 'telegram-photo'}.jpg`;
|
|
121
|
+
} else if (message?.document) {
|
|
122
|
+
const type = imageTypeForDocument(message.document);
|
|
123
|
+
if (!type) return null;
|
|
124
|
+
file = message.document;
|
|
125
|
+
mediaType = type;
|
|
126
|
+
name = typeof file.file_name === 'string' ? file.file_name : undefined;
|
|
127
|
+
}
|
|
128
|
+
if (!file || typeof file.file_id !== 'string') return null;
|
|
129
|
+
return {
|
|
130
|
+
name,
|
|
131
|
+
mediaType,
|
|
132
|
+
size: fileSize(file.file_size),
|
|
133
|
+
load: (options) => loadFile(file.file_id, options),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function telegramFileSource(message, loadFile) {
|
|
138
|
+
const file = message?.document;
|
|
139
|
+
if (!file || imageTypeForDocument(file)
|
|
140
|
+
|| typeof file.file_id !== 'string' || !file.file_id) return null;
|
|
141
|
+
const mediaType = typeof file.mime_type === 'string' && file.mime_type
|
|
142
|
+
? file.mime_type.toLowerCase() : undefined;
|
|
143
|
+
return {
|
|
144
|
+
name: typeof file.file_name === 'string' && file.file_name
|
|
145
|
+
? file.file_name : String(file.file_unique_id ?? file.file_id),
|
|
146
|
+
...(mediaType ? { mediaType } : {}),
|
|
147
|
+
size: fileSize(file.file_size),
|
|
148
|
+
load: ({ signal } = {}) => loadFile(file.file_id, { signal }),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function telegramReplyAttachment(kind, file) {
|
|
153
|
+
if (!file || typeof file !== 'object') return null;
|
|
154
|
+
const name = typeof file.file_name === 'string' && file.file_name
|
|
155
|
+
? file.file_name : undefined;
|
|
156
|
+
return { kind, ...(name ? { name } : {}) };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function telegramReplyAttachments(message) {
|
|
160
|
+
const attachments = [];
|
|
161
|
+
if (Array.isArray(message?.photo) && message.photo.length > 0) {
|
|
162
|
+
const largest = message.photo.reduce((best, candidate) => (
|
|
163
|
+
photoScore(candidate) > photoScore(best) ? candidate : best
|
|
164
|
+
));
|
|
165
|
+
attachments.push(telegramReplyAttachment('image', largest));
|
|
166
|
+
} else if (message?.document) {
|
|
167
|
+
attachments.push(telegramReplyAttachment(
|
|
168
|
+
imageTypeForDocument(message.document) ? 'image' : 'file',
|
|
169
|
+
message.document,
|
|
170
|
+
));
|
|
171
|
+
}
|
|
172
|
+
for (const [field, kind] of [
|
|
173
|
+
['audio', 'audio'],
|
|
174
|
+
['voice', 'audio'],
|
|
175
|
+
['video', 'video'],
|
|
176
|
+
['video_note', 'video'],
|
|
177
|
+
['animation', 'video'],
|
|
178
|
+
]) {
|
|
179
|
+
if (message?.[field]) attachments.push(telegramReplyAttachment(kind, message[field]));
|
|
180
|
+
}
|
|
181
|
+
if (message?.sticker) {
|
|
182
|
+
attachments.push(telegramReplyAttachment(
|
|
183
|
+
message.sticker.is_video === true ? 'video' : 'image',
|
|
184
|
+
message.sticker,
|
|
185
|
+
));
|
|
186
|
+
}
|
|
187
|
+
return attachments.filter(Boolean);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function telegramReplyReference(message, { quote, loadReplyContent } = {}) {
|
|
191
|
+
if ((!message || typeof message !== 'object')
|
|
192
|
+
&& (!quote || typeof quote !== 'object')) return undefined;
|
|
193
|
+
const authorId = message?.from?.id === undefined ? undefined : String(message.from.id);
|
|
194
|
+
const authorName = [message?.from?.first_name, message?.from?.last_name]
|
|
195
|
+
.filter((value) => typeof value === 'string' && value.trim())
|
|
196
|
+
.map((value) => value.trim()).join(' ') || (
|
|
197
|
+
typeof message?.from?.username === 'string' && message.from.username
|
|
198
|
+
? message.from.username : undefined
|
|
199
|
+
);
|
|
200
|
+
const content = typeof message?.text === 'string'
|
|
201
|
+
? message.text : typeof message?.caption === 'string'
|
|
202
|
+
? message.caption : typeof quote?.text === 'string' ? quote.text : '';
|
|
203
|
+
const attachments = telegramReplyAttachments(message);
|
|
204
|
+
const messageId = Number.isSafeInteger(message?.message_id)
|
|
205
|
+
? String(message.message_id) : undefined;
|
|
206
|
+
const createdAt = Number.isSafeInteger(message?.date) && message.date >= 0
|
|
207
|
+
? message.date * 1_000 : undefined;
|
|
208
|
+
const load = !content.trim() && attachments.length === 0
|
|
209
|
+
&& typeof loadReplyContent === 'function'
|
|
210
|
+
? ({ signal } = {}) => loadReplyContent({
|
|
211
|
+
...(messageId ? { messageId } : {}),
|
|
212
|
+
...(createdAt === undefined ? {} : { createdAt }),
|
|
213
|
+
}, { signal })
|
|
214
|
+
: null;
|
|
215
|
+
return {
|
|
216
|
+
...(messageId ? { messageId } : {}),
|
|
217
|
+
...(authorId ? { authorId } : {}),
|
|
218
|
+
...(authorName ? { authorName } : {}),
|
|
219
|
+
...(content.trim() ? { content } : {}),
|
|
220
|
+
...(attachments.length > 0 ? { attachments } : {}),
|
|
221
|
+
...(load ? { load } : {}),
|
|
222
|
+
...(!content.trim() && attachments.length === 0 && !load
|
|
223
|
+
? { unavailableReason: 'not-delivered' }
|
|
224
|
+
: {}),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Normalize an inline-keyboard press into the same shape the bridge already
|
|
230
|
+
* consumes for messages, so a button reuses the existing conversation key,
|
|
231
|
+
* access policy, and pending-interaction routing instead of a parallel path.
|
|
232
|
+
* A press always counts as addressed: the user acted on a message the bot sent.
|
|
233
|
+
*/
|
|
234
|
+
export function normalizeTelegramCallback(update, { botId } = {}) {
|
|
235
|
+
const callback = update?.callback_query;
|
|
236
|
+
const message = callback?.message;
|
|
237
|
+
const chatId = message?.chat?.id;
|
|
238
|
+
const senderId = callback?.from?.id;
|
|
239
|
+
const providerMessageId = message?.message_id;
|
|
240
|
+
if (!Number.isSafeInteger(update?.update_id)
|
|
241
|
+
|| typeof callback?.id !== 'string' || !callback.id
|
|
242
|
+
|| chatId === undefined || senderId === undefined
|
|
243
|
+
|| !Number.isSafeInteger(providerMessageId)) return null;
|
|
244
|
+
if (!['private', 'group', 'supergroup'].includes(message.chat?.type)) return null;
|
|
245
|
+
const direct = message.chat.type === 'private';
|
|
246
|
+
const messageThreadId = Number.isSafeInteger(message.message_thread_id)
|
|
247
|
+
? message.message_thread_id : undefined;
|
|
248
|
+
const conversationId = messageThreadId === undefined
|
|
249
|
+
? String(chatId) : `${chatId}:${messageThreadId}`;
|
|
250
|
+
return {
|
|
251
|
+
messageId: String(update.update_id),
|
|
252
|
+
callbackQueryId: callback.id,
|
|
253
|
+
providerMessageId,
|
|
254
|
+
senderId: String(senderId),
|
|
255
|
+
senderIsBot: callback.from?.is_bot === true,
|
|
256
|
+
kind: direct ? 'direct' : 'group',
|
|
257
|
+
conversationId,
|
|
258
|
+
data: typeof callback.data === 'string' ? callback.data : '',
|
|
259
|
+
addressed: true,
|
|
260
|
+
replyTarget: {
|
|
261
|
+
chatId,
|
|
262
|
+
chatType: message.chat.type,
|
|
263
|
+
messageThreadId,
|
|
264
|
+
},
|
|
265
|
+
reactionTarget: { chatId, messageId: providerMessageId },
|
|
266
|
+
contextSource: () => ({
|
|
267
|
+
senderName: [callback.from?.first_name, callback.from?.last_name]
|
|
268
|
+
.filter((value) => typeof value === 'string' && value.trim())
|
|
269
|
+
.map((value) => value.trim()).join(' ') || callback.from?.username,
|
|
270
|
+
conversationTitle: direct ? undefined : message.chat?.title,
|
|
271
|
+
chatId: String(chatId),
|
|
272
|
+
threadId: messageThreadId === undefined ? undefined : String(messageThreadId),
|
|
273
|
+
}),
|
|
274
|
+
...(botId === undefined ? {} : { botId }),
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function normalizeTelegramUpdate(update, {
|
|
279
|
+
botId,
|
|
280
|
+
username,
|
|
281
|
+
loadFile = async () => { throw new Error('Telegram file downloader is unavailable'); },
|
|
282
|
+
loadFileStream = loadFile,
|
|
283
|
+
loadReplyContent,
|
|
284
|
+
}) {
|
|
285
|
+
const message = update?.message;
|
|
286
|
+
const chatId = message?.chat?.id;
|
|
287
|
+
const senderId = message?.from?.id;
|
|
288
|
+
const messageId = message?.message_id;
|
|
289
|
+
if (!Number.isSafeInteger(update?.update_id) || chatId === undefined || senderId === undefined
|
|
290
|
+
|| !Number.isSafeInteger(messageId)) return null;
|
|
291
|
+
if (!['private', 'group', 'supergroup'].includes(message.chat?.type)) return null;
|
|
292
|
+
const direct = message.chat.type === 'private';
|
|
293
|
+
const addressed = direct
|
|
294
|
+
|| String(message.reply_to_message?.from?.id ?? '') === String(botId)
|
|
295
|
+
|| mentionedUsername(message, username);
|
|
296
|
+
const messageThreadId = Number.isSafeInteger(message.message_thread_id)
|
|
297
|
+
? message.message_thread_id : undefined;
|
|
298
|
+
const image = telegramImageSource(message, loadFile);
|
|
299
|
+
const file = telegramFileSource(message, loadFileStream);
|
|
300
|
+
const conversationId = messageThreadId === undefined
|
|
301
|
+
? String(chatId) : `${chatId}:${messageThreadId}`;
|
|
302
|
+
const key = `${direct ? 'direct' : 'group'}:${conversationId}`;
|
|
303
|
+
const replyTo = telegramReplyReference(
|
|
304
|
+
message.reply_to_message ?? message.external_reply,
|
|
305
|
+
{
|
|
306
|
+
quote: message.quote,
|
|
307
|
+
...(typeof loadReplyContent === 'function' ? {
|
|
308
|
+
loadReplyContent: (reference, options) => loadReplyContent({
|
|
309
|
+
conversationKey: key,
|
|
310
|
+
...reference,
|
|
311
|
+
}, options),
|
|
312
|
+
} : {}),
|
|
313
|
+
},
|
|
314
|
+
);
|
|
315
|
+
return {
|
|
316
|
+
messageId: String(update.update_id),
|
|
317
|
+
senderId: String(senderId),
|
|
318
|
+
contextSource: () => ({
|
|
319
|
+
senderName: [message.from?.first_name, message.from?.last_name]
|
|
320
|
+
.filter((value) => typeof value === 'string' && value.trim())
|
|
321
|
+
.map((value) => value.trim()).join(' ') || message.from?.username,
|
|
322
|
+
conversationTitle: direct ? undefined : message.chat?.title,
|
|
323
|
+
chatId: String(chatId),
|
|
324
|
+
threadId: messageThreadId === undefined ? undefined : String(messageThreadId),
|
|
325
|
+
}),
|
|
326
|
+
senderIsBot: message.from?.is_bot === true,
|
|
327
|
+
kind: direct ? 'direct' : 'group',
|
|
328
|
+
conversationId,
|
|
329
|
+
content: withoutBotMention(message.text ?? message.caption ?? '', username),
|
|
330
|
+
plainText: typeof message.text === 'string',
|
|
331
|
+
images: image ? [image] : [],
|
|
332
|
+
files: file ? [file] : [],
|
|
333
|
+
...(replyTo ? { replyTo } : {}),
|
|
334
|
+
addressed,
|
|
335
|
+
reactionTarget: { chatId, messageId },
|
|
336
|
+
replyTarget: {
|
|
337
|
+
chatId,
|
|
338
|
+
chatType: message.chat.type,
|
|
339
|
+
replyToMessageId: messageId,
|
|
340
|
+
messageThreadId,
|
|
341
|
+
},
|
|
342
|
+
connectionTestTarget: { chatId, messageThreadId },
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function telegramInboundAllowed(message, {
|
|
347
|
+
accessMode = TELEGRAM_ACCESS_MODES.compatible,
|
|
348
|
+
allowedPrivateUserIds = new Set(),
|
|
349
|
+
} = {}) {
|
|
350
|
+
if (accessMode !== TELEGRAM_ACCESS_MODES.privateAllowlist) return true;
|
|
351
|
+
return message?.kind === 'direct'
|
|
352
|
+
&& allowedPrivateUserIds instanceof Set
|
|
353
|
+
&& allowedPrivateUserIds.has(String(message.senderId));
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function telegramMessageId(value) {
|
|
357
|
+
return Number.isSafeInteger(value?.message_id) ? String(value.message_id) : null;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function telegramFailure(error) {
|
|
361
|
+
const providerCode = Number(error?.providerCode);
|
|
362
|
+
const status = Number(error?.status);
|
|
363
|
+
const unknown = error?.deliveryOutcome === 'unknown'
|
|
364
|
+
|| providerCode >= 500
|
|
365
|
+
|| status >= 500
|
|
366
|
+
|| ['telegram-timeout', 'telegram-aborted-after-dispatch', 'telegram-transport-error',
|
|
367
|
+
'telegram-response-invalid'].includes(error?.code);
|
|
368
|
+
return {
|
|
369
|
+
outcome: unknown ? 'unknown' : 'failed',
|
|
370
|
+
reason: typeof error?.code === 'string' && error.code
|
|
371
|
+
? error.code
|
|
372
|
+
: unknown ? 'telegram-delivery-uncertain' : 'telegram-provider-rejected',
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function deliveryResult(presentation, providerMessageIds, deliveryOutcome = 'sent', reason) {
|
|
377
|
+
return {
|
|
378
|
+
presentation,
|
|
379
|
+
providerMessageIds: [...new Set(providerMessageIds)],
|
|
380
|
+
deliveryOutcome,
|
|
381
|
+
...(reason ? { reason } : {}),
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
class TelegramDeliveryStream {
|
|
386
|
+
#update;
|
|
387
|
+
#finish;
|
|
388
|
+
#fail;
|
|
389
|
+
#logger;
|
|
390
|
+
#providerMessageIds;
|
|
391
|
+
#closed = false;
|
|
392
|
+
#lastUpdate = null;
|
|
393
|
+
#lastBlock = null;
|
|
394
|
+
#keepalive = false;
|
|
395
|
+
#previewStopped = false;
|
|
396
|
+
#chain = Promise.resolve();
|
|
397
|
+
|
|
398
|
+
constructor({
|
|
399
|
+
update,
|
|
400
|
+
finish,
|
|
401
|
+
fail,
|
|
402
|
+
providerMessageIds = [],
|
|
403
|
+
presentation,
|
|
404
|
+
logger,
|
|
405
|
+
keepalive = false,
|
|
406
|
+
}) {
|
|
407
|
+
this.#update = update;
|
|
408
|
+
this.#finish = finish;
|
|
409
|
+
this.#fail = fail;
|
|
410
|
+
this.#providerMessageIds = providerMessageIds;
|
|
411
|
+
this.presentation = presentation;
|
|
412
|
+
this.#logger = logger;
|
|
413
|
+
// Only short-lived carriers (e.g. the private-chat Rich Draft) need a
|
|
414
|
+
// keepalive refresh; editing a real placeholder message with identical
|
|
415
|
+
// content would be rejected by the platform.
|
|
416
|
+
this.#keepalive = keepalive === true;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
get providerMessageIds() {
|
|
420
|
+
return [...this.#providerMessageIds];
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** Whether this carrier is short-lived and wants a keepalive heartbeat. */
|
|
424
|
+
get keepalive() {
|
|
425
|
+
return this.#keepalive;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** Serialize every write so an in-flight keepalive refresh can never land
|
|
429
|
+
* after the final frame: finish()/fail() queue behind refresh()/update(). */
|
|
430
|
+
#enqueue(task) {
|
|
431
|
+
const run = this.#chain.then(task);
|
|
432
|
+
this.#chain = run.catch(() => undefined);
|
|
433
|
+
return run;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// Live drafts can block the user's composer. Drain any pending draft before
|
|
437
|
+
// the regular question/approval message clears it, and keep this turn's
|
|
438
|
+
// preview stopped so late progress cannot block the answer again.
|
|
439
|
+
stopPreview() {
|
|
440
|
+
this.#previewStopped = true;
|
|
441
|
+
return this.#enqueue(() => undefined);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
update(value) {
|
|
445
|
+
return this.#enqueue(async () => {
|
|
446
|
+
if (this.#closed || this.#previewStopped) return undefined;
|
|
447
|
+
const block = createTextDeliveryBlock(value);
|
|
448
|
+
this.#lastBlock = block;
|
|
449
|
+
const key = `${block.format}:${block.text}`;
|
|
450
|
+
if (key === this.#lastUpdate) return undefined;
|
|
451
|
+
this.#lastUpdate = key;
|
|
452
|
+
try {
|
|
453
|
+
return await this.#update(block);
|
|
454
|
+
} catch (error) {
|
|
455
|
+
this.#logger.warn?.('[dsh-im:telegram] rich stream update failed:', extractConnectionEvidence(error).details);
|
|
456
|
+
return undefined;
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** Re-send the most recent frame even when unchanged, to keep a short-lived
|
|
462
|
+
* carrier (the private-chat Rich Draft) visible during long silent
|
|
463
|
+
* stretches such as a running tool call. Serialized like update() so it
|
|
464
|
+
* never overtakes a later finish(). No-op for carriers without keepalive. */
|
|
465
|
+
refresh() {
|
|
466
|
+
return this.#enqueue(async () => {
|
|
467
|
+
if (this.#closed || this.#previewStopped || !this.#keepalive || !this.#lastBlock) return undefined;
|
|
468
|
+
try {
|
|
469
|
+
return await this.#update(this.#lastBlock);
|
|
470
|
+
} catch (error) {
|
|
471
|
+
this.#logger.warn?.('[dsh-im:telegram] rich stream refresh failed:', extractConnectionEvidence(error).details);
|
|
472
|
+
return undefined;
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
finish(value) {
|
|
478
|
+
return this.#enqueue(async () => {
|
|
479
|
+
if (this.#closed) throw new Error('Message stream is already closed');
|
|
480
|
+
this.#closed = true;
|
|
481
|
+
const result = await this.#finish(createTextDeliveryBlock(value));
|
|
482
|
+
this.#providerMessageIds.push(...(result?.providerMessageIds ?? []));
|
|
483
|
+
return result;
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
fail(text) {
|
|
488
|
+
return this.#enqueue(async () => {
|
|
489
|
+
if (this.#closed) return undefined;
|
|
490
|
+
this.#closed = true;
|
|
491
|
+
const result = await this.#fail(createTextDeliveryBlock(text, 'plain'));
|
|
492
|
+
this.#providerMessageIds.push(...(result?.providerMessageIds ?? []));
|
|
493
|
+
return result;
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
cancel() {
|
|
498
|
+
this.#closed = true;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// Thinking-trace display rules. Truncation fallback (spoiler / inline-button
|
|
503
|
+
// expansion are follow-ups gated on three-platform client verification):
|
|
504
|
+
// tool traces cap the argument summary, reasoning caps the first paragraph.
|
|
505
|
+
const TOOL_TRACE_ARG_KEYS = Object.freeze([
|
|
506
|
+
'command', 'pattern', 'query', 'url', 'file_path', 'path', 'text', 'prompt', 'message', 'description',
|
|
507
|
+
]);
|
|
508
|
+
const TOOL_TRACE_SUMMARY_LIMIT = 120;
|
|
509
|
+
const THINKING_LINE_LIMIT = 200;
|
|
510
|
+
|
|
511
|
+
function truncateCapped(value, limit) {
|
|
512
|
+
return value.length > limit ? `${value.slice(0, limit)}…` : value;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Extract a one-line argument summary from a tool call's `arguments`. */
|
|
516
|
+
export function toolTraceSummary(argumentsValue) {
|
|
517
|
+
let record = null;
|
|
518
|
+
if (argumentsValue && typeof argumentsValue === 'object' && !Array.isArray(argumentsValue)) {
|
|
519
|
+
record = argumentsValue;
|
|
520
|
+
} else if (typeof argumentsValue === 'string') {
|
|
521
|
+
const trimmed = argumentsValue.trim();
|
|
522
|
+
if (!trimmed) return null;
|
|
523
|
+
let parsed = null;
|
|
524
|
+
try {
|
|
525
|
+
parsed = JSON.parse(trimmed);
|
|
526
|
+
} catch {
|
|
527
|
+
return truncateCapped(trimmed.replace(/\s+/g, ' ').trim(), TOOL_TRACE_SUMMARY_LIMIT);
|
|
528
|
+
}
|
|
529
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
530
|
+
record = parsed;
|
|
531
|
+
} else {
|
|
532
|
+
return truncateCapped(trimmed.replace(/\s+/g, ' ').trim(), TOOL_TRACE_SUMMARY_LIMIT);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (!record) return null;
|
|
536
|
+
for (const key of TOOL_TRACE_ARG_KEYS) {
|
|
537
|
+
const value = record[key];
|
|
538
|
+
if (typeof value === 'string' && value.trim()) {
|
|
539
|
+
return truncateCapped(value.replace(/\s+/g, ' ').trim(), TOOL_TRACE_SUMMARY_LIMIT);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return null;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Format one tool-trace line: `🔧 <name> → <summary>` (summary optional). */
|
|
546
|
+
export function formatToolTrace(name, argumentsValue) {
|
|
547
|
+
const toolName = typeof name === 'string' && name.trim() ? name.trim() : t('工具');
|
|
548
|
+
const summary = toolTraceSummary(argumentsValue);
|
|
549
|
+
return summary ? `🔧 ${toolName} → ${summary}` : `🔧 ${toolName}`;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** Format one reasoning line: `💭 <first paragraph>` (200-char cap). */
|
|
553
|
+
export function formatThinkingLine(text) {
|
|
554
|
+
const trimmed = typeof text === 'string' ? text.trim() : '';
|
|
555
|
+
if (!trimmed) return null;
|
|
556
|
+
const firstParagraph = trimmed.split(/\n{2,}/)[0].trim();
|
|
557
|
+
if (!firstParagraph) return null;
|
|
558
|
+
return `💭 ${truncateCapped(firstParagraph, THINKING_LINE_LIMIT)}`;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
export class TelegramBotClient {
|
|
562
|
+
#api;
|
|
563
|
+
#signal;
|
|
564
|
+
#logger;
|
|
565
|
+
|
|
566
|
+
constructor({ api, signal, logger = console }) {
|
|
567
|
+
this.#api = api;
|
|
568
|
+
this.#signal = signal;
|
|
569
|
+
this.#logger = logger;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
async sendText(target, text) {
|
|
573
|
+
const chunks = splitTelegramRegularText(text);
|
|
574
|
+
const providerMessageIds = [];
|
|
575
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
576
|
+
const result = await this.#api.sendMessage({
|
|
577
|
+
chatId: target.chatId,
|
|
578
|
+
text: chunk,
|
|
579
|
+
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
|
|
580
|
+
messageThreadId: target.messageThreadId,
|
|
581
|
+
signal: this.#signal,
|
|
582
|
+
});
|
|
583
|
+
if (Number.isSafeInteger(result?.message_id)) {
|
|
584
|
+
providerMessageIds.push(String(result.message_id));
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
return { providerMessageIds };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Deliver a card whose inline keyboard carries the interaction payloads.
|
|
592
|
+
* Kept separate from sendText so a markup failure can be caught and degraded
|
|
593
|
+
* to the plain-text flow by the caller without losing the text itself.
|
|
594
|
+
*/
|
|
595
|
+
async sendInteractionCard(target, { text, markup, replyToMessageId } = {}) {
|
|
596
|
+
const result = await this.#api.sendMessage({
|
|
597
|
+
chatId: target.chatId,
|
|
598
|
+
text,
|
|
599
|
+
replyToMessageId: replyToMessageId ?? target.replyToMessageId,
|
|
600
|
+
messageThreadId: target.messageThreadId,
|
|
601
|
+
replyMarkup: markup,
|
|
602
|
+
signal: this.#signal,
|
|
603
|
+
});
|
|
604
|
+
const providerMessageIds = [];
|
|
605
|
+
if (Number.isSafeInteger(result?.message_id)) {
|
|
606
|
+
providerMessageIds.push(String(result.message_id));
|
|
607
|
+
}
|
|
608
|
+
return { providerMessageIds };
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** Replace a delivered card's keyboard in place; an empty keyboard removes it. */
|
|
612
|
+
async updateInteractionCard(target, providerMessageId, { markup } = {}) {
|
|
613
|
+
await this.#api.editMessageReplyMarkup({
|
|
614
|
+
chatId: target.chatId,
|
|
615
|
+
messageId: Number(providerMessageId),
|
|
616
|
+
replyMarkup: markup,
|
|
617
|
+
signal: this.#signal,
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** Stop the client-side spinner on a pressed button. */
|
|
622
|
+
async answerInteractionCallback(callbackQueryId, notice) {
|
|
623
|
+
await this.#api.answerCallbackQuery({
|
|
624
|
+
callbackQueryId,
|
|
625
|
+
text: notice,
|
|
626
|
+
signal: this.#signal,
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
async addReaction(target, emoji, { signal } = {}) {
|
|
631
|
+
const reactionKey = String(emoji ?? '').trim();
|
|
632
|
+
await this.#api.setMessageReaction({
|
|
633
|
+
chatId: target.chatId,
|
|
634
|
+
messageId: target.messageId,
|
|
635
|
+
emoji: reactionKey,
|
|
636
|
+
signal: signal ?? this.#signal,
|
|
637
|
+
});
|
|
638
|
+
return reactionKey;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
removeReaction(target, _reactionKey, { signal } = {}) {
|
|
642
|
+
return this.#api.setMessageReaction({
|
|
643
|
+
chatId: target.chatId,
|
|
644
|
+
messageId: target.messageId,
|
|
645
|
+
signal: signal ?? this.#signal,
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
sendTyping(target) {
|
|
650
|
+
return this.#api.sendChatAction({
|
|
651
|
+
chatId: target.chatId,
|
|
652
|
+
messageThreadId: target.messageThreadId,
|
|
653
|
+
signal: this.#signal,
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
sendFile(target, file) {
|
|
658
|
+
return this.#api.sendDocument({
|
|
659
|
+
chatId: target.chatId,
|
|
660
|
+
file,
|
|
661
|
+
replyToMessageId: target.replyToMessageId,
|
|
662
|
+
messageThreadId: target.messageThreadId,
|
|
663
|
+
signal: this.#signal,
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
sendImage(target, file) {
|
|
668
|
+
return this.#api.sendPhoto({
|
|
669
|
+
chatId: target.chatId,
|
|
670
|
+
file,
|
|
671
|
+
replyToMessageId: target.replyToMessageId,
|
|
672
|
+
messageThreadId: target.messageThreadId,
|
|
673
|
+
signal: this.#signal,
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
async #sendPlain(target, text, { placeholderMessageId } = {}) {
|
|
678
|
+
const chunks = splitTelegramRegularText(text);
|
|
679
|
+
const providerMessageIds = placeholderMessageId === undefined
|
|
680
|
+
? []
|
|
681
|
+
: [String(placeholderMessageId)];
|
|
682
|
+
let firstUnsent = 0;
|
|
683
|
+
if (placeholderMessageId !== undefined) {
|
|
684
|
+
try {
|
|
685
|
+
await this.#api.editMessageText({
|
|
686
|
+
chatId: target.chatId,
|
|
687
|
+
messageId: placeholderMessageId,
|
|
688
|
+
text: chunks[0],
|
|
689
|
+
signal: this.#signal,
|
|
690
|
+
});
|
|
691
|
+
firstUnsent = 1;
|
|
692
|
+
} catch (error) {
|
|
693
|
+
const failure = telegramFailure(error);
|
|
694
|
+
if (failure.outcome === 'unknown') {
|
|
695
|
+
return deliveryResult('text-fallback', providerMessageIds, 'unknown', failure.reason);
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
const fallback = await this.#sendPlain(target, text);
|
|
699
|
+
const terminalText = fallback.deliveryOutcome === 'sent'
|
|
700
|
+
? t('回复已发送。')
|
|
701
|
+
: fallback.deliveryOutcome === 'unknown'
|
|
702
|
+
? t('回复发送结果未能确认。')
|
|
703
|
+
: t('消息发送失败,请稍后重试。');
|
|
704
|
+
try {
|
|
705
|
+
await this.#api.editMessageText({
|
|
706
|
+
chatId: target.chatId,
|
|
707
|
+
messageId: placeholderMessageId,
|
|
708
|
+
text: terminalText,
|
|
709
|
+
signal: this.#signal,
|
|
710
|
+
});
|
|
711
|
+
} catch (terminalError) {
|
|
712
|
+
this.#logger.warn?.(
|
|
713
|
+
'[dsh-im:telegram] unable to replace the processing placeholder:',
|
|
714
|
+
terminalError,
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
return deliveryResult(
|
|
718
|
+
'text-fallback',
|
|
719
|
+
[...providerMessageIds, ...fallback.providerMessageIds],
|
|
720
|
+
fallback.deliveryOutcome,
|
|
721
|
+
fallback.reason,
|
|
722
|
+
);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
for (let index = firstUnsent; index < chunks.length; index += 1) {
|
|
727
|
+
try {
|
|
728
|
+
const result = await this.#api.sendMessage({
|
|
729
|
+
chatId: target.chatId,
|
|
730
|
+
text: chunks[index],
|
|
731
|
+
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
|
|
732
|
+
messageThreadId: target.messageThreadId,
|
|
733
|
+
signal: this.#signal,
|
|
734
|
+
});
|
|
735
|
+
const id = telegramMessageId(result);
|
|
736
|
+
if (id) providerMessageIds.push(id);
|
|
737
|
+
} catch (error) {
|
|
738
|
+
const failure = telegramFailure(error);
|
|
739
|
+
return deliveryResult(
|
|
740
|
+
'text-fallback',
|
|
741
|
+
providerMessageIds,
|
|
742
|
+
failure.outcome,
|
|
743
|
+
failure.reason,
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
return deliveryResult('text-fallback', providerMessageIds);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
async #sendRich(target, block) {
|
|
751
|
+
if (block.format === 'plain') return this.#sendPlain(target, block.text);
|
|
752
|
+
|
|
753
|
+
let chunks;
|
|
754
|
+
try {
|
|
755
|
+
chunks = splitTelegramRichMarkdown(block.text);
|
|
756
|
+
} catch {
|
|
757
|
+
return this.#sendPlain(target, block.text);
|
|
758
|
+
}
|
|
759
|
+
const providerMessageIds = [];
|
|
760
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
761
|
+
try {
|
|
762
|
+
const result = await this.#api.sendRichMessage({
|
|
763
|
+
chatId: target.chatId,
|
|
764
|
+
richMessage: { markdown: chunk.markdown },
|
|
765
|
+
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
|
|
766
|
+
messageThreadId: target.messageThreadId,
|
|
767
|
+
signal: this.#signal,
|
|
768
|
+
});
|
|
769
|
+
const id = telegramMessageId(result);
|
|
770
|
+
if (id) providerMessageIds.push(id);
|
|
771
|
+
} catch (error) {
|
|
772
|
+
const failure = telegramFailure(error);
|
|
773
|
+
if (failure.outcome === 'unknown') {
|
|
774
|
+
return deliveryResult(
|
|
775
|
+
'telegram-rich-final',
|
|
776
|
+
providerMessageIds,
|
|
777
|
+
'unknown',
|
|
778
|
+
failure.reason,
|
|
779
|
+
);
|
|
780
|
+
}
|
|
781
|
+
const remaining = chunks.slice(index).map((part) => part.source).join('');
|
|
782
|
+
const fallback = await this.#sendPlain({
|
|
783
|
+
...target,
|
|
784
|
+
replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
|
|
785
|
+
}, remaining);
|
|
786
|
+
return deliveryResult(
|
|
787
|
+
fallback.presentation,
|
|
788
|
+
[...providerMessageIds, ...fallback.providerMessageIds],
|
|
789
|
+
fallback.deliveryOutcome,
|
|
790
|
+
fallback.reason,
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
return deliveryResult('telegram-rich-final', providerMessageIds);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
async #editRich(target, messageId, block) {
|
|
798
|
+
if (block.format === 'plain') {
|
|
799
|
+
return this.#sendPlain(target, block.text, {
|
|
800
|
+
placeholderMessageId: messageId,
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
let chunks;
|
|
805
|
+
try {
|
|
806
|
+
chunks = splitTelegramRichMarkdown(block.text);
|
|
807
|
+
} catch {
|
|
808
|
+
return this.#sendPlain(target, block.text, { placeholderMessageId: messageId });
|
|
809
|
+
}
|
|
810
|
+
const providerMessageIds = [String(messageId)];
|
|
811
|
+
try {
|
|
812
|
+
await this.#api.editMessageText({
|
|
813
|
+
chatId: target.chatId,
|
|
814
|
+
messageId,
|
|
815
|
+
richMessage: { markdown: chunks[0].markdown },
|
|
816
|
+
signal: this.#signal,
|
|
817
|
+
});
|
|
818
|
+
} catch (error) {
|
|
819
|
+
const failure = telegramFailure(error);
|
|
820
|
+
if (failure.outcome === 'unknown') {
|
|
821
|
+
return deliveryResult(
|
|
822
|
+
'telegram-rich-final',
|
|
823
|
+
providerMessageIds,
|
|
824
|
+
'unknown',
|
|
825
|
+
failure.reason,
|
|
826
|
+
);
|
|
827
|
+
}
|
|
828
|
+
return this.#sendPlain(target, block.text, { placeholderMessageId: messageId });
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
for (const [offset, chunk] of chunks.slice(1).entries()) {
|
|
832
|
+
try {
|
|
833
|
+
const result = await this.#api.sendRichMessage({
|
|
834
|
+
chatId: target.chatId,
|
|
835
|
+
richMessage: { markdown: chunk.markdown },
|
|
836
|
+
messageThreadId: target.messageThreadId,
|
|
837
|
+
signal: this.#signal,
|
|
838
|
+
});
|
|
839
|
+
const id = telegramMessageId(result);
|
|
840
|
+
if (id) providerMessageIds.push(id);
|
|
841
|
+
} catch (error) {
|
|
842
|
+
const failure = telegramFailure(error);
|
|
843
|
+
if (failure.outcome === 'unknown') {
|
|
844
|
+
return deliveryResult(
|
|
845
|
+
'telegram-rich-final',
|
|
846
|
+
providerMessageIds,
|
|
847
|
+
'unknown',
|
|
848
|
+
failure.reason,
|
|
849
|
+
);
|
|
850
|
+
}
|
|
851
|
+
const remaining = chunks.slice(offset + 1).map((part) => part.source).join('');
|
|
852
|
+
const fallback = await this.#sendPlain({
|
|
853
|
+
...target,
|
|
854
|
+
replyToMessageId: undefined,
|
|
855
|
+
}, remaining);
|
|
856
|
+
return deliveryResult(
|
|
857
|
+
fallback.presentation,
|
|
858
|
+
[...providerMessageIds, ...fallback.providerMessageIds],
|
|
859
|
+
fallback.deliveryOutcome,
|
|
860
|
+
fallback.reason,
|
|
861
|
+
);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
return deliveryResult('telegram-rich-final', providerMessageIds);
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
sendDelivery(target, value) {
|
|
868
|
+
return this.#sendRich(target, createTextDeliveryBlock(value));
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
async openDeliveryStream(target) {
|
|
872
|
+
if (target.chatType === 'private') {
|
|
873
|
+
const draftId = randomInt(1, 2_147_483_647);
|
|
874
|
+
const updateDraft = async (block) => {
|
|
875
|
+
const richMessage = { markdown: toTelegramRichMarkdown(block.text) };
|
|
876
|
+
await this.#api.sendRichMessageDraft({
|
|
877
|
+
chatId: target.chatId,
|
|
878
|
+
draftId,
|
|
879
|
+
richMessage,
|
|
880
|
+
messageThreadId: target.messageThreadId,
|
|
881
|
+
signal: this.#signal,
|
|
882
|
+
});
|
|
883
|
+
return deliveryResult('telegram-rich-draft', []);
|
|
884
|
+
};
|
|
885
|
+
const stream = new TelegramDeliveryStream({
|
|
886
|
+
update: updateDraft,
|
|
887
|
+
finish: (block) => this.#sendRich(target, block),
|
|
888
|
+
fail: (block) => this.#sendPlain(target, block.text),
|
|
889
|
+
presentation: 'telegram-rich-draft',
|
|
890
|
+
keepalive: true,
|
|
891
|
+
logger: this.#logger,
|
|
892
|
+
});
|
|
893
|
+
await stream.update(createTextDeliveryBlock(t('正在处理…'), 'plain'));
|
|
894
|
+
return stream;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
const placeholder = await this.#api.sendMessage({
|
|
898
|
+
chatId: target.chatId,
|
|
899
|
+
text: t('正在处理…'),
|
|
900
|
+
replyToMessageId: target.replyToMessageId,
|
|
901
|
+
messageThreadId: target.messageThreadId,
|
|
902
|
+
signal: this.#signal,
|
|
903
|
+
});
|
|
904
|
+
const messageId = placeholder?.message_id;
|
|
905
|
+
if (!Number.isSafeInteger(messageId)) {
|
|
906
|
+
throw new Error('Telegram did not return a placeholder message id');
|
|
907
|
+
}
|
|
908
|
+
return new TelegramDeliveryStream({
|
|
909
|
+
update: async (block) => {
|
|
910
|
+
if (block.format === 'plain') {
|
|
911
|
+
await this.#api.editMessageText({
|
|
912
|
+
chatId: target.chatId,
|
|
913
|
+
messageId,
|
|
914
|
+
text: block.text,
|
|
915
|
+
signal: this.#signal,
|
|
916
|
+
});
|
|
917
|
+
return deliveryResult('text-fallback', [String(messageId)]);
|
|
918
|
+
}
|
|
919
|
+
await this.#api.editMessageText({
|
|
920
|
+
chatId: target.chatId,
|
|
921
|
+
messageId,
|
|
922
|
+
richMessage: { markdown: toTelegramRichMarkdown(block.text) },
|
|
923
|
+
signal: this.#signal,
|
|
924
|
+
});
|
|
925
|
+
return deliveryResult('telegram-rich-draft', [String(messageId)]);
|
|
926
|
+
},
|
|
927
|
+
finish: (block) => this.#editRich(target, messageId, block),
|
|
928
|
+
fail: (block) => this.#sendPlain(target, block.text, {
|
|
929
|
+
placeholderMessageId: messageId,
|
|
930
|
+
}),
|
|
931
|
+
providerMessageIds: [String(messageId)],
|
|
932
|
+
presentation: 'telegram-regular',
|
|
933
|
+
logger: this.#logger,
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
async openStream(target) {
|
|
938
|
+
const stream = createEditableMessageStream({
|
|
939
|
+
limit: 4_000,
|
|
940
|
+
create: async (text) => {
|
|
941
|
+
const message = await this.#api.sendMessage({
|
|
942
|
+
chatId: target.chatId,
|
|
943
|
+
text,
|
|
944
|
+
replyToMessageId: target.replyToMessageId,
|
|
945
|
+
messageThreadId: target.messageThreadId,
|
|
946
|
+
signal: this.#signal,
|
|
947
|
+
});
|
|
948
|
+
return message.message_id;
|
|
949
|
+
},
|
|
950
|
+
edit: (messageId, text) => this.#api.editMessageText({
|
|
951
|
+
chatId: target.chatId,
|
|
952
|
+
messageId,
|
|
953
|
+
text,
|
|
954
|
+
signal: this.#signal,
|
|
955
|
+
}),
|
|
956
|
+
sendRemainder: (text) => this.#api.sendMessage({
|
|
957
|
+
chatId: target.chatId,
|
|
958
|
+
text,
|
|
959
|
+
messageThreadId: target.messageThreadId,
|
|
960
|
+
signal: this.#signal,
|
|
961
|
+
}),
|
|
962
|
+
messageIdForResult: (message) => message?.message_id,
|
|
963
|
+
});
|
|
964
|
+
return stream.start();
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
/**
|
|
968
|
+
* Thinking-trace stream: every intermediate line is a permanent, separate
|
|
969
|
+
* Telegram message (no placeholder editing), so the user watches the
|
|
970
|
+
* "think → act" chain build up. Trace lines are best-effort; the final
|
|
971
|
+
* answer must still land, falling back to plain sendText delivery.
|
|
972
|
+
*/
|
|
973
|
+
openThinkingStream(target) {
|
|
974
|
+
const client = this;
|
|
975
|
+
const providerMessageIds = [];
|
|
976
|
+
let firstMessageId = null;
|
|
977
|
+
let closed = false;
|
|
978
|
+
const logger = this.#logger;
|
|
979
|
+
const warnFailure = (label, error) => {
|
|
980
|
+
logger?.warn?.(`[dsh-im:telegram] thinking stream ${label} failed:`, error);
|
|
981
|
+
};
|
|
982
|
+
const sendLine = async (text) => {
|
|
983
|
+
const message = await this.#api.sendMessage({
|
|
984
|
+
chatId: target.chatId,
|
|
985
|
+
text,
|
|
986
|
+
replyToMessageId: firstMessageId === null ? target.replyToMessageId : undefined,
|
|
987
|
+
messageThreadId: target.messageThreadId,
|
|
988
|
+
signal: this.#signal,
|
|
989
|
+
});
|
|
990
|
+
const id = message?.message_id;
|
|
991
|
+
if (Number.isSafeInteger(id)) {
|
|
992
|
+
if (firstMessageId === null) firstMessageId = id;
|
|
993
|
+
providerMessageIds.push(String(id));
|
|
994
|
+
}
|
|
995
|
+
};
|
|
996
|
+
return {
|
|
997
|
+
get messageId() {
|
|
998
|
+
return firstMessageId;
|
|
999
|
+
},
|
|
1000
|
+
get providerMessageIds() {
|
|
1001
|
+
return [...providerMessageIds];
|
|
1002
|
+
},
|
|
1003
|
+
presentation: 'telegram-thinking',
|
|
1004
|
+
// The chain is made of permanent messages, but long tool runs still
|
|
1005
|
+
// want the typing indicator; the bridge re-sends it every 4 seconds.
|
|
1006
|
+
keepalive: true,
|
|
1007
|
+
update: async () => {},
|
|
1008
|
+
refresh: async () => {},
|
|
1009
|
+
sendLine,
|
|
1010
|
+
sendToolTrace: (name, argumentsValue) => (async () => {
|
|
1011
|
+
if (closed) return;
|
|
1012
|
+
try {
|
|
1013
|
+
await sendLine(formatToolTrace(name, argumentsValue));
|
|
1014
|
+
} catch (error) {
|
|
1015
|
+
warnFailure('tool trace', error);
|
|
1016
|
+
}
|
|
1017
|
+
})(),
|
|
1018
|
+
sendThinking: (text) => (async () => {
|
|
1019
|
+
if (closed) return;
|
|
1020
|
+
const line = formatThinkingLine(text);
|
|
1021
|
+
if (!line) return;
|
|
1022
|
+
try {
|
|
1023
|
+
await sendLine(line);
|
|
1024
|
+
} catch (error) {
|
|
1025
|
+
warnFailure('thinking line', error);
|
|
1026
|
+
}
|
|
1027
|
+
})(),
|
|
1028
|
+
async finish(answer) {
|
|
1029
|
+
if (closed) throw new Error('Message stream is already closed');
|
|
1030
|
+
closed = true;
|
|
1031
|
+
const format = answer && typeof answer === 'object' && answer.format === 'markdown'
|
|
1032
|
+
? 'markdown'
|
|
1033
|
+
: 'plain';
|
|
1034
|
+
const text = answer && typeof answer === 'object' && typeof answer.text === 'string'
|
|
1035
|
+
? answer.text
|
|
1036
|
+
: typeof answer === 'string' ? answer : '';
|
|
1037
|
+
const trimmed = text.trim();
|
|
1038
|
+
const answerText = trimmed || t('处理完成。');
|
|
1039
|
+
// The final answer keeps the channel's normal delivery path, so a
|
|
1040
|
+
// markdown answer renders rich (bold, code fences) exactly like
|
|
1041
|
+
// non-trace mode; trace lines above stay plain permanent messages.
|
|
1042
|
+
// Markdown goes to #sendRich in one shot: splitTelegramRichMarkdown
|
|
1043
|
+
// is fence-aware, so code blocks with inner blank lines stay intact
|
|
1044
|
+
// and no blank line is rewritten. A blank-line pre-split would break
|
|
1045
|
+
// both: unfinished fences fall back to plain, and rejoining with a
|
|
1046
|
+
// fixed separator collapses \n{3,} inside multi-line strings. Plain
|
|
1047
|
+
// answers use the whitespace-preserving regular-text splitter.
|
|
1048
|
+
const chunks = format === 'markdown'
|
|
1049
|
+
? [answerText]
|
|
1050
|
+
: splitTelegramRegularText(answerText);
|
|
1051
|
+
const remember = (ids) => {
|
|
1052
|
+
for (const id of ids ?? []) {
|
|
1053
|
+
if (!providerMessageIds.includes(id)) providerMessageIds.push(id);
|
|
1054
|
+
}
|
|
1055
|
+
};
|
|
1056
|
+
for (let index = 0; index < chunks.length; index += 1) {
|
|
1057
|
+
let result;
|
|
1058
|
+
try {
|
|
1059
|
+
result = await client.#sendRich(target, createTextDeliveryBlock(chunks[index], format));
|
|
1060
|
+
} catch (error) {
|
|
1061
|
+
const failure = telegramFailure(error);
|
|
1062
|
+
warnFailure('final answer', error);
|
|
1063
|
+
if (failure.outcome === 'unknown') {
|
|
1064
|
+
return deliveryResult('telegram-thinking', providerMessageIds, 'unknown', failure.reason);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
if (result?.deliveryOutcome === 'sent') {
|
|
1068
|
+
remember(result.providerMessageIds);
|
|
1069
|
+
continue;
|
|
1070
|
+
}
|
|
1071
|
+
if (result?.deliveryOutcome === 'unknown') {
|
|
1072
|
+
// 结果未知(超时等):可能已送达,重发会造成重复,保留 unknown 状态。
|
|
1073
|
+
remember(result.providerMessageIds);
|
|
1074
|
+
return deliveryResult('telegram-thinking', providerMessageIds, 'unknown', result.reason);
|
|
1075
|
+
}
|
|
1076
|
+
// 明确失败:该分片确认未送达。纯文本分片再走一次 plain 重发
|
|
1077
|
+
// (markdown 分片的 plain 回退已在 #sendRich 内尝试过),只重发
|
|
1078
|
+
// 尚未发送的尾部内容,已成功的分片不重复。
|
|
1079
|
+
remember(result?.providerMessageIds);
|
|
1080
|
+
if (format === 'markdown') {
|
|
1081
|
+
return deliveryResult('telegram-thinking', providerMessageIds, 'failed', result.reason);
|
|
1082
|
+
}
|
|
1083
|
+
warnFailure('final answer chunk', new Error('chunk definitively rejected'));
|
|
1084
|
+
try {
|
|
1085
|
+
// Regular-text chunks already retain the original whitespace.
|
|
1086
|
+
const fallback = await client.sendText(target, chunks.slice(index).join(''));
|
|
1087
|
+
remember(fallback.providerMessageIds);
|
|
1088
|
+
return deliveryResult('telegram-thinking', providerMessageIds);
|
|
1089
|
+
} catch (error) {
|
|
1090
|
+
const failure = telegramFailure(error);
|
|
1091
|
+
warnFailure('final answer fallback', error);
|
|
1092
|
+
return deliveryResult('telegram-thinking', providerMessageIds, failure.outcome, failure.reason);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
return deliveryResult('telegram-thinking', providerMessageIds);
|
|
1096
|
+
},
|
|
1097
|
+
cancel() {
|
|
1098
|
+
closed = true;
|
|
1099
|
+
},
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
export function createTelegramRuntimeStatus() {
|
|
1105
|
+
return {
|
|
1106
|
+
startedAt: null,
|
|
1107
|
+
ready: false,
|
|
1108
|
+
connectionState: 'idle',
|
|
1109
|
+
harnessReachable: false,
|
|
1110
|
+
lastCheckedAt: null,
|
|
1111
|
+
lastConnectedAt: null,
|
|
1112
|
+
lastError: null,
|
|
1113
|
+
...createTelegramBridgeStatus(),
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
export class TelegramRuntime {
|
|
1118
|
+
#config;
|
|
1119
|
+
#token;
|
|
1120
|
+
#harness;
|
|
1121
|
+
#state;
|
|
1122
|
+
#contextEnhancement;
|
|
1123
|
+
#accessPolicy;
|
|
1124
|
+
#logger;
|
|
1125
|
+
#diagnostics;
|
|
1126
|
+
#replyTimeoutMs;
|
|
1127
|
+
#createApi;
|
|
1128
|
+
#createHttpTransport;
|
|
1129
|
+
#commandCatalog;
|
|
1130
|
+
#status = createTelegramRuntimeStatus();
|
|
1131
|
+
#httpTransport = null;
|
|
1132
|
+
#api = null;
|
|
1133
|
+
#bridge = null;
|
|
1134
|
+
#abortController = null;
|
|
1135
|
+
#pollTask = null;
|
|
1136
|
+
#starting = null;
|
|
1137
|
+
// True only while #start() is between "started connecting" and "ready",
|
|
1138
|
+
// which is the one window a skipped refresh must be reconciled. A refresh on
|
|
1139
|
+
// a never-started or already-stopped runtime stays a no-op.
|
|
1140
|
+
#connecting = false;
|
|
1141
|
+
// True when a language switch arrived while the runtime was connecting, so a
|
|
1142
|
+
// refreshCommandMenu() had nothing to push. Reconciled once startup
|
|
1143
|
+
// completes, so the platform always ends up with the latest language.
|
|
1144
|
+
#menuDirty = false;
|
|
1145
|
+
|
|
1146
|
+
constructor({
|
|
1147
|
+
config,
|
|
1148
|
+
token,
|
|
1149
|
+
harness,
|
|
1150
|
+
state,
|
|
1151
|
+
contextEnhancement,
|
|
1152
|
+
accessPolicy,
|
|
1153
|
+
logger = console,
|
|
1154
|
+
replyTimeoutMs = 600_000,
|
|
1155
|
+
createApi = (options) => new TelegramApi(options),
|
|
1156
|
+
createHttpTransport = createTelegramHttpTransport,
|
|
1157
|
+
commandCatalog = SHARED_COMMAND_CATALOG,
|
|
1158
|
+
}) {
|
|
1159
|
+
if (!config || !token || !harness || !state) {
|
|
1160
|
+
throw new TypeError('TelegramRuntime requires config, token, Harness, and state');
|
|
1161
|
+
}
|
|
1162
|
+
this.#config = config;
|
|
1163
|
+
this.#token = token;
|
|
1164
|
+
this.#harness = harness;
|
|
1165
|
+
this.#state = state;
|
|
1166
|
+
this.#contextEnhancement = contextEnhancement;
|
|
1167
|
+
this.#accessPolicy = accessPolicy;
|
|
1168
|
+
this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'telegram', logger });
|
|
1169
|
+
this.#replyTimeoutMs = replyTimeoutMs;
|
|
1170
|
+
this.#createApi = createApi;
|
|
1171
|
+
this.#createHttpTransport = createHttpTransport;
|
|
1172
|
+
this.#commandCatalog = commandCatalog;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
get status() {
|
|
1176
|
+
return structuredClone(this.#status);
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
async sendConnectionTest(text) {
|
|
1180
|
+
if (!this.#status.ready || !this.#bridge) {
|
|
1181
|
+
const error = new Error('Telegram bot is not connected');
|
|
1182
|
+
error.code = 'test-target-unavailable';
|
|
1183
|
+
throw error;
|
|
1184
|
+
}
|
|
1185
|
+
return this.#bridge.sendConnectionTest(text);
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
async sendProactiveText(target, text, options = {}) {
|
|
1189
|
+
if (!this.#status.ready || !this.#bridge) {
|
|
1190
|
+
const error = new Error('Telegram bot is not connected');
|
|
1191
|
+
error.code = 'bot-not-connected';
|
|
1192
|
+
throw error;
|
|
1193
|
+
}
|
|
1194
|
+
const chatIdText = typeof target?.route?.chatId === 'string'
|
|
1195
|
+
? target.route.chatId.trim() : '';
|
|
1196
|
+
const chatId = Number(chatIdText);
|
|
1197
|
+
const messageThreadId = target?.route?.messageThreadId;
|
|
1198
|
+
if (!/^-?\d+$/.test(chatIdText) || !Number.isSafeInteger(chatId)
|
|
1199
|
+
|| (target?.kind !== 'chat' && target?.kind !== 'topic')
|
|
1200
|
+
|| (target.kind === 'topic' && (!Number.isSafeInteger(messageThreadId) || messageThreadId <= 0))
|
|
1201
|
+
|| (target.kind === 'chat' && messageThreadId !== undefined)) {
|
|
1202
|
+
const error = new TypeError('Invalid Telegram proactive delivery target');
|
|
1203
|
+
error.code = 'invalid-target';
|
|
1204
|
+
throw error;
|
|
1205
|
+
}
|
|
1206
|
+
return this.#bridge.sendProactiveText({
|
|
1207
|
+
chatId,
|
|
1208
|
+
...(target.kind === 'topic' ? { messageThreadId } : {}),
|
|
1209
|
+
}, text, options);
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
async start() {
|
|
1213
|
+
if (this.#status.ready && this.#pollTask) return this.status;
|
|
1214
|
+
if (this.#starting) return this.#starting;
|
|
1215
|
+
this.#starting = this.#start().finally(() => {
|
|
1216
|
+
this.#starting = null;
|
|
1217
|
+
});
|
|
1218
|
+
return this.#starting;
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
async #start() {
|
|
1222
|
+
await this.stop();
|
|
1223
|
+
this.#connecting = true;
|
|
1224
|
+
this.#status.startedAt = new Date().toISOString();
|
|
1225
|
+
this.#status.connectionState = 'connecting';
|
|
1226
|
+
this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
|
|
1227
|
+
await atConnectionStage('harness.check', () => this.#harness.ensureRunning());
|
|
1228
|
+
this.#status.harnessReachable = true;
|
|
1229
|
+
|
|
1230
|
+
const controller = new AbortController();
|
|
1231
|
+
this.#abortController = controller;
|
|
1232
|
+
try {
|
|
1233
|
+
const transport = this.#createHttpTransport();
|
|
1234
|
+
this.#httpTransport = transport;
|
|
1235
|
+
const api = this.#createApi({
|
|
1236
|
+
token: this.#token,
|
|
1237
|
+
fetchImpl: transport.fetchImpl,
|
|
1238
|
+
FormDataImpl: transport.FormDataImpl,
|
|
1239
|
+
});
|
|
1240
|
+
this.#api = api;
|
|
1241
|
+
const bot = await api.getMe({ signal: controller.signal });
|
|
1242
|
+
if (String(bot?.id ?? '') !== this.#config.platformId || bot?.is_bot !== true) {
|
|
1243
|
+
throw new Error('Telegram token identity does not match the saved bot');
|
|
1244
|
+
}
|
|
1245
|
+
const webhook = await api.getWebhookInfo({ signal: controller.signal });
|
|
1246
|
+
if (typeof webhook?.url === 'string' && webhook.url) {
|
|
1247
|
+
const error = new Error(t('该 Telegram 机器人已配置 Webhook,请先在原服务中移除 Webhook 后重试。'));
|
|
1248
|
+
error.code = 'webhook-configured';
|
|
1249
|
+
throw error;
|
|
1250
|
+
}
|
|
1251
|
+
try {
|
|
1252
|
+
await this.#sendCommandMenu(api, controller.signal);
|
|
1253
|
+
await api.setChatMenuButton({ menuButton: COMMANDS_MENU_BUTTON, signal: controller.signal });
|
|
1254
|
+
} catch (error) {
|
|
1255
|
+
this.#logger.warn?.(
|
|
1256
|
+
`[dsh-im:telegram] bot ${this.#config.botId} command menu setup failed:`,
|
|
1257
|
+
extractConnectionEvidence(error).details,
|
|
1258
|
+
);
|
|
1259
|
+
}
|
|
1260
|
+
const client = new TelegramBotClient({
|
|
1261
|
+
api,
|
|
1262
|
+
signal: controller.signal,
|
|
1263
|
+
logger: this.#logger,
|
|
1264
|
+
});
|
|
1265
|
+
this.#bridge = new TelegramHarnessBridge({
|
|
1266
|
+
bot: client,
|
|
1267
|
+
harness: this.#harness,
|
|
1268
|
+
state: this.#state,
|
|
1269
|
+
contextEnhancement: this.#contextEnhancement,
|
|
1270
|
+
accessPolicy: this.#accessPolicy,
|
|
1271
|
+
// Default ON; an explicit false in the bot config opts out.
|
|
1272
|
+
thinkingTraces: this.#config?.thinkingTraces !== false,
|
|
1273
|
+
status: this.#status,
|
|
1274
|
+
logger: this.#logger,
|
|
1275
|
+
replyTimeoutMs: this.#replyTimeoutMs,
|
|
1276
|
+
signal: controller.signal,
|
|
1277
|
+
});
|
|
1278
|
+
|
|
1279
|
+
let cursor = this.#state.cursor();
|
|
1280
|
+
if (cursor === null) {
|
|
1281
|
+
const latest = await api.getUpdates({ offset: -1, timeout: 0, signal: controller.signal });
|
|
1282
|
+
cursor = latest.length > 0 ? latest.at(-1).update_id + 1 : 0;
|
|
1283
|
+
await this.#state.setCursor(cursor);
|
|
1284
|
+
}
|
|
1285
|
+
const now = Date.now();
|
|
1286
|
+
this.#status.ready = true;
|
|
1287
|
+
this.#status.connectionState = 'connected';
|
|
1288
|
+
this.#status.lastCheckedAt = now;
|
|
1289
|
+
this.#status.lastConnectedAt = now;
|
|
1290
|
+
// A language switch that landed while we were connecting was skipped by
|
|
1291
|
+
// refreshCommandMenu(); re-send the menu now that the API is usable, so
|
|
1292
|
+
// the platform ends with the latest language instead of the one that was
|
|
1293
|
+
// current when #sendCommandMenu first ran.
|
|
1294
|
+
if (this.#menuDirty) {
|
|
1295
|
+
this.#menuDirty = false;
|
|
1296
|
+
try {
|
|
1297
|
+
await this.#sendCommandMenu(api, controller.signal);
|
|
1298
|
+
} catch (error) {
|
|
1299
|
+
this.#logger.warn?.(
|
|
1300
|
+
`[dsh-im:telegram] bot ${this.#config.botId} command menu catch-up failed:`,
|
|
1301
|
+
extractConnectionEvidence(error).details,
|
|
1302
|
+
);
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
this.#pollTask = this.#poll(cursor, controller.signal);
|
|
1306
|
+
this.#pollTask.catch((error) => {
|
|
1307
|
+
if (controller.signal.aborted) return;
|
|
1308
|
+
this.#status.ready = false;
|
|
1309
|
+
this.#status.connectionState = 'failed';
|
|
1310
|
+
this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#config?.botId, automatic: true }).publicError;
|
|
1311
|
+
this.#status.lastError = this.#status.error.message;
|
|
1312
|
+
|
|
1313
|
+
});
|
|
1314
|
+
return this.status;
|
|
1315
|
+
} catch (error) {
|
|
1316
|
+
this.#status.ready = false;
|
|
1317
|
+
this.#status.connectionState = 'failed';
|
|
1318
|
+
this.#status.error = this.#diagnostics.report(error, { operation: 'connection.restore', reuse: true, botId: this.#config?.botId, automatic: true }).publicError;
|
|
1319
|
+
this.#status.lastError = this.#status.error.message;
|
|
1320
|
+
await this.stop();
|
|
1321
|
+
throw error;
|
|
1322
|
+
} finally {
|
|
1323
|
+
// Whether the bot is now ready or the attempt failed, the connecting
|
|
1324
|
+
// window is over. A failed attempt also drops any unreconciled dirty
|
|
1325
|
+
// flag: a later retry re-sends the menu from scratch in the current
|
|
1326
|
+
// language anyway.
|
|
1327
|
+
this.#connecting = false;
|
|
1328
|
+
this.#menuDirty = false;
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
// Both operations use the existing default scope and language. Sending the
|
|
1333
|
+
// full list replaces old entries; an empty catalog clears that list.
|
|
1334
|
+
async #sendCommandMenu(api, signal) {
|
|
1335
|
+
const commands = telegramCommandMenu(this.#commandCatalog);
|
|
1336
|
+
if (commands.length > 0) await api.setMyCommands({ commands, signal });
|
|
1337
|
+
else await api.deleteMyCommands({ signal });
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
/**
|
|
1341
|
+
* Re-send the command menu in the current host message language.
|
|
1342
|
+
*
|
|
1343
|
+
* The menu Telegram shows is registered once per connection, so a language
|
|
1344
|
+
* change would otherwise stay invisible until the bot reconnected. This
|
|
1345
|
+
* replaces the text only: the chat menu button is owned by connect.
|
|
1346
|
+
* @returns whether a connected bot accepted the refreshed menu.
|
|
1347
|
+
*/
|
|
1348
|
+
async refreshCommandMenu() {
|
|
1349
|
+
const api = this.#api;
|
|
1350
|
+
const signal = this.#abortController?.signal;
|
|
1351
|
+
if (!this.#status.ready || !api || !signal || signal.aborted) {
|
|
1352
|
+
// A refresh during an in-progress connection must not be lost: mark the
|
|
1353
|
+
// menu dirty so #start() reconciles it the moment the bot is ready. A
|
|
1354
|
+
// never-started or stopped runtime stays a no-op, as before.
|
|
1355
|
+
if (this.#connecting) this.#menuDirty = true;
|
|
1356
|
+
return false;
|
|
1357
|
+
}
|
|
1358
|
+
try {
|
|
1359
|
+
await this.#sendCommandMenu(api, signal);
|
|
1360
|
+
return true;
|
|
1361
|
+
} catch (error) {
|
|
1362
|
+
this.#logger.warn?.(
|
|
1363
|
+
`[dsh-im:telegram] bot ${this.#config.botId} command menu refresh failed:`,
|
|
1364
|
+
extractConnectionEvidence(error).details,
|
|
1365
|
+
);
|
|
1366
|
+
return false;
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
async #loadReplyContent(reference, { signal } = {}) {
|
|
1371
|
+
const key = typeof reference?.conversationKey === 'string'
|
|
1372
|
+
? reference.conversationKey.trim() : '';
|
|
1373
|
+
const quotedAt = Number(reference?.createdAt);
|
|
1374
|
+
if (!key || !Number.isFinite(quotedAt)) {
|
|
1375
|
+
return { unavailableReason: 'not-delivered' };
|
|
1376
|
+
}
|
|
1377
|
+
const sessionId = this.#state.sessionFor(key);
|
|
1378
|
+
const session = typeof sessionId === 'string' && sessionId
|
|
1379
|
+
? this.#harness.workspaceSession?.(sessionId, key)
|
|
1380
|
+
: null;
|
|
1381
|
+
const text = await recoverAssistantTextByTimestamp({ session, quotedAt, signal });
|
|
1382
|
+
return text ? { content: text } : { unavailableReason: 'not-delivered' };
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
async #poll(initialCursor, signal) {
|
|
1386
|
+
let cursor = initialCursor;
|
|
1387
|
+
while (!signal.aborted) {
|
|
1388
|
+
const updates = await this.#api.getUpdates({ offset: cursor, timeout: 25, signal });
|
|
1389
|
+
this.#status.lastCheckedAt = Date.now();
|
|
1390
|
+
if (signal.aborted) return;
|
|
1391
|
+
// All updates have arrived together; cursor persistence must not move the
|
|
1392
|
+
// settings boundary for the later messages in this received batch.
|
|
1393
|
+
const received = updates.map((update) => {
|
|
1394
|
+
const chatType = update?.message?.chat?.type
|
|
1395
|
+
?? update?.callback_query?.message?.chat?.type;
|
|
1396
|
+
return {
|
|
1397
|
+
update,
|
|
1398
|
+
contextSnapshot: captureContextEnhancement(this.#contextEnhancement,
|
|
1399
|
+
chatType === 'private' ? 'direct'
|
|
1400
|
+
: chatType === 'group' || chatType === 'supergroup' ? 'group' : null),
|
|
1401
|
+
};
|
|
1402
|
+
});
|
|
1403
|
+
for (const { update, contextSnapshot } of received) {
|
|
1404
|
+
if (signal.aborted) return;
|
|
1405
|
+
const callback = normalizeTelegramCallback(update, {
|
|
1406
|
+
botId: this.#config.platformId,
|
|
1407
|
+
});
|
|
1408
|
+
if (callback) {
|
|
1409
|
+
if (typeof this.#bridge.acceptCallback === 'function') {
|
|
1410
|
+
void this.#bridge.acceptCallback(callback, { contextSnapshot }).catch((error) => {
|
|
1411
|
+
if (signal.aborted) return;
|
|
1412
|
+
this.#logger.error?.(
|
|
1413
|
+
`[dsh-im:telegram] bot ${this.#config.botId} callback handling failed:`,
|
|
1414
|
+
extractConnectionEvidence(error).details,
|
|
1415
|
+
);
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
cursor = update.update_id + 1;
|
|
1419
|
+
await this.#state.setCursor(cursor);
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
const message = normalizeTelegramUpdate(update, {
|
|
1423
|
+
botId: this.#config.platformId,
|
|
1424
|
+
username: this.#config.username,
|
|
1425
|
+
loadFile: (fileId, options) => this.#api.downloadFile({ fileId, ...options }),
|
|
1426
|
+
loadFileStream: (fileId, options) => this.#api.downloadFileStream({ fileId, ...options }),
|
|
1427
|
+
loadReplyContent: (reference, options) => this.#loadReplyContent(reference, options),
|
|
1428
|
+
});
|
|
1429
|
+
if (message) {
|
|
1430
|
+
void this.#bridge.accept(message, { contextSnapshot }).catch((error) => {
|
|
1431
|
+
if (signal.aborted) return;
|
|
1432
|
+
this.#logger.error?.(
|
|
1433
|
+
`[dsh-im:telegram] bot ${this.#config.botId} message handling failed:`,
|
|
1434
|
+
extractConnectionEvidence(error).details,
|
|
1435
|
+
);
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
cursor = update.update_id + 1;
|
|
1439
|
+
await this.#state.setCursor(cursor);
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
async stop() {
|
|
1445
|
+
const pollTask = this.#pollTask;
|
|
1446
|
+
const bridge = this.#bridge;
|
|
1447
|
+
const httpTransport = this.#httpTransport;
|
|
1448
|
+
this.#abortController?.abort();
|
|
1449
|
+
this.#abortController = null;
|
|
1450
|
+
this.#pollTask = null;
|
|
1451
|
+
this.#httpTransport = null;
|
|
1452
|
+
this.#api = null;
|
|
1453
|
+
this.#bridge = null;
|
|
1454
|
+
await Promise.race([
|
|
1455
|
+
pollTask?.catch(() => undefined) ?? Promise.resolve(),
|
|
1456
|
+
new Promise((resolve) => setTimeout(resolve, 2_000)),
|
|
1457
|
+
]);
|
|
1458
|
+
await Promise.race([
|
|
1459
|
+
bridge?.waitForIdle() ?? Promise.resolve(),
|
|
1460
|
+
new Promise((resolve) => setTimeout(resolve, 2_000)),
|
|
1461
|
+
]);
|
|
1462
|
+
try {
|
|
1463
|
+
await httpTransport?.destroy();
|
|
1464
|
+
} catch {
|
|
1465
|
+
this.#logger.warn?.('[dsh-im:telegram] Telegram HTTP transport cleanup failed');
|
|
1466
|
+
}
|
|
1467
|
+
this.#status.ready = false;
|
|
1468
|
+
this.#status.connectionState = 'idle';
|
|
1469
|
+
return this.status;
|
|
1470
|
+
}
|
|
1471
|
+
}
|