@botharness/im-provider 4.32.0-botharness.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/PROVENANCE.json +25 -0
- package/README.en.md +445 -0
- package/README.md +448 -0
- package/THIRD_PARTY_NOTICES.md +93 -0
- package/assets/dingtalk-menu-template.json +6 -0
- package/assets/logo-dsh-im-chinese-readme-3x2.png +0 -0
- package/assets/logo-dsh-im-connecting-readme-3x2.png +0 -0
- package/assets/logo-dsh-im-connecting-square-v4.png +0 -0
- package/assets/logo-icon.png +0 -0
- package/assets/logo-plugin-message-link-gradient.webp +0 -0
- package/assets/logo-plugin-phone.png +0 -0
- package/assets/logo.png +0 -0
- package/assets/logo_cn.png +0 -0
- package/assets/screenshot-menu-card.png +0 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +20330 -0
- package/lib/index.js +602 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +5 -0
- package/package.json +181 -0
- package/plugin-src/client/access-policy-settings.js +362 -0
- package/plugin-src/client/agent-preset.js +119 -0
- package/plugin-src/client/bot-alias.js +169 -0
- package/plugin-src/client/build.mjs +38 -0
- package/plugin-src/client/channel-card-meta.js +132 -0
- package/plugin-src/client/channel-logos.js +190 -0
- package/plugin-src/client/channels/dingtalk/api.js +267 -0
- package/plugin-src/client/channels/dingtalk/index.js +954 -0
- package/plugin-src/client/channels/dingtalk/styles.js +136 -0
- package/plugin-src/client/channels/discord/api.js +11 -0
- package/plugin-src/client/channels/discord/index.js +25 -0
- package/plugin-src/client/channels/discord/styles.js +19 -0
- package/plugin-src/client/channels/email/api.js +52 -0
- package/plugin-src/client/channels/email/index.js +728 -0
- package/plugin-src/client/channels/email/styles.js +51 -0
- package/plugin-src/client/channels/feishu/api.js +405 -0
- package/plugin-src/client/channels/feishu/group-settings.js +581 -0
- package/plugin-src/client/channels/feishu/index.js +1583 -0
- package/plugin-src/client/channels/feishu/slash-panel-settings.js +322 -0
- package/plugin-src/client/channels/feishu/styles.js +573 -0
- package/plugin-src/client/channels/feishu/voice-editor.js +115 -0
- package/plugin-src/client/channels/feishu/voice-settings.js +71 -0
- package/plugin-src/client/channels/imessage/api.js +12 -0
- package/plugin-src/client/channels/imessage/index.js +46 -0
- package/plugin-src/client/channels/imessage/styles.js +19 -0
- package/plugin-src/client/channels/matrix/api.js +11 -0
- package/plugin-src/client/channels/matrix/index.js +151 -0
- package/plugin-src/client/channels/matrix/styles.js +36 -0
- package/plugin-src/client/channels/office/api.js +46 -0
- package/plugin-src/client/channels/office/index.js +153 -0
- package/plugin-src/client/channels/office/styles.js +50 -0
- package/plugin-src/client/channels/qq/api.js +171 -0
- package/plugin-src/client/channels/qq/index.js +593 -0
- package/plugin-src/client/channels/qq/styles.js +19 -0
- package/plugin-src/client/channels/shared/collapsible-account.js +103 -0
- package/plugin-src/client/channels/shared/token-api.js +124 -0
- package/plugin-src/client/channels/shared/token-channel.js +495 -0
- package/plugin-src/client/channels/slack/api.js +11 -0
- package/plugin-src/client/channels/slack/index.js +131 -0
- package/plugin-src/client/channels/slack/styles.js +34 -0
- package/plugin-src/client/channels/telegram/api.js +11 -0
- package/plugin-src/client/channels/telegram/index.js +28 -0
- package/plugin-src/client/channels/telegram/styles.js +31 -0
- package/plugin-src/client/channels/telegram/thinking-traces.js +25 -0
- package/plugin-src/client/channels/wecom/api.js +160 -0
- package/plugin-src/client/channels/wecom/index.js +625 -0
- package/plugin-src/client/channels/wecom/styles.js +19 -0
- package/plugin-src/client/channels/wecom-app/api.js +132 -0
- package/plugin-src/client/channels/wecom-app/index.js +634 -0
- package/plugin-src/client/channels/wecom-app/styles.js +25 -0
- package/plugin-src/client/channels/weixin/api.js +211 -0
- package/plugin-src/client/channels/weixin/connection-error.js +1 -0
- package/plugin-src/client/channels/weixin/index.js +801 -0
- package/plugin-src/client/channels/weixin/styles.js +115 -0
- package/plugin-src/client/channels/whatsapp/api.js +152 -0
- package/plugin-src/client/channels/whatsapp/index.js +609 -0
- package/plugin-src/client/channels/whatsapp/styles.js +19 -0
- package/plugin-src/client/connection-error.js +87 -0
- package/plugin-src/client/context-enhancement.js +415 -0
- package/plugin-src/client/credential-binding.js +118 -0
- package/plugin-src/client/delivery-settings.js +905 -0
- package/plugin-src/client/global-settings.js +433 -0
- package/plugin-src/client/i18n.js +1314 -0
- package/plugin-src/client/index.js +624 -0
- package/plugin-src/client/interface-language.js +89 -0
- package/plugin-src/client/last-message-error.js +18 -0
- package/plugin-src/client/lifecycle.js +86 -0
- package/plugin-src/client/loopback-recovery.js +75 -0
- package/plugin-src/client/model-setting.js +172 -0
- package/plugin-src/client/panel-error-boundary.js +21 -0
- package/plugin-src/client/plugin-page.js +51 -0
- package/plugin-src/client/session-channel-logos.js +243 -0
- package/plugin-src/client/styles.js +770 -0
- package/plugin-src/client/update-panel.js +14 -0
- package/plugin-src/client/workspace-directory-picker.js +280 -0
- package/plugin-src/client/workspace-editor.js +69 -0
- package/plugin-src/client/workspace-snapshot-fence.js +28 -0
- package/plugin-src/host/build.mjs +52 -0
- package/plugin-src/host/channels/dingtalk/connection-supervisor.mjs +130 -0
- package/plugin-src/host/channels/dingtalk/index.mjs +35 -0
- package/plugin-src/host/channels/dingtalk/production.mjs +193 -0
- package/plugin-src/host/channels/dingtalk/rpc.mjs +359 -0
- package/plugin-src/host/channels/discord/index.mjs +33 -0
- package/plugin-src/host/channels/discord/production.mjs +17 -0
- package/plugin-src/host/channels/discord/rpc.mjs +21 -0
- package/plugin-src/host/channels/email/availability.mjs +60 -0
- package/plugin-src/host/channels/email/index.mjs +36 -0
- package/plugin-src/host/channels/email/production.mjs +58 -0
- package/plugin-src/host/channels/email/rpc.mjs +163 -0
- package/plugin-src/host/channels/feishu/connection-supervisor.mjs +167 -0
- package/plugin-src/host/channels/feishu/controller.mjs +172 -0
- package/plugin-src/host/channels/feishu/credential-store.mjs +84 -0
- package/plugin-src/host/channels/feishu/index.mjs +69 -0
- package/plugin-src/host/channels/feishu/production.mjs +318 -0
- package/plugin-src/host/channels/feishu/rpc.mjs +863 -0
- package/plugin-src/host/channels/imessage/index.mjs +21 -0
- package/plugin-src/host/channels/imessage/production.mjs +13 -0
- package/plugin-src/host/channels/imessage/rpc.mjs +78 -0
- package/plugin-src/host/channels/matrix/index.mjs +31 -0
- package/plugin-src/host/channels/matrix/production.mjs +241 -0
- package/plugin-src/host/channels/matrix/rpc.mjs +228 -0
- package/plugin-src/host/channels/office/index.mjs +14 -0
- package/plugin-src/host/channels/office/production.mjs +45 -0
- package/plugin-src/host/channels/office/rpc.mjs +51 -0
- package/plugin-src/host/channels/qq/connection-supervisor.mjs +124 -0
- package/plugin-src/host/channels/qq/index.mjs +28 -0
- package/plugin-src/host/channels/qq/production.mjs +181 -0
- package/plugin-src/host/channels/qq/rpc.mjs +250 -0
- package/plugin-src/host/channels/shared/access-policy-production.mjs +137 -0
- package/plugin-src/host/channels/shared/access-policy-rpc.mjs +17 -0
- package/plugin-src/host/channels/shared/agent-preset-rpc.mjs +25 -0
- package/plugin-src/host/channels/shared/bot-alias-rpc.mjs +15 -0
- package/plugin-src/host/channels/shared/connection-supervisor.mjs +133 -0
- package/plugin-src/host/channels/shared/context-enhancement-rpc.mjs +17 -0
- package/plugin-src/host/channels/shared/model-setting-rpc.mjs +18 -0
- package/plugin-src/host/channels/shared/production.mjs +237 -0
- package/plugin-src/host/channels/shared/rpc.mjs +226 -0
- package/plugin-src/host/channels/shared/startup-error.mjs +55 -0
- package/plugin-src/host/channels/shared/startup.mjs +76 -0
- package/plugin-src/host/channels/shared/thinking-traces-rpc.mjs +11 -0
- package/plugin-src/host/channels/shared/workspace-rpc.mjs +31 -0
- package/plugin-src/host/channels/slack/index.mjs +31 -0
- package/plugin-src/host/channels/slack/production.mjs +176 -0
- package/plugin-src/host/channels/slack/rpc.mjs +221 -0
- package/plugin-src/host/channels/telegram/index.mjs +33 -0
- package/plugin-src/host/channels/telegram/production.mjs +19 -0
- package/plugin-src/host/channels/telegram/rpc.mjs +22 -0
- package/plugin-src/host/channels/wecom/connection-supervisor.mjs +124 -0
- package/plugin-src/host/channels/wecom/index.mjs +34 -0
- package/plugin-src/host/channels/wecom/production.mjs +187 -0
- package/plugin-src/host/channels/wecom/rpc.mjs +255 -0
- package/plugin-src/host/channels/wecom-app/index.mjs +33 -0
- package/plugin-src/host/channels/wecom-app/production.mjs +221 -0
- package/plugin-src/host/channels/wecom-app/rpc.mjs +235 -0
- package/plugin-src/host/channels/weixin/connection-supervisor.mjs +139 -0
- package/plugin-src/host/channels/weixin/index.mjs +44 -0
- package/plugin-src/host/channels/weixin/production.mjs +257 -0
- package/plugin-src/host/channels/weixin/rpc.mjs +285 -0
- package/plugin-src/host/channels/whatsapp/index.mjs +33 -0
- package/plugin-src/host/channels/whatsapp/production.mjs +198 -0
- package/plugin-src/host/channels/whatsapp/rpc.mjs +242 -0
- package/plugin-src/host/delivery-adapter.mjs +388 -0
- package/plugin-src/host/delivery-http.mjs +132 -0
- package/plugin-src/host/delivery-rpc.mjs +173 -0
- package/plugin-src/host/delivery-service.mjs +552 -0
- package/plugin-src/host/delivery-suggestions.mjs +198 -0
- package/plugin-src/host/harness-command-executor.mjs +48 -0
- package/plugin-src/host/harness-connection.mjs +20 -0
- package/plugin-src/host/harness-session-coordinator.mjs +183 -0
- package/plugin-src/host/host-language-rpc.mjs +71 -0
- package/plugin-src/host/host-language.mjs +157 -0
- package/plugin-src/host/image-input-rpc.mjs +24 -0
- package/plugin-src/host/inbound-ttl-rpc.mjs +86 -0
- package/plugin-src/host/inbound-ttl-runtime.mjs +85 -0
- package/plugin-src/host/inbound-ttl-service.mjs +179 -0
- package/plugin-src/host/index.mjs +224 -0
- package/plugin-src/host/injected-context.mjs +104 -0
- package/plugin-src/host/lark-sdk-handshake-patch.mjs +181 -0
- package/plugin-src/host/modern-harness-api.mjs +738 -0
- package/plugin-src/host/rpc-authority.mjs +12 -0
- package/plugin-src/host/session-sync-coordinator.mjs +233 -0
- package/plugin-src/host/session-title-prefix.mjs +122 -0
- package/plugin-src/host/update-policy.mjs +31 -0
- package/plugin-src/host/update-rpc.mjs +16 -0
- package/plugin-src/host/update-runtime.mjs +339 -0
- package/plugin-src/host/update-service.mjs +392 -0
- package/plugin-src/management-rpc.mjs +87 -0
- package/src/channels/dingtalk/config-store.mjs +284 -0
- package/src/channels/dingtalk/connection-error.mjs +292 -0
- package/src/channels/dingtalk/device-auth.mjs +240 -0
- package/src/channels/dingtalk/dingtalk-api.mjs +1140 -0
- package/src/channels/dingtalk/dingtalk-bridge.mjs +1889 -0
- package/src/channels/dingtalk/dingtalk-card-stream.mjs +242 -0
- package/src/channels/dingtalk/dingtalk-controller.mjs +852 -0
- package/src/channels/dingtalk/dingtalk-menu.mjs +95 -0
- package/src/channels/dingtalk/dingtalk-runtime.mjs +482 -0
- package/src/channels/dingtalk/harness-client.mjs +19 -0
- package/src/channels/dingtalk/state-store.mjs +325 -0
- package/src/channels/discord/config-store.mjs +25 -0
- package/src/channels/discord/discord-api.mjs +347 -0
- package/src/channels/discord/discord-bridge.mjs +16 -0
- package/src/channels/discord/discord-controller.mjs +16 -0
- package/src/channels/discord/discord-runtime.mjs +974 -0
- package/src/channels/discord/harness-client.mjs +11 -0
- package/src/channels/discord/state-store.mjs +3 -0
- package/src/channels/email/config-store.mjs +194 -0
- package/src/channels/email/email-api.mjs +20 -0
- package/src/channels/email/email-bridge.mjs +17 -0
- package/src/channels/email/email-controller.mjs +824 -0
- package/src/channels/email/email-runtime.mjs +699 -0
- package/src/channels/email/harness-client.mjs +7 -0
- package/src/channels/email/mail-format.mjs +91 -0
- package/src/channels/email/state-store.mjs +176 -0
- package/src/channels/email/transport.mjs +64 -0
- package/src/channels/email/transports/agent-mail.mjs +604 -0
- package/src/channels/email/transports/agently-cli.mjs +288 -0
- package/src/channels/email/transports/imap-smtp.mjs +165 -0
- package/src/channels/feishu/bridge.mjs +6286 -0
- package/src/channels/feishu/config.mjs +71 -0
- package/src/channels/feishu/external-consumer.mjs +77 -0
- package/src/channels/feishu/external-files.mjs +111 -0
- package/src/channels/feishu/feishu-app.mjs +54 -0
- package/src/channels/feishu/feishu-cards.mjs +1285 -0
- package/src/channels/feishu/feishu-channel.mjs +651 -0
- package/src/channels/feishu/feishu-runtime.mjs +950 -0
- package/src/channels/feishu/group-message-permission-manager.mjs +72 -0
- package/src/channels/feishu/group-response-mode.mjs +15 -0
- package/src/channels/feishu/harness-client.mjs +19 -0
- package/src/channels/feishu/history-reader.mjs +77 -0
- package/src/channels/feishu/live-cot.mjs +260 -0
- package/src/channels/feishu/message-utils.mjs +613 -0
- package/src/channels/feishu/multi-bot-controller.mjs +1588 -0
- package/src/channels/feishu/nearby-history.mjs +72 -0
- package/src/channels/feishu/plugin-config-store.mjs +216 -0
- package/src/channels/feishu/plugin-controller.mjs +254 -0
- package/src/channels/feishu/registration-manager.mjs +349 -0
- package/src/channels/feishu/repair-manager.mjs +138 -0
- package/src/channels/feishu/reply-context.mjs +22 -0
- package/src/channels/feishu/slash-command-panel.mjs +155 -0
- package/src/channels/feishu/slash-command-registry.mjs +495 -0
- package/src/channels/feishu/state-store.mjs +214 -0
- package/src/channels/feishu/step-push-mode.mjs +25 -0
- package/src/channels/feishu/voice-config.mjs +34 -0
- package/src/channels/feishu/voice.mjs +134 -0
- package/src/channels/imessage/config-store.mjs +24 -0
- package/src/channels/imessage/controller.mjs +37 -0
- package/src/channels/imessage/harness-client.mjs +7 -0
- package/src/channels/imessage/imessage-api.mjs +194 -0
- package/src/channels/imessage/imessage-bridge.mjs +16 -0
- package/src/channels/imessage/runtime.mjs +102 -0
- package/src/channels/imessage/state-store.mjs +3 -0
- package/src/channels/matrix/matrix-api.mjs +696 -0
- package/src/channels/matrix/matrix-bridge.mjs +20 -0
- package/src/channels/matrix/matrix-config-store.mjs +368 -0
- package/src/channels/matrix/matrix-controller.mjs +404 -0
- package/src/channels/matrix/matrix-crypto-store.mjs +279 -0
- package/src/channels/matrix/matrix-crypto.mjs +1014 -0
- package/src/channels/matrix/matrix-harness-client.mjs +11 -0
- package/src/channels/matrix/matrix-normalize.mjs +357 -0
- package/src/channels/matrix/matrix-rich-text.mjs +313 -0
- package/src/channels/matrix/matrix-room-history.mjs +316 -0
- package/src/channels/matrix/matrix-runtime.mjs +1014 -0
- package/src/channels/office/config-store.mjs +107 -0
- package/src/channels/office/office-controller.mjs +178 -0
- package/src/channels/office/office-job-executor.mjs +391 -0
- package/src/channels/office/office-runtime.mjs +175 -0
- package/src/channels/office/office-transport.mjs +171 -0
- package/src/channels/office/protocol.mjs +43 -0
- package/src/channels/qq/config-store.mjs +173 -0
- package/src/channels/qq/harness-client.mjs +11 -0
- package/src/channels/qq/markdown-reply.mjs +446 -0
- package/src/channels/qq/qq-bridge.mjs +1507 -0
- package/src/channels/qq/qq-controller.mjs +514 -0
- package/src/channels/qq/qq-menu.mjs +208 -0
- package/src/channels/qq/qq-runtime.mjs +303 -0
- package/src/channels/qq/qr-auth.mjs +24 -0
- package/src/channels/qq/state-error.mjs +17 -0
- package/src/channels/qq/state-store.mjs +143 -0
- package/src/channels/shared/access-policy.mjs +210 -0
- package/src/channels/shared/agent-preset.mjs +76 -0
- package/src/channels/shared/batch-input.mjs +229 -0
- package/src/channels/shared/bot-alias.mjs +29 -0
- package/src/channels/shared/bot-workspace-store.mjs +2383 -0
- package/src/channels/shared/command-catalog.mjs +107 -0
- package/src/channels/shared/command-permission.mjs +32 -0
- package/src/channels/shared/compact-command.mjs +109 -0
- package/src/channels/shared/config-read-error.mjs +24 -0
- package/src/channels/shared/connection-error.mjs +191 -0
- package/src/channels/shared/connection-test.mjs +58 -0
- package/src/channels/shared/context-enhancement.mjs +372 -0
- package/src/channels/shared/control-command.mjs +111 -0
- package/src/channels/shared/conversation-state-store.mjs +165 -0
- package/src/channels/shared/default-workspace.mjs +31 -0
- package/src/channels/shared/deferred-delivery-coordinator.mjs +241 -0
- package/src/channels/shared/deferred-delivery.mjs +161 -0
- package/src/channels/shared/deferred-state.mjs +53 -0
- package/src/channels/shared/diagnostic-details.mjs +95 -0
- package/src/channels/shared/editable-message-stream.mjs +100 -0
- package/src/channels/shared/exclusive-inbound-consumers.mjs +71 -0
- package/src/channels/shared/file-download.mjs +64 -0
- package/src/channels/shared/harness-approval.mjs +508 -0
- package/src/channels/shared/harness-client.mjs +2143 -0
- package/src/channels/shared/harness-mux.mjs +123 -0
- package/src/channels/shared/harness-question.mjs +95 -0
- package/src/channels/shared/harness-session-binding.mjs +119 -0
- package/src/channels/shared/history-command.mjs +193 -0
- package/src/channels/shared/i18n-en/diagnostics.mjs +55 -0
- package/src/channels/shared/i18n-en/dingtalk.mjs +81 -0
- package/src/channels/shared/i18n-en/discord.mjs +10 -0
- package/src/channels/shared/i18n-en/email.mjs +25 -0
- package/src/channels/shared/i18n-en/feishu.mjs +404 -0
- package/src/channels/shared/i18n-en/image-input.mjs +18 -0
- package/src/channels/shared/i18n-en/matrix.mjs +85 -0
- package/src/channels/shared/i18n-en/office.mjs +23 -0
- package/src/channels/shared/i18n-en/qq.mjs +96 -0
- package/src/channels/shared/i18n-en/shared-a.mjs +241 -0
- package/src/channels/shared/i18n-en/shared-b.mjs +263 -0
- package/src/channels/shared/i18n-en/shared-c.mjs +203 -0
- package/src/channels/shared/i18n-en/slack.mjs +27 -0
- package/src/channels/shared/i18n-en/telegram.mjs +27 -0
- package/src/channels/shared/i18n-en/wecom-app.mjs +33 -0
- package/src/channels/shared/i18n-en/wecom.mjs +62 -0
- package/src/channels/shared/i18n-en/weixin.mjs +88 -0
- package/src/channels/shared/i18n-en/whatsapp.mjs +17 -0
- package/src/channels/shared/i18n-en.mjs +45 -0
- package/src/channels/shared/i18n.mjs +78 -0
- package/src/channels/shared/im-source-guidance.mjs +65 -0
- package/src/channels/shared/image-input-policy.mjs +35 -0
- package/src/channels/shared/image-input-settings-store.mjs +60 -0
- package/src/channels/shared/image-input.mjs +124 -0
- package/src/channels/shared/image-prompt.mjs +360 -0
- package/src/channels/shared/inbound-access.mjs +43 -0
- package/src/channels/shared/inbound-file.mjs +323 -0
- package/src/channels/shared/inbound-ttl-store.mjs +110 -0
- package/src/channels/shared/inbound-ttl.mjs +22 -0
- package/src/channels/shared/injected-context.mjs +362 -0
- package/src/channels/shared/interface-language-store.mjs +127 -0
- package/src/channels/shared/interface-language.mjs +51 -0
- package/src/channels/shared/message-failure.mjs +257 -0
- package/src/channels/shared/model-command.mjs +741 -0
- package/src/channels/shared/model-setting.mjs +145 -0
- package/src/channels/shared/preset-command.mjs +308 -0
- package/src/channels/shared/semantic/artifact-delivery.mjs +177 -0
- package/src/channels/shared/semantic/artifact.mjs +750 -0
- package/src/channels/shared/semantic/delivery.mjs +193 -0
- package/src/channels/shared/semantic/reply-reference.mjs +148 -0
- package/src/channels/shared/session-binding-lock.mjs +40 -0
- package/src/channels/shared/session-channel-labels.mjs +28 -0
- package/src/channels/shared/session-reply-recovery.mjs +104 -0
- package/src/channels/shared/session-sync-registry.mjs +22 -0
- package/src/channels/shared/session-title.mjs +74 -0
- package/src/channels/shared/status-reaction.mjs +107 -0
- package/src/channels/shared/text-harness-bridge.mjs +1623 -0
- package/src/channels/shared/token-bot-controller.mjs +417 -0
- package/src/channels/shared/token-config-store.mjs +208 -0
- package/src/channels/shared/workspace-command.mjs +532 -0
- package/src/channels/shared/workspace-session.mjs +196 -0
- package/src/channels/slack/config-store.mjs +177 -0
- package/src/channels/slack/external-consumer.mjs +80 -0
- package/src/channels/slack/external-files.mjs +90 -0
- package/src/channels/slack/harness-client.mjs +11 -0
- package/src/channels/slack/history-reader.mjs +203 -0
- package/src/channels/slack/manifest.mjs +37 -0
- package/src/channels/slack/slack-api.mjs +636 -0
- package/src/channels/slack/slack-bridge.mjs +20 -0
- package/src/channels/slack/slack-controller.mjs +468 -0
- package/src/channels/slack/slack-runtime.mjs +879 -0
- package/src/channels/slack/state-store.mjs +3 -0
- package/src/channels/telegram/config-store.mjs +89 -0
- package/src/channels/telegram/harness-client.mjs +11 -0
- package/src/channels/telegram/state-store.mjs +3 -0
- package/src/channels/telegram/telegram-api.mjs +486 -0
- package/src/channels/telegram/telegram-bridge.mjs +81 -0
- package/src/channels/telegram/telegram-controller.mjs +52 -0
- package/src/channels/telegram/telegram-http.mjs +21 -0
- package/src/channels/telegram/telegram-rich-message.mjs +149 -0
- package/src/channels/telegram/telegram-runtime.mjs +1471 -0
- package/src/channels/wecom/config-store.mjs +172 -0
- package/src/channels/wecom/harness-client.mjs +11 -0
- package/src/channels/wecom/qr-auth.mjs +95 -0
- package/src/channels/wecom/send-error.mjs +31 -0
- package/src/channels/wecom/state-store.mjs +107 -0
- package/src/channels/wecom/wecom-bridge.mjs +1833 -0
- package/src/channels/wecom/wecom-cards.mjs +101 -0
- package/src/channels/wecom/wecom-controller.mjs +530 -0
- package/src/channels/wecom/wecom-runtime.mjs +269 -0
- package/src/channels/wecom-app/callback-server.mjs +471 -0
- package/src/channels/wecom-app/config-store.mjs +242 -0
- package/src/channels/wecom-app/harness-client.mjs +11 -0
- package/src/channels/wecom-app/state-store.mjs +107 -0
- package/src/channels/wecom-app/wecom-app-api.mjs +432 -0
- package/src/channels/wecom-app/wecom-app-bridge.mjs +1072 -0
- package/src/channels/wecom-app/wecom-app-controller.mjs +453 -0
- package/src/channels/wecom-app/wecom-app-runtime.mjs +222 -0
- package/src/channels/weixin/config-store.mjs +192 -0
- package/src/channels/weixin/connection-error.en.mjs +137 -0
- package/src/channels/weixin/connection-error.mjs +153 -0
- package/src/channels/weixin/diagnostic-details.mjs +1 -0
- package/src/channels/weixin/harness-client.mjs +19 -0
- package/src/channels/weixin/state-store.mjs +291 -0
- package/src/channels/weixin/weixin-api.mjs +949 -0
- package/src/channels/weixin/weixin-bridge.mjs +1537 -0
- package/src/channels/weixin/weixin-controller.mjs +669 -0
- package/src/channels/weixin/weixin-runtime.mjs +416 -0
- package/src/channels/whatsapp/config-store.mjs +210 -0
- package/src/channels/whatsapp/harness-client.mjs +11 -0
- package/src/channels/whatsapp/state-store.mjs +3 -0
- package/src/channels/whatsapp/whatsapp-bridge.mjs +18 -0
- package/src/channels/whatsapp/whatsapp-controller.mjs +470 -0
- package/src/channels/whatsapp/whatsapp-runtime.mjs +917 -0
- package/src/channels/whatsapp/whatsapp-web-session.mjs +214 -0
|
@@ -0,0 +1,2383 @@
|
|
|
1
|
+
import { t } from './i18n.mjs';
|
|
2
|
+
import { atConnectionStage, connectionStageError, extractConnectionEvidence } from './connection-error.mjs';
|
|
3
|
+
import { validateBotAlias, withBotAlias } from './bot-alias.mjs';
|
|
4
|
+
import { defaultImWorkspace, ensureImWorkspaceDirectory, sameWorkspacePath } from './default-workspace.mjs';
|
|
5
|
+
import {
|
|
6
|
+
mkdir,
|
|
7
|
+
readFile,
|
|
8
|
+
realpath,
|
|
9
|
+
rename,
|
|
10
|
+
stat,
|
|
11
|
+
unlink,
|
|
12
|
+
writeFile,
|
|
13
|
+
} from 'node:fs/promises';
|
|
14
|
+
import { dirname, isAbsolute, resolve } from 'node:path';
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
normalizeAgentPresetCatalog,
|
|
18
|
+
validateAgentPresetId,
|
|
19
|
+
} from './agent-preset.mjs';
|
|
20
|
+
import {
|
|
21
|
+
normalizeAccessPolicy,
|
|
22
|
+
validateAccessPolicy,
|
|
23
|
+
} from './access-policy.mjs';
|
|
24
|
+
import { CONNECTION_TEST_STATE_IDENTITY } from './connection-test.mjs';
|
|
25
|
+
import {
|
|
26
|
+
DEFAULT_CONTEXT_ENHANCEMENT_CONFIG,
|
|
27
|
+
normalizeContextEnhancementConfig,
|
|
28
|
+
validateContextEnhancementConfig,
|
|
29
|
+
} from './context-enhancement.mjs';
|
|
30
|
+
import {
|
|
31
|
+
confirmsModelSelection,
|
|
32
|
+
modelCatalogEntry,
|
|
33
|
+
normalizeModelCatalog,
|
|
34
|
+
sameModelSelection,
|
|
35
|
+
validateModelSelection,
|
|
36
|
+
} from './model-setting.mjs';
|
|
37
|
+
import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs';
|
|
38
|
+
import { configValidationError, withConfigResource } from './config-read-error.mjs';
|
|
39
|
+
|
|
40
|
+
const DELIVERY_DOCUMENT_VERSION = 2;
|
|
41
|
+
export const CURRENT_DOCUMENT_VERSION = 3;
|
|
42
|
+
const EMPTY_DOCUMENT = Object.freeze({ version: 1, workspaces: Object.freeze({}) });
|
|
43
|
+
|
|
44
|
+
function invalidWorkspaceConfig(field, issue) {
|
|
45
|
+
throw configValidationError('dsh-im workspace config is invalid', field, issue);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function workspaceSessionStale(message) {
|
|
49
|
+
const error = new Error(message);
|
|
50
|
+
error.code = WORKSPACE_SESSION_STALE;
|
|
51
|
+
return error;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function canonicalWorkspacePath(value) {
|
|
55
|
+
return resolve(await realpath(value));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function botIdOf(value) {
|
|
59
|
+
if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(value)) {
|
|
60
|
+
throw new TypeError('Invalid bot id');
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function deliveryTargetError(code, message, options) {
|
|
66
|
+
const error = new Error(message, options);
|
|
67
|
+
error.code = code;
|
|
68
|
+
return error;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function targetIdOf(value) {
|
|
72
|
+
if (typeof value !== 'string'
|
|
73
|
+
|| !/^[A-Za-z0-9._:@-]{1,128}$/.test(value)) {
|
|
74
|
+
throw deliveryTargetError('invalid-target', 'Invalid target id');
|
|
75
|
+
}
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function jsonRecord(value) {
|
|
80
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
81
|
+
throw deliveryTargetError('invalid-target', 'Invalid target route');
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
const serialized = JSON.stringify(value);
|
|
85
|
+
if (serialized === undefined) throw new TypeError('route is not JSON');
|
|
86
|
+
const route = JSON.parse(serialized);
|
|
87
|
+
if (!route || typeof route !== 'object' || Array.isArray(route)) {
|
|
88
|
+
throw new TypeError('route is not an object');
|
|
89
|
+
}
|
|
90
|
+
return route;
|
|
91
|
+
} catch (cause) {
|
|
92
|
+
throw deliveryTargetError('invalid-target', 'Invalid target route', { cause });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function conversationKeyOf(value) {
|
|
97
|
+
if (typeof value !== 'string' || !value || value.length > 1_024
|
|
98
|
+
|| value.trim() !== value || /[\u0000-\u001f\u007f]/u.test(value)) {
|
|
99
|
+
throw deliveryTargetError('invalid-target', 'Invalid private conversation key');
|
|
100
|
+
}
|
|
101
|
+
return value;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function conversationWorkspaceGenerationKey(botId, conversationKey) {
|
|
105
|
+
// Conversation keys validated by conversationKeyOf never contain the null
|
|
106
|
+
// separator, so the compound key stays unambiguous.
|
|
107
|
+
return `${botIdOf(botId)}\u0000${conversationKeyOf(conversationKey)}`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function normalizeConversationWorkspaces(value) {
|
|
111
|
+
const conversationWorkspaces = Object.create(null);
|
|
112
|
+
if (value === undefined) return conversationWorkspaces;
|
|
113
|
+
// Override damage is isolated: an invalid entry is dropped rather than
|
|
114
|
+
// failing the whole document, because a missing/invalid override falls back
|
|
115
|
+
// to the bot workspace safely.
|
|
116
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
117
|
+
return conversationWorkspaces;
|
|
118
|
+
}
|
|
119
|
+
for (const [botId, overrides] of Object.entries(value)) {
|
|
120
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(botId)) continue;
|
|
121
|
+
if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides)) continue;
|
|
122
|
+
const normalized = Object.create(null);
|
|
123
|
+
for (const [conversationKey, workspace] of Object.entries(overrides)) {
|
|
124
|
+
if (typeof conversationKey !== 'string' || !conversationKey
|
|
125
|
+
|| typeof workspace !== 'string' || !isAbsolute(workspace)) continue;
|
|
126
|
+
normalized[conversationKey] = resolve(workspace);
|
|
127
|
+
}
|
|
128
|
+
if (Object.keys(normalized).length > 0) conversationWorkspaces[botId] = normalized;
|
|
129
|
+
}
|
|
130
|
+
return conversationWorkspaces;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function normalizeDeliveryTarget(value, { targetId, allowSessionSync = false } = {}) {
|
|
134
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
135
|
+
throw deliveryTargetError('invalid-target', 'Invalid delivery target');
|
|
136
|
+
}
|
|
137
|
+
const allowed = targetId === undefined
|
|
138
|
+
? new Set(['targetId', 'name', 'kind', 'route', ...(allowSessionSync ? ['sessionSync'] : [])])
|
|
139
|
+
: new Set(['name', 'kind', 'route', ...(allowSessionSync ? ['sessionSync'] : [])]);
|
|
140
|
+
if (Object.keys(value).some((key) => !allowed.has(key))) {
|
|
141
|
+
throw deliveryTargetError('invalid-target', 'Invalid delivery target');
|
|
142
|
+
}
|
|
143
|
+
const id = targetIdOf(targetId ?? value.targetId);
|
|
144
|
+
if (typeof value.kind !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(value.kind)) {
|
|
145
|
+
throw deliveryTargetError('invalid-target', 'Invalid target kind');
|
|
146
|
+
}
|
|
147
|
+
let name;
|
|
148
|
+
if (value.name !== undefined) {
|
|
149
|
+
if (typeof value.name !== 'string' || !value.name.trim() || value.name.trim().length > 80) {
|
|
150
|
+
throw deliveryTargetError('invalid-target', 'Invalid target name');
|
|
151
|
+
}
|
|
152
|
+
name = value.name.trim();
|
|
153
|
+
}
|
|
154
|
+
let sessionSync;
|
|
155
|
+
if (value.sessionSync !== undefined) {
|
|
156
|
+
if (!allowSessionSync || !value.sessionSync || typeof value.sessionSync !== 'object'
|
|
157
|
+
|| Array.isArray(value.sessionSync)
|
|
158
|
+
|| Object.keys(value.sessionSync).length !== 1
|
|
159
|
+
|| !Object.hasOwn(value.sessionSync, 'conversationKey')) {
|
|
160
|
+
throw deliveryTargetError('invalid-target', 'Invalid delivery target session sync');
|
|
161
|
+
}
|
|
162
|
+
sessionSync = { conversationKey: conversationKeyOf(value.sessionSync.conversationKey) };
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
targetId: id,
|
|
166
|
+
...(name === undefined ? {} : { name }),
|
|
167
|
+
kind: value.kind,
|
|
168
|
+
route: jsonRecord(value.route),
|
|
169
|
+
...(sessionSync === undefined ? {} : { sessionSync }),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function publicDeliveryTarget(value, { targetId } = {}) {
|
|
174
|
+
const normalized = normalizeDeliveryTarget(value, { targetId, allowSessionSync: true });
|
|
175
|
+
const { sessionSync: _sessionSync, ...target } = normalized;
|
|
176
|
+
return target;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function sameDeliveryRoute(left, right) {
|
|
180
|
+
return left?.kind === right?.kind
|
|
181
|
+
&& JSON.stringify(left?.route) === JSON.stringify(right?.route);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function normalizeDeliveryTargets(value, { version } = {}) {
|
|
185
|
+
const deliveryTargets = Object.create(null);
|
|
186
|
+
if (value === undefined) return deliveryTargets;
|
|
187
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return invalidWorkspaceConfig('deliveryTargets', 'expected-object');
|
|
188
|
+
let field = 'deliveryTargets';
|
|
189
|
+
try {
|
|
190
|
+
for (const [botIndex, [botId, targets]] of Object.entries(value).entries()) {
|
|
191
|
+
field = `deliveryTargets[${botIndex}].key`;
|
|
192
|
+
botIdOf(botId);
|
|
193
|
+
field = `deliveryTargets[${botIndex}].targets`;
|
|
194
|
+
if (!targets || typeof targets !== 'object' || Array.isArray(targets)) throw new TypeError('Invalid targets');
|
|
195
|
+
const normalizedTargets = Object.create(null);
|
|
196
|
+
for (const [targetIndex, [targetId, target]] of Object.entries(targets).entries()) {
|
|
197
|
+
field = `deliveryTargets[${botIndex}].targets[${targetIndex}]`;
|
|
198
|
+
// Backward compatibility: some released builds persisted the target id
|
|
199
|
+
// inside the stored object as well. Accept a redundant targetId that
|
|
200
|
+
// matches the map key when loading a stored document; a mismatch stays
|
|
201
|
+
// invalid so a corrupted file still fails closed.
|
|
202
|
+
let candidate = target;
|
|
203
|
+
if (target && typeof target === 'object' && !Array.isArray(target)
|
|
204
|
+
&& target.targetId !== undefined) {
|
|
205
|
+
if (target.targetId !== targetId) {
|
|
206
|
+
throw deliveryTargetError('invalid-target', 'Invalid target id');
|
|
207
|
+
}
|
|
208
|
+
const { targetId: _legacyTargetId, ...withoutLegacyId } = target;
|
|
209
|
+
candidate = withoutLegacyId;
|
|
210
|
+
}
|
|
211
|
+
const normalized = normalizeDeliveryTarget(candidate, {
|
|
212
|
+
targetId,
|
|
213
|
+
allowSessionSync: version >= CURRENT_DOCUMENT_VERSION,
|
|
214
|
+
});
|
|
215
|
+
const { targetId: _targetId, ...stored } = normalized;
|
|
216
|
+
normalizedTargets[targetId] = stored;
|
|
217
|
+
}
|
|
218
|
+
deliveryTargets[botId] = normalizedTargets;
|
|
219
|
+
}
|
|
220
|
+
} catch {
|
|
221
|
+
return invalidWorkspaceConfig(field, 'invalid-delivery-target');
|
|
222
|
+
}
|
|
223
|
+
return deliveryTargets;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function normalizeAccessPolicies(value, workspaces) {
|
|
227
|
+
const accessPolicies = Object.create(null);
|
|
228
|
+
if (value === undefined) return accessPolicies;
|
|
229
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
230
|
+
// Preserve the distinction between a missing policy (eligible for startup
|
|
231
|
+
// initialization) and damaged persisted data (fail closed).
|
|
232
|
+
for (const botId of Object.keys(workspaces)) accessPolicies[botId] = null;
|
|
233
|
+
return accessPolicies;
|
|
234
|
+
}
|
|
235
|
+
for (const [botId, policy] of Object.entries(value)) {
|
|
236
|
+
try {
|
|
237
|
+
botIdOf(botId);
|
|
238
|
+
accessPolicies[botId] = normalizeAccessPolicy(policy);
|
|
239
|
+
} catch {
|
|
240
|
+
// An invalid key cannot identify a bot, so it is isolated and ignored.
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return accessPolicies;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function normalizeDocument(value) {
|
|
247
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return invalidWorkspaceConfig('$', 'expected-object');
|
|
248
|
+
if (![1, DELIVERY_DOCUMENT_VERSION, CURRENT_DOCUMENT_VERSION].includes(value.version)) return invalidWorkspaceConfig('version', 'unsupported-version');
|
|
249
|
+
if (!value.workspaces || typeof value.workspaces !== 'object' || Array.isArray(value.workspaces)) return invalidWorkspaceConfig('workspaces', 'expected-object');
|
|
250
|
+
const workspaces = {};
|
|
251
|
+
for (const [index, [botId, workspace]] of Object.entries(value.workspaces).entries()) {
|
|
252
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(botId)) return invalidWorkspaceConfig(`workspaces[${index}].key`, 'invalid-identifier');
|
|
253
|
+
if (typeof workspace !== 'string' || !isAbsolute(workspace)) return invalidWorkspaceConfig(`workspaces[${index}].value`, 'invalid-workspace-path');
|
|
254
|
+
workspaces[botId] = resolve(workspace);
|
|
255
|
+
}
|
|
256
|
+
const conversationWorkspaces = normalizeConversationWorkspaces(value.conversationWorkspaces);
|
|
257
|
+
let agentPresets = {};
|
|
258
|
+
if (value.agentPresets !== undefined) {
|
|
259
|
+
if (!value.agentPresets || typeof value.agentPresets !== 'object'
|
|
260
|
+
|| Array.isArray(value.agentPresets)) return invalidWorkspaceConfig('agentPresets', 'expected-object');
|
|
261
|
+
for (const [index, [botId, agentPreset]] of Object.entries(value.agentPresets).entries()) {
|
|
262
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(botId)) return invalidWorkspaceConfig(`agentPresets[${index}].key`, 'invalid-identifier');
|
|
263
|
+
try {
|
|
264
|
+
const normalized = validateAgentPresetId(agentPreset);
|
|
265
|
+
if (!normalized) return invalidWorkspaceConfig(`agentPresets[${index}].value`, 'invalid-agent-preset');
|
|
266
|
+
agentPresets[botId] = normalized;
|
|
267
|
+
} catch {
|
|
268
|
+
return invalidWorkspaceConfig(`agentPresets[${index}].value`, 'invalid-agent-preset');
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const models = {};
|
|
273
|
+
if (value.models !== undefined) {
|
|
274
|
+
if (!value.models || typeof value.models !== 'object' || Array.isArray(value.models)) {
|
|
275
|
+
return invalidWorkspaceConfig('models', 'expected-object');
|
|
276
|
+
}
|
|
277
|
+
for (const [index, [botId, model]] of Object.entries(value.models).entries()) {
|
|
278
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(botId)) return invalidWorkspaceConfig(`models[${index}].key`, 'invalid-identifier');
|
|
279
|
+
try {
|
|
280
|
+
const normalized = validateModelSelection(model);
|
|
281
|
+
if (!normalized) return invalidWorkspaceConfig(`models[${index}].value`, 'invalid-model-selection');
|
|
282
|
+
models[botId] = normalized;
|
|
283
|
+
} catch {
|
|
284
|
+
return invalidWorkspaceConfig(`models[${index}].value`, 'invalid-model-selection');
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
const contextEnhancement = Object.create(null);
|
|
289
|
+
// Enhancement damage is isolated from the existing workspace/preset document.
|
|
290
|
+
if (value.contextEnhancement && typeof value.contextEnhancement === 'object'
|
|
291
|
+
&& !Array.isArray(value.contextEnhancement)) {
|
|
292
|
+
for (const [botId, config] of Object.entries(value.contextEnhancement)) {
|
|
293
|
+
if (/^[A-Za-z0-9_-]{1,128}$/.test(botId)) {
|
|
294
|
+
contextEnhancement[botId] = normalizeContextEnhancementConfig(config);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (value.version === 1 && value.deliveryTargets !== undefined) return invalidWorkspaceConfig('deliveryTargets', 'unexpected-field');
|
|
299
|
+
const deliveryTargets = normalizeDeliveryTargets(value.deliveryTargets, { version: value.version });
|
|
300
|
+
const aliases = Object.create(null);
|
|
301
|
+
if (value.aliases && typeof value.aliases === 'object' && !Array.isArray(value.aliases)) {
|
|
302
|
+
for (const [botId, alias] of Object.entries(value.aliases)) {
|
|
303
|
+
try {
|
|
304
|
+
botIdOf(botId);
|
|
305
|
+
const normalized = validateBotAlias(alias);
|
|
306
|
+
if (normalized) aliases[botId] = normalized;
|
|
307
|
+
} catch { /* A damaged display name must not disable the bot. */ }
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const accessPolicies = normalizeAccessPolicies(value.accessPolicies, workspaces);
|
|
311
|
+
const version = Math.max(
|
|
312
|
+
value.version,
|
|
313
|
+
value.accessPolicies === undefined ? 1 : DELIVERY_DOCUMENT_VERSION,
|
|
314
|
+
);
|
|
315
|
+
return {
|
|
316
|
+
// A v1 file cannot be emitted with this optional v2 section. If one is
|
|
317
|
+
// recovered from an interrupted/manual edit, retain it on the next write.
|
|
318
|
+
version,
|
|
319
|
+
workspaces,
|
|
320
|
+
conversationWorkspaces,
|
|
321
|
+
agentPresets,
|
|
322
|
+
models,
|
|
323
|
+
contextEnhancement,
|
|
324
|
+
deliveryTargets,
|
|
325
|
+
accessPolicies,
|
|
326
|
+
aliases,
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function storedDocument({
|
|
331
|
+
version,
|
|
332
|
+
workspaces,
|
|
333
|
+
conversationWorkspaces,
|
|
334
|
+
agentPresets,
|
|
335
|
+
models,
|
|
336
|
+
contextEnhancement,
|
|
337
|
+
deliveryTargets,
|
|
338
|
+
accessPolicies,
|
|
339
|
+
aliases,
|
|
340
|
+
}) {
|
|
341
|
+
const document = { version, workspaces };
|
|
342
|
+
if (Object.keys(aliases).length > 0) document.aliases = aliases;
|
|
343
|
+
if (Object.keys(conversationWorkspaces).length > 0) {
|
|
344
|
+
document.conversationWorkspaces = conversationWorkspaces;
|
|
345
|
+
}
|
|
346
|
+
if (Object.keys(agentPresets).length > 0) document.agentPresets = agentPresets;
|
|
347
|
+
if (Object.keys(models).length > 0) document.models = models;
|
|
348
|
+
if (Object.keys(contextEnhancement).length > 0) {
|
|
349
|
+
document.contextEnhancement = contextEnhancement;
|
|
350
|
+
}
|
|
351
|
+
if (version >= DELIVERY_DOCUMENT_VERSION && Object.keys(deliveryTargets).length > 0) {
|
|
352
|
+
document.deliveryTargets = deliveryTargets;
|
|
353
|
+
}
|
|
354
|
+
if (version >= DELIVERY_DOCUMENT_VERSION && Object.keys(accessPolicies).length > 0) {
|
|
355
|
+
document.accessPolicies = accessPolicies;
|
|
356
|
+
}
|
|
357
|
+
return document;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async function writeStoredDocument(path, document) {
|
|
361
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
362
|
+
const temporary = `${path}.tmp`;
|
|
363
|
+
await writeFile(temporary, `${JSON.stringify(document, null, 2)}\n`, {
|
|
364
|
+
encoding: 'utf8',
|
|
365
|
+
mode: 0o600,
|
|
366
|
+
});
|
|
367
|
+
await rename(temporary, path);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export async function validateWorkspacePath(value, { ungroupedWorkspace } = {}) {
|
|
371
|
+
if (typeof value !== 'string' || !value.trim() || !isAbsolute(value.trim())) {
|
|
372
|
+
const error = new Error('工作区必须是绝对路径。');
|
|
373
|
+
error.code = 'workspace-not-absolute';
|
|
374
|
+
throw error;
|
|
375
|
+
}
|
|
376
|
+
const workspace = resolve(value.trim());
|
|
377
|
+
await ensureImWorkspaceDirectory(workspace, ungroupedWorkspace);
|
|
378
|
+
let info;
|
|
379
|
+
try {
|
|
380
|
+
info = await stat(workspace);
|
|
381
|
+
} catch (cause) {
|
|
382
|
+
const error = new Error('工作区路径不存在。', { cause });
|
|
383
|
+
error.code = 'workspace-not-found';
|
|
384
|
+
throw error;
|
|
385
|
+
}
|
|
386
|
+
if (!info.isDirectory()) {
|
|
387
|
+
const error = new Error('工作区路径必须指向一个目录。');
|
|
388
|
+
error.code = 'workspace-not-directory';
|
|
389
|
+
throw error;
|
|
390
|
+
}
|
|
391
|
+
return workspace;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export class BotWorkspaceStore {
|
|
395
|
+
#path;
|
|
396
|
+
#defaultWorkspace;
|
|
397
|
+
#ungroupedWorkspace;
|
|
398
|
+
#version = 1;
|
|
399
|
+
#workspaces = {};
|
|
400
|
+
#agentPresets = {};
|
|
401
|
+
#models = {};
|
|
402
|
+
#aliases = Object.create(null);
|
|
403
|
+
#contextEnhancement = {};
|
|
404
|
+
#deliveryTargets = Object.create(null);
|
|
405
|
+
#accessPolicies = Object.create(null);
|
|
406
|
+
#conversationWorkspaces = Object.create(null);
|
|
407
|
+
#generations = new Map();
|
|
408
|
+
#nextGeneration = 1;
|
|
409
|
+
#conversationGenerations = new Map();
|
|
410
|
+
#nextConversationGeneration = 1;
|
|
411
|
+
#incarnations = new Map();
|
|
412
|
+
#nextIncarnation = 1;
|
|
413
|
+
#removals = new Map();
|
|
414
|
+
#removalDetails = new WeakMap();
|
|
415
|
+
#dirtyRemovals = new Set();
|
|
416
|
+
#writeQueue = Promise.resolve();
|
|
417
|
+
#botQueues = new Map();
|
|
418
|
+
|
|
419
|
+
constructor(path, { defaultWorkspace = defaultImWorkspace(), ungroupedWorkspace } = {}) {
|
|
420
|
+
if (typeof path !== 'string' || !path) throw new TypeError('workspace store path is required');
|
|
421
|
+
this.#path = path;
|
|
422
|
+
this.#defaultWorkspace = resolve(defaultWorkspace);
|
|
423
|
+
this.#ungroupedWorkspace = ungroupedWorkspace;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async load() {
|
|
427
|
+
try {
|
|
428
|
+
const normalized = normalizeDocument(JSON.parse(await readFile(this.#path, 'utf8')));
|
|
429
|
+
this.#version = normalized.version;
|
|
430
|
+
this.#workspaces = normalized.workspaces;
|
|
431
|
+
this.#agentPresets = normalized.agentPresets;
|
|
432
|
+
this.#models = normalized.models;
|
|
433
|
+
this.#aliases = normalized.aliases;
|
|
434
|
+
this.#contextEnhancement = normalized.contextEnhancement;
|
|
435
|
+
this.#deliveryTargets = normalized.deliveryTargets;
|
|
436
|
+
this.#accessPolicies = normalized.accessPolicies;
|
|
437
|
+
this.#conversationWorkspaces = normalized.conversationWorkspaces;
|
|
438
|
+
} catch (error) {
|
|
439
|
+
if (error?.code !== 'ENOENT') throw withConfigResource(error, 'workspace-config');
|
|
440
|
+
this.#version = 1;
|
|
441
|
+
this.#workspaces = {};
|
|
442
|
+
this.#agentPresets = {};
|
|
443
|
+
this.#models = {};
|
|
444
|
+
this.#aliases = Object.create(null);
|
|
445
|
+
this.#contextEnhancement = {};
|
|
446
|
+
this.#deliveryTargets = Object.create(null);
|
|
447
|
+
this.#accessPolicies = Object.create(null);
|
|
448
|
+
this.#conversationWorkspaces = Object.create(null);
|
|
449
|
+
}
|
|
450
|
+
this.#generations.clear();
|
|
451
|
+
this.#nextGeneration = 1;
|
|
452
|
+
this.#conversationGenerations.clear();
|
|
453
|
+
this.#nextConversationGeneration = 1;
|
|
454
|
+
this.#incarnations.clear();
|
|
455
|
+
this.#nextIncarnation = 1;
|
|
456
|
+
this.#removals.clear();
|
|
457
|
+
this.#dirtyRemovals.clear();
|
|
458
|
+
for (const botId of Object.keys(this.#workspaces)) {
|
|
459
|
+
this.#generations.set(botId, this.#freshGeneration());
|
|
460
|
+
this.#incarnations.set(botId, this.#freshIncarnation());
|
|
461
|
+
}
|
|
462
|
+
return this;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
has(botId) {
|
|
466
|
+
const id = botIdOf(botId);
|
|
467
|
+
return Object.hasOwn(this.#workspaces, id) && !this.#removals.has(id);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
listBotIds() {
|
|
471
|
+
return Object.keys(this.#workspaces)
|
|
472
|
+
.filter((botId) => !this.#removals.has(botId))
|
|
473
|
+
.sort();
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
incarnationFor(botId) {
|
|
477
|
+
return this.#incarnations.get(botIdOf(botId)) ?? null;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
workspaceFor(botId) {
|
|
481
|
+
return this.#workspaces[botIdOf(botId)] ?? this.#defaultWorkspace;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* An explicit override is stored even when it equals the current bot default,
|
|
486
|
+
* so a later default change must never move a conversation that pinned its
|
|
487
|
+
* own workspace.
|
|
488
|
+
*/
|
|
489
|
+
hasConversationWorkspaceOverride(botId, conversationKey) {
|
|
490
|
+
const id = botIdOf(botId);
|
|
491
|
+
return Boolean(conversationKey) && Boolean(this.#conversationWorkspaces[id]?.[conversationKey]);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
conversationWorkspaceFor(botId, conversationKey) {
|
|
495
|
+
const id = botIdOf(botId);
|
|
496
|
+
const override = this.#conversationWorkspaces[id]?.[conversationKey];
|
|
497
|
+
if (override) return override;
|
|
498
|
+
return this.workspaceFor(id);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
conversationGenerationFor(botId, conversationKey) {
|
|
502
|
+
if (typeof conversationKey !== 'string' || !conversationKey) return null;
|
|
503
|
+
return this.#conversationGenerations.get(
|
|
504
|
+
conversationWorkspaceGenerationKey(botId, conversationKey),
|
|
505
|
+
) ?? null;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
agentPresetFor(botId) {
|
|
509
|
+
return this.#agentPresets[botIdOf(botId)] ?? null;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
modelFor(botId) {
|
|
513
|
+
const selection = this.#models[botIdOf(botId)];
|
|
514
|
+
return selection ? { ...selection } : null;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
aliasFor(botId) {
|
|
518
|
+
const id = botIdOf(botId);
|
|
519
|
+
return this.has(id) && Object.hasOwn(this.#aliases, id) ? this.#aliases[id] : '';
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
contextEnhancementFor(botId) {
|
|
523
|
+
const id = botIdOf(botId);
|
|
524
|
+
return this.has(id) && Object.hasOwn(this.#contextEnhancement, id)
|
|
525
|
+
? this.#contextEnhancement[id]
|
|
526
|
+
: DEFAULT_CONTEXT_ENHANCEMENT_CONFIG;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
accessPolicyFor(botId) {
|
|
530
|
+
const id = botIdOf(botId);
|
|
531
|
+
return this.has(id) && Object.hasOwn(this.#accessPolicies, id)
|
|
532
|
+
? this.#accessPolicies[id]
|
|
533
|
+
: null;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
listDeliveryTargets(botId) {
|
|
537
|
+
const id = botIdOf(botId);
|
|
538
|
+
if (!this.has(id)) throw deliveryTargetError('unknown-bot', 'Unknown bot');
|
|
539
|
+
return Object.entries(this.#deliveryTargets[id] ?? {})
|
|
540
|
+
.map(([targetId, target]) => publicDeliveryTarget(target, { targetId }))
|
|
541
|
+
.sort((left, right) => left.targetId.localeCompare(right.targetId));
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
deliveryTargetFor(botId, targetId) {
|
|
545
|
+
const id = botIdOf(botId);
|
|
546
|
+
const targetKey = targetIdOf(targetId);
|
|
547
|
+
if (!this.has(id)) throw deliveryTargetError('unknown-bot', 'Unknown bot');
|
|
548
|
+
const target = this.#deliveryTargets[id]?.[targetKey];
|
|
549
|
+
return target ? publicDeliveryTarget(target, { targetId: targetKey }) : null;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
listSessionSyncTargets() {
|
|
553
|
+
const targets = [];
|
|
554
|
+
for (const [botId, botTargets] of Object.entries(this.#deliveryTargets)) {
|
|
555
|
+
if (!this.has(botId)) continue;
|
|
556
|
+
for (const [targetId, target] of Object.entries(botTargets)) {
|
|
557
|
+
const normalized = normalizeDeliveryTarget(target, {
|
|
558
|
+
targetId,
|
|
559
|
+
allowSessionSync: true,
|
|
560
|
+
});
|
|
561
|
+
if (!normalized.sessionSync) continue;
|
|
562
|
+
targets.push({
|
|
563
|
+
botId,
|
|
564
|
+
targetId,
|
|
565
|
+
conversationKey: normalized.sessionSync.conversationKey,
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return targets.sort((left, right) => (
|
|
570
|
+
left.botId.localeCompare(right.botId) || left.targetId.localeCompare(right.targetId)
|
|
571
|
+
));
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
async createDeliveryTarget(botId, value) {
|
|
575
|
+
const id = botIdOf(botId);
|
|
576
|
+
const target = normalizeDeliveryTarget(value);
|
|
577
|
+
return this.#enqueue(id, async () => {
|
|
578
|
+
if (!this.has(id)) throw deliveryTargetError('unknown-bot', 'Unknown bot');
|
|
579
|
+
if (Object.hasOwn(this.#deliveryTargets[id] ?? {}, target.targetId)) {
|
|
580
|
+
throw deliveryTargetError('target-conflict', 'Target already exists');
|
|
581
|
+
}
|
|
582
|
+
const { targetId, ...stored } = target;
|
|
583
|
+
const next = {
|
|
584
|
+
...this.#deliveryTargets,
|
|
585
|
+
[id]: { ...(this.#deliveryTargets[id] ?? {}), [targetId]: stored },
|
|
586
|
+
};
|
|
587
|
+
const nextVersion = Math.max(this.#version, DELIVERY_DOCUMENT_VERSION);
|
|
588
|
+
await this.#persist(this.#contextEnhancement, next, nextVersion);
|
|
589
|
+
this.#deliveryTargets = next;
|
|
590
|
+
this.#version = nextVersion;
|
|
591
|
+
return publicDeliveryTarget(stored, { targetId });
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
async updateDeliveryTarget(botId, targetId, value) {
|
|
596
|
+
const id = botIdOf(botId);
|
|
597
|
+
const targetKey = targetIdOf(targetId);
|
|
598
|
+
const replacement = normalizeDeliveryTarget(value, { targetId: targetKey });
|
|
599
|
+
return this.#enqueue(id, async () => {
|
|
600
|
+
if (!this.has(id)) throw deliveryTargetError('unknown-bot', 'Unknown bot');
|
|
601
|
+
if (!Object.hasOwn(this.#deliveryTargets[id] ?? {}, targetKey)) {
|
|
602
|
+
throw deliveryTargetError('unknown-target', 'Unknown target');
|
|
603
|
+
}
|
|
604
|
+
const { targetId: _targetId, ...stored } = replacement;
|
|
605
|
+
const previous = this.#deliveryTargets[id][targetKey];
|
|
606
|
+
const nextStored = previous.sessionSync && sameDeliveryRoute(previous, stored)
|
|
607
|
+
? { ...stored, sessionSync: previous.sessionSync }
|
|
608
|
+
: stored;
|
|
609
|
+
const next = {
|
|
610
|
+
...this.#deliveryTargets,
|
|
611
|
+
[id]: { ...this.#deliveryTargets[id], [targetKey]: nextStored },
|
|
612
|
+
};
|
|
613
|
+
const nextVersion = Math.max(this.#version, DELIVERY_DOCUMENT_VERSION);
|
|
614
|
+
await this.#persist(this.#contextEnhancement, next, nextVersion);
|
|
615
|
+
this.#deliveryTargets = next;
|
|
616
|
+
this.#version = nextVersion;
|
|
617
|
+
return publicDeliveryTarget(nextStored, { targetId: targetKey });
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
async deleteDeliveryTarget(botId, targetId) {
|
|
622
|
+
const id = botIdOf(botId);
|
|
623
|
+
const targetKey = targetIdOf(targetId);
|
|
624
|
+
return this.#enqueue(id, async () => {
|
|
625
|
+
if (!this.has(id)) throw deliveryTargetError('unknown-bot', 'Unknown bot');
|
|
626
|
+
if (!Object.hasOwn(this.#deliveryTargets[id] ?? {}, targetKey)) {
|
|
627
|
+
throw deliveryTargetError('unknown-target', 'Unknown target');
|
|
628
|
+
}
|
|
629
|
+
const botTargets = { ...this.#deliveryTargets[id] };
|
|
630
|
+
delete botTargets[targetKey];
|
|
631
|
+
const next = { ...this.#deliveryTargets };
|
|
632
|
+
if (Object.keys(botTargets).length > 0) next[id] = botTargets;
|
|
633
|
+
else delete next[id];
|
|
634
|
+
const nextVersion = Math.max(this.#version, DELIVERY_DOCUMENT_VERSION);
|
|
635
|
+
await this.#persist(this.#contextEnhancement, next, nextVersion);
|
|
636
|
+
this.#deliveryTargets = next;
|
|
637
|
+
this.#version = nextVersion;
|
|
638
|
+
return true;
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
async setDeliveryTargetSessionSync(botId, targetId, conversationKeyOrNull) {
|
|
643
|
+
const id = botIdOf(botId);
|
|
644
|
+
const targetKey = targetIdOf(targetId);
|
|
645
|
+
const conversationKey = conversationKeyOrNull === null
|
|
646
|
+
? null
|
|
647
|
+
: conversationKeyOf(conversationKeyOrNull);
|
|
648
|
+
return this.#enqueue(id, async () => {
|
|
649
|
+
if (!this.has(id)) throw deliveryTargetError('unknown-bot', 'Unknown bot');
|
|
650
|
+
const previous = this.#deliveryTargets[id]?.[targetKey];
|
|
651
|
+
if (!previous) throw deliveryTargetError('unknown-target', 'Unknown target');
|
|
652
|
+
const previousKey = previous.sessionSync?.conversationKey ?? null;
|
|
653
|
+
if (previousKey === conversationKey) return conversationKey !== null;
|
|
654
|
+
const nextStored = { ...previous };
|
|
655
|
+
if (conversationKey === null) delete nextStored.sessionSync;
|
|
656
|
+
else nextStored.sessionSync = { conversationKey };
|
|
657
|
+
const next = {
|
|
658
|
+
...this.#deliveryTargets,
|
|
659
|
+
[id]: { ...this.#deliveryTargets[id], [targetKey]: nextStored },
|
|
660
|
+
};
|
|
661
|
+
await this.#persist(this.#contextEnhancement, next, CURRENT_DOCUMENT_VERSION);
|
|
662
|
+
this.#deliveryTargets = next;
|
|
663
|
+
this.#version = CURRENT_DOCUMENT_VERSION;
|
|
664
|
+
return conversationKey !== null;
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
generationFor(botId) {
|
|
669
|
+
return this.#generations.get(botIdOf(botId)) ?? null;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
async whenIdle() {
|
|
673
|
+
await this.#writeQueue;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
async whenBotIdle(botId) {
|
|
677
|
+
const id = botIdOf(botId);
|
|
678
|
+
while (true) {
|
|
679
|
+
const pending = this.#botQueues.get(id);
|
|
680
|
+
if (!pending) return;
|
|
681
|
+
await pending;
|
|
682
|
+
if (this.#botQueues.get(id) === pending) return;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
async ensure(botId, {
|
|
687
|
+
workspace = this.#defaultWorkspace,
|
|
688
|
+
defaultAgentPreset,
|
|
689
|
+
initialAccessPolicy,
|
|
690
|
+
} = {}) {
|
|
691
|
+
const id = botIdOf(botId);
|
|
692
|
+
const initialWorkspace = resolve(workspace);
|
|
693
|
+
return this.#enqueue(id, async () => {
|
|
694
|
+
const createsBot = !this.#workspaces[id];
|
|
695
|
+
const initializesAccessPolicy = initialAccessPolicy !== undefined
|
|
696
|
+
&& !Object.hasOwn(this.#accessPolicies, id);
|
|
697
|
+
const accessPolicy = initializesAccessPolicy
|
|
698
|
+
? validateAccessPolicy(initialAccessPolicy)
|
|
699
|
+
: undefined;
|
|
700
|
+
const agentPreset = createsBot ? validateAgentPresetId(defaultAgentPreset) : null;
|
|
701
|
+
// Resolve saved bot/conversation choices before preparing the shared IM
|
|
702
|
+
// directory. Merely loading a channel must not create an unused fallback.
|
|
703
|
+
const selectedWorkspaces = new Set([
|
|
704
|
+
this.#workspaces[id] ?? initialWorkspace,
|
|
705
|
+
...Object.values(this.#conversationWorkspaces[id] ?? {}),
|
|
706
|
+
]);
|
|
707
|
+
for (const selected of selectedWorkspaces) {
|
|
708
|
+
await ensureImWorkspaceDirectory(selected, this.#ungroupedWorkspace);
|
|
709
|
+
}
|
|
710
|
+
if (createsBot || initializesAccessPolicy) {
|
|
711
|
+
const hadAgentPreset = Object.hasOwn(this.#agentPresets, id);
|
|
712
|
+
const previousAgentPreset = this.#agentPresets[id];
|
|
713
|
+
const nextAccessPolicies = initializesAccessPolicy
|
|
714
|
+
? { ...this.#accessPolicies, [id]: accessPolicy }
|
|
715
|
+
: this.#accessPolicies;
|
|
716
|
+
if (createsBot) {
|
|
717
|
+
this.#workspaces[id] = initialWorkspace;
|
|
718
|
+
if (agentPreset) this.#agentPresets[id] = agentPreset;
|
|
719
|
+
this.#generations.set(id, this.#freshGeneration());
|
|
720
|
+
this.#incarnations.set(id, this.#freshIncarnation());
|
|
721
|
+
}
|
|
722
|
+
const nextVersion = initializesAccessPolicy
|
|
723
|
+
? Math.max(this.#version, DELIVERY_DOCUMENT_VERSION)
|
|
724
|
+
: this.#version;
|
|
725
|
+
try {
|
|
726
|
+
await this.#persist(
|
|
727
|
+
this.#contextEnhancement,
|
|
728
|
+
this.#deliveryTargets,
|
|
729
|
+
nextVersion,
|
|
730
|
+
nextAccessPolicies,
|
|
731
|
+
);
|
|
732
|
+
} catch (error) {
|
|
733
|
+
if (createsBot) {
|
|
734
|
+
delete this.#workspaces[id];
|
|
735
|
+
if (hadAgentPreset) this.#agentPresets[id] = previousAgentPreset;
|
|
736
|
+
else delete this.#agentPresets[id];
|
|
737
|
+
this.#generations.delete(id);
|
|
738
|
+
this.#incarnations.delete(id);
|
|
739
|
+
}
|
|
740
|
+
throw error;
|
|
741
|
+
}
|
|
742
|
+
this.#accessPolicies = nextAccessPolicies;
|
|
743
|
+
this.#version = nextVersion;
|
|
744
|
+
} else if (!this.#generations.has(id)) {
|
|
745
|
+
this.#generations.set(id, this.#freshGeneration());
|
|
746
|
+
}
|
|
747
|
+
return this.#workspaces[id];
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
async setWorkspace(botId, value, { clearSessions, incarnation } = {}) {
|
|
752
|
+
const id = botIdOf(botId);
|
|
753
|
+
if (!this.has(id)
|
|
754
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
755
|
+
const error = new Error('找不到要修改的机器人。');
|
|
756
|
+
error.code = 'workspace-bot-not-found';
|
|
757
|
+
throw error;
|
|
758
|
+
}
|
|
759
|
+
const workspace = await validateWorkspacePath(value, { ungroupedWorkspace: this.#ungroupedWorkspace });
|
|
760
|
+
return this.#enqueue(id, async () => {
|
|
761
|
+
if (!this.has(id)
|
|
762
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
763
|
+
const error = new Error('找不到要修改的机器人。');
|
|
764
|
+
error.code = 'workspace-bot-not-found';
|
|
765
|
+
throw error;
|
|
766
|
+
}
|
|
767
|
+
if (workspace === this.workspaceFor(id)) return workspace;
|
|
768
|
+
const previous = this.#workspaces[id];
|
|
769
|
+
// Advance first so a session creation that started before this queued
|
|
770
|
+
// transition can never be written back after the clear.
|
|
771
|
+
this.#generations.set(id, this.#freshGeneration());
|
|
772
|
+
// Clear the old session mapping before publishing the new workspace.
|
|
773
|
+
// A crash can then lose conversation continuity, but can never pair the
|
|
774
|
+
// new workspace with sessions created in the old one.
|
|
775
|
+
await clearSessions?.();
|
|
776
|
+
this.#workspaces[id] = workspace;
|
|
777
|
+
try {
|
|
778
|
+
await this.#persist();
|
|
779
|
+
} catch (error) {
|
|
780
|
+
this.#workspaces[id] = previous;
|
|
781
|
+
throw error;
|
|
782
|
+
}
|
|
783
|
+
return workspace;
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
async setConversationWorkspace(botId, conversationKey, value, {
|
|
788
|
+
clearSession,
|
|
789
|
+
incarnation,
|
|
790
|
+
} = {}) {
|
|
791
|
+
const id = botIdOf(botId);
|
|
792
|
+
if (typeof conversationKey !== 'string' || !conversationKey
|
|
793
|
+
|| conversationKey.length > 1_024 || conversationKey.trim() !== conversationKey
|
|
794
|
+
|| /[\u0000-\u001f\u007f]/u.test(conversationKey)) {
|
|
795
|
+
throw new TypeError('conversationKey is required');
|
|
796
|
+
}
|
|
797
|
+
if (!this.has(id)
|
|
798
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
799
|
+
const error = new Error('找不到要修改的机器人。');
|
|
800
|
+
error.code = 'workspace-bot-not-found';
|
|
801
|
+
throw error;
|
|
802
|
+
}
|
|
803
|
+
const token = this.publishConversationWorkspaceSwitch(id, conversationKey);
|
|
804
|
+
return this.applyConversationWorkspaceSwitch(id, conversationKey, value, {
|
|
805
|
+
token,
|
|
806
|
+
clearSession,
|
|
807
|
+
incarnation,
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
async setAgentPreset(botId, value, { incarnation } = {}) {
|
|
812
|
+
const id = botIdOf(botId);
|
|
813
|
+
if (!this.has(id)
|
|
814
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
815
|
+
const error = new Error('找不到要修改的机器人。');
|
|
816
|
+
error.code = 'workspace-bot-not-found';
|
|
817
|
+
throw error;
|
|
818
|
+
}
|
|
819
|
+
const agentPreset = validateAgentPresetId(value);
|
|
820
|
+
return this.#enqueue(id, async () => {
|
|
821
|
+
if (!this.has(id)
|
|
822
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
823
|
+
const error = new Error('找不到要修改的机器人。');
|
|
824
|
+
error.code = 'workspace-bot-not-found';
|
|
825
|
+
throw error;
|
|
826
|
+
}
|
|
827
|
+
const previous = this.#agentPresets[id] ?? null;
|
|
828
|
+
if (previous === agentPreset) return agentPreset;
|
|
829
|
+
if (agentPreset) this.#agentPresets[id] = agentPreset;
|
|
830
|
+
else delete this.#agentPresets[id];
|
|
831
|
+
try {
|
|
832
|
+
await this.#persist();
|
|
833
|
+
} catch (error) {
|
|
834
|
+
if (previous) this.#agentPresets[id] = previous;
|
|
835
|
+
else delete this.#agentPresets[id];
|
|
836
|
+
throw error;
|
|
837
|
+
}
|
|
838
|
+
return agentPreset;
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
async setModel(botId, value, { incarnation } = {}) {
|
|
843
|
+
const id = botIdOf(botId);
|
|
844
|
+
if (!this.has(id)
|
|
845
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
846
|
+
const error = new Error('找不到要修改的机器人。');
|
|
847
|
+
error.code = 'workspace-bot-not-found';
|
|
848
|
+
throw error;
|
|
849
|
+
}
|
|
850
|
+
const model = validateModelSelection(value);
|
|
851
|
+
return this.#enqueue(id, async () => {
|
|
852
|
+
if (!this.has(id)
|
|
853
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
854
|
+
const error = new Error('找不到要修改的机器人。');
|
|
855
|
+
error.code = 'workspace-bot-not-found';
|
|
856
|
+
throw error;
|
|
857
|
+
}
|
|
858
|
+
const previous = this.#models[id] ?? null;
|
|
859
|
+
if (sameModelSelection(previous, model)) return model ? { ...model } : null;
|
|
860
|
+
if (model) this.#models[id] = model;
|
|
861
|
+
else delete this.#models[id];
|
|
862
|
+
try {
|
|
863
|
+
await this.#persist();
|
|
864
|
+
} catch (error) {
|
|
865
|
+
if (previous) this.#models[id] = previous;
|
|
866
|
+
else delete this.#models[id];
|
|
867
|
+
throw error;
|
|
868
|
+
}
|
|
869
|
+
return model ? { ...model } : null;
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
async setAlias(botId, value, { incarnation } = {}) {
|
|
874
|
+
const id = botIdOf(botId);
|
|
875
|
+
const expectedIncarnation = incarnation === undefined ? this.incarnationFor(id) : incarnation;
|
|
876
|
+
const alias = validateBotAlias(value);
|
|
877
|
+
return this.#enqueue(id, async () => {
|
|
878
|
+
if (!this.has(id) || expectedIncarnation !== this.incarnationFor(id)) {
|
|
879
|
+
const error = new Error('找不到要修改的机器人。');
|
|
880
|
+
error.code = 'workspace-bot-not-found';
|
|
881
|
+
throw error;
|
|
882
|
+
}
|
|
883
|
+
const next = { ...this.#aliases };
|
|
884
|
+
if (alias) next[id] = alias;
|
|
885
|
+
else delete next[id];
|
|
886
|
+
await this.#persist(this.#contextEnhancement, this.#deliveryTargets,
|
|
887
|
+
this.#version, this.#accessPolicies, next);
|
|
888
|
+
this.#aliases = next;
|
|
889
|
+
return alias;
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
async setContextEnhancement(botId, value, { incarnation } = {}) {
|
|
894
|
+
const id = botIdOf(botId);
|
|
895
|
+
const expectedIncarnation = incarnation === undefined ? this.incarnationFor(id) : incarnation;
|
|
896
|
+
const config = validateContextEnhancementConfig(value);
|
|
897
|
+
return this.#enqueue(id, async () => {
|
|
898
|
+
if (!this.has(id) || expectedIncarnation !== this.incarnationFor(id)) {
|
|
899
|
+
const error = new Error('找不到要修改的机器人。');
|
|
900
|
+
error.code = 'workspace-bot-not-found';
|
|
901
|
+
throw error;
|
|
902
|
+
}
|
|
903
|
+
const next = { ...this.#contextEnhancement, [id]: config };
|
|
904
|
+
// Messages keep the previous committed snapshot until rename succeeds.
|
|
905
|
+
await this.#persist(next);
|
|
906
|
+
this.#contextEnhancement = next;
|
|
907
|
+
return config;
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
async setAccessPolicy(botId, value, { incarnation } = {}) {
|
|
912
|
+
const id = botIdOf(botId);
|
|
913
|
+
const expectedIncarnation = incarnation === undefined ? this.incarnationFor(id) : incarnation;
|
|
914
|
+
const policy = validateAccessPolicy(value);
|
|
915
|
+
return this.#enqueue(id, async () => {
|
|
916
|
+
if (!this.has(id) || expectedIncarnation !== this.incarnationFor(id)) {
|
|
917
|
+
const error = new Error('找不到要修改的机器人。');
|
|
918
|
+
error.code = 'workspace-bot-not-found';
|
|
919
|
+
throw error;
|
|
920
|
+
}
|
|
921
|
+
const next = { ...this.#accessPolicies, [id]: policy };
|
|
922
|
+
// Inbound messages keep the previous committed snapshot until rename succeeds.
|
|
923
|
+
await this.#persist(
|
|
924
|
+
this.#contextEnhancement,
|
|
925
|
+
this.#deliveryTargets,
|
|
926
|
+
Math.max(this.#version, DELIVERY_DOCUMENT_VERSION),
|
|
927
|
+
next,
|
|
928
|
+
);
|
|
929
|
+
this.#accessPolicies = next;
|
|
930
|
+
this.#version = Math.max(this.#version, DELIVERY_DOCUMENT_VERSION);
|
|
931
|
+
return policy;
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* Publish the fence for a conversation-level switch before its asynchronous
|
|
937
|
+
* work starts. Every session that was resolved for this conversation is
|
|
938
|
+
* invalidated from this moment on: a bind or prompt already in flight must
|
|
939
|
+
* not keep running (or be written back) in the workspace being left behind.
|
|
940
|
+
* Returns the opaque token that applyConversationWorkspaceSwitch requires, so
|
|
941
|
+
* two overlapping switches cannot adopt each other's fence.
|
|
942
|
+
*/
|
|
943
|
+
publishConversationWorkspaceSwitch(botId, conversationKey) {
|
|
944
|
+
const id = botIdOf(botId);
|
|
945
|
+
conversationKeyOf(conversationKey);
|
|
946
|
+
const token = this.#freshConversationGeneration();
|
|
947
|
+
this.#conversationGenerations.set(
|
|
948
|
+
conversationWorkspaceGenerationKey(id, conversationKey),
|
|
949
|
+
token,
|
|
950
|
+
);
|
|
951
|
+
return token;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
/** True while this token is still the current fence for the conversation. */
|
|
955
|
+
isConversationWorkspaceSwitchCurrent(botId, conversationKey, token) {
|
|
956
|
+
const id = botIdOf(botId);
|
|
957
|
+
conversationKeyOf(conversationKey);
|
|
958
|
+
return this.#conversationGenerations.get(
|
|
959
|
+
conversationWorkspaceGenerationKey(id, conversationKey),
|
|
960
|
+
) === token;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
async applyConversationWorkspaceSwitch(botId, conversationKey, value, {
|
|
964
|
+
token,
|
|
965
|
+
clearSession,
|
|
966
|
+
sessionMatchesWorkspace,
|
|
967
|
+
incarnation,
|
|
968
|
+
} = {}) {
|
|
969
|
+
const id = botIdOf(botId);
|
|
970
|
+
const key = conversationKeyOf(conversationKey);
|
|
971
|
+
if (typeof token !== 'number') throw new TypeError('token is required');
|
|
972
|
+
if (!this.has(id)
|
|
973
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
974
|
+
const error = new Error('找不到要修改的机器人。');
|
|
975
|
+
error.code = 'workspace-bot-not-found';
|
|
976
|
+
throw error;
|
|
977
|
+
}
|
|
978
|
+
// Validate before queueing so an invalid path fails without disturbing the
|
|
979
|
+
// conversation's current workspace or its session.
|
|
980
|
+
const workspace = value === null ? null : await validateWorkspacePath(value, {
|
|
981
|
+
ungroupedWorkspace: this.#ungroupedWorkspace,
|
|
982
|
+
});
|
|
983
|
+
return this.#enqueue(id, async () => {
|
|
984
|
+
const assertCurrentSwitch = () => {
|
|
985
|
+
if (!this.has(id)
|
|
986
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
987
|
+
const error = new Error('找不到要修改的机器人。');
|
|
988
|
+
error.code = 'workspace-bot-not-found';
|
|
989
|
+
throw error;
|
|
990
|
+
}
|
|
991
|
+
if (!this.isConversationWorkspaceSwitchCurrent(id, key, token)) {
|
|
992
|
+
throw workspaceSessionStale(
|
|
993
|
+
'The conversation workspace changed before this switch could be committed.',
|
|
994
|
+
);
|
|
995
|
+
}
|
|
996
|
+
};
|
|
997
|
+
assertCurrentSwitch();
|
|
998
|
+
if (workspace === null) {
|
|
999
|
+
await ensureImWorkspaceDirectory(this.workspaceFor(id), this.#ungroupedWorkspace);
|
|
1000
|
+
assertCurrentSwitch();
|
|
1001
|
+
}
|
|
1002
|
+
const previousOverrides = this.#conversationWorkspaces[id];
|
|
1003
|
+
const previous = previousOverrides?.[key];
|
|
1004
|
+
const hadOverride = Boolean(previousOverrides)
|
|
1005
|
+
&& Object.hasOwn(previousOverrides, key);
|
|
1006
|
+
if (workspace === null ? !hadOverride : (hadOverride && previous === workspace)) {
|
|
1007
|
+
// The override may be unchanged while a binding persisted by an older
|
|
1008
|
+
// version still points elsewhere. Only preserve a verified matching
|
|
1009
|
+
// Session; never acknowledge /conv while keeping a foreign cwd.
|
|
1010
|
+
const matches = await sessionMatchesWorkspace?.(this.conversationWorkspaceFor(id, key));
|
|
1011
|
+
assertCurrentSwitch();
|
|
1012
|
+
if (matches === false) {
|
|
1013
|
+
await clearSession?.();
|
|
1014
|
+
assertCurrentSwitch();
|
|
1015
|
+
}
|
|
1016
|
+
return this.conversationWorkspaceFor(id, key);
|
|
1017
|
+
}
|
|
1018
|
+
const next = workspace === null
|
|
1019
|
+
? (() => {
|
|
1020
|
+
const overrides = { ...previousOverrides };
|
|
1021
|
+
delete overrides[key];
|
|
1022
|
+
return overrides;
|
|
1023
|
+
})()
|
|
1024
|
+
: { ...previousOverrides, [key]: workspace };
|
|
1025
|
+
await clearSession?.();
|
|
1026
|
+
assertCurrentSwitch();
|
|
1027
|
+
if (Object.keys(next).length > 0) this.#conversationWorkspaces[id] = next;
|
|
1028
|
+
else delete this.#conversationWorkspaces[id];
|
|
1029
|
+
try {
|
|
1030
|
+
// Binding a conversation to its own current default is still persisted:
|
|
1031
|
+
// a later bot-default change must not move a conversation that pinned
|
|
1032
|
+
// the workspace it was using.
|
|
1033
|
+
await this.#persist();
|
|
1034
|
+
} catch (error) {
|
|
1035
|
+
if (Object.keys(next).length > 0 || hadOverride) {
|
|
1036
|
+
this.#conversationWorkspaces[id] = {
|
|
1037
|
+
...(previousOverrides ?? {}),
|
|
1038
|
+
...(hadOverride ? { [key]: previous } : {}),
|
|
1039
|
+
};
|
|
1040
|
+
} else {
|
|
1041
|
+
delete this.#conversationWorkspaces[id];
|
|
1042
|
+
}
|
|
1043
|
+
throw error;
|
|
1044
|
+
}
|
|
1045
|
+
return this.conversationWorkspaceFor(id, key);
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
async bindWorkspaceSession(botId, value, {
|
|
1050
|
+
conversationKey,
|
|
1051
|
+
sessionId,
|
|
1052
|
+
clearSessions,
|
|
1053
|
+
clearSession,
|
|
1054
|
+
setSession,
|
|
1055
|
+
onConversationGeneration,
|
|
1056
|
+
incarnation,
|
|
1057
|
+
expectedGeneration,
|
|
1058
|
+
expectedConversationGeneration,
|
|
1059
|
+
} = {}) {
|
|
1060
|
+
const id = botIdOf(botId);
|
|
1061
|
+
if (typeof conversationKey !== 'string' || !conversationKey
|
|
1062
|
+
|| typeof sessionId !== 'string' || !sessionId) {
|
|
1063
|
+
throw new TypeError('conversationKey and sessionId are required');
|
|
1064
|
+
}
|
|
1065
|
+
if (typeof clearSessions !== 'function' || typeof setSession !== 'function') {
|
|
1066
|
+
throw new TypeError('session state callbacks are required');
|
|
1067
|
+
}
|
|
1068
|
+
if (!this.has(id)
|
|
1069
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
1070
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1071
|
+
error.code = 'workspace-bot-not-found';
|
|
1072
|
+
throw error;
|
|
1073
|
+
}
|
|
1074
|
+
// Capture before any asynchronous lookup, unless the caller already captured
|
|
1075
|
+
// the fence before adopting the Session.
|
|
1076
|
+
let conversationGeneration = expectedConversationGeneration === undefined
|
|
1077
|
+
? this.conversationGenerationFor(id, conversationKey)
|
|
1078
|
+
: expectedConversationGeneration;
|
|
1079
|
+
const assertConversationCurrent = () => {
|
|
1080
|
+
if (conversationGeneration !== this.conversationGenerationFor(id, conversationKey)) {
|
|
1081
|
+
throw workspaceSessionStale(
|
|
1082
|
+
'The conversation workspace changed before the session binding could be committed.',
|
|
1083
|
+
);
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1086
|
+
const workspace = await canonicalWorkspacePath(await validateWorkspacePath(value, {
|
|
1087
|
+
ungroupedWorkspace: this.#ungroupedWorkspace,
|
|
1088
|
+
}));
|
|
1089
|
+
return this.#enqueue(id, async () => {
|
|
1090
|
+
if (!this.has(id)
|
|
1091
|
+
|| (incarnation !== undefined && incarnation !== this.incarnationFor(id))) {
|
|
1092
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1093
|
+
error.code = 'workspace-bot-not-found';
|
|
1094
|
+
throw error;
|
|
1095
|
+
}
|
|
1096
|
+
if (expectedGeneration !== undefined
|
|
1097
|
+
&& expectedGeneration !== this.generationFor(id)) {
|
|
1098
|
+
throw workspaceSessionStale(
|
|
1099
|
+
'The bot workspace changed before the session binding could be committed.',
|
|
1100
|
+
);
|
|
1101
|
+
}
|
|
1102
|
+
// An explicit session binding is also a conversation-level statement: a
|
|
1103
|
+
// workspace switch queued while the session was being adopted must not be
|
|
1104
|
+
// silently overwritten by the binding that started before it.
|
|
1105
|
+
assertConversationCurrent();
|
|
1106
|
+
const sameWorkspace = await sameWorkspacePath(workspace, this.workspaceFor(id));
|
|
1107
|
+
const previousOverrides = this.#conversationWorkspaces[id];
|
|
1108
|
+
const override = previousOverrides?.[conversationKey];
|
|
1109
|
+
const clearsOverride = override !== undefined && !(await sameWorkspacePath(workspace, override));
|
|
1110
|
+
assertConversationCurrent();
|
|
1111
|
+
if (!sameWorkspace || clearsOverride) {
|
|
1112
|
+
if (sameWorkspace && typeof clearSession !== 'function') {
|
|
1113
|
+
throw new TypeError('clearSession is required to reconcile a conversation workspace');
|
|
1114
|
+
}
|
|
1115
|
+
const previous = this.#workspaces[id];
|
|
1116
|
+
if (clearsOverride) {
|
|
1117
|
+
// /session keeps its bot-default semantics, but cannot leave this
|
|
1118
|
+
// conversation pinned to a different cwd from the adopted Session.
|
|
1119
|
+
// Publish the new fence to the scope before any asynchronous work.
|
|
1120
|
+
conversationGeneration = this.publishConversationWorkspaceSwitch(id, conversationKey);
|
|
1121
|
+
onConversationGeneration?.(conversationGeneration);
|
|
1122
|
+
}
|
|
1123
|
+
if (!sameWorkspace) {
|
|
1124
|
+
this.#generations.set(id, this.#freshGeneration());
|
|
1125
|
+
await clearSessions();
|
|
1126
|
+
} else {
|
|
1127
|
+
await clearSession(conversationKey);
|
|
1128
|
+
}
|
|
1129
|
+
assertConversationCurrent();
|
|
1130
|
+
if (!sameWorkspace) this.#workspaces[id] = workspace;
|
|
1131
|
+
if (clearsOverride) {
|
|
1132
|
+
const next = { ...previousOverrides };
|
|
1133
|
+
delete next[conversationKey];
|
|
1134
|
+
if (Object.keys(next).length) this.#conversationWorkspaces[id] = next;
|
|
1135
|
+
else delete this.#conversationWorkspaces[id];
|
|
1136
|
+
}
|
|
1137
|
+
try {
|
|
1138
|
+
await this.#persist();
|
|
1139
|
+
} catch (error) {
|
|
1140
|
+
// Session mappings stay cleared and the advanced generation stays
|
|
1141
|
+
// fenced. Restoring either could pair an old session with a state
|
|
1142
|
+
// transition whose durable outcome is unknown.
|
|
1143
|
+
this.#workspaces[id] = previous;
|
|
1144
|
+
if (clearsOverride) this.#conversationWorkspaces[id] = previousOverrides;
|
|
1145
|
+
throw error;
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
// This write remains inside the same bot transition as the workspace
|
|
1150
|
+
// mutation, so another switch or bind cannot interleave between them.
|
|
1151
|
+
assertConversationCurrent();
|
|
1152
|
+
await setSession(conversationKey, sessionId);
|
|
1153
|
+
assertConversationCurrent();
|
|
1154
|
+
return {
|
|
1155
|
+
workspace,
|
|
1156
|
+
sessionId,
|
|
1157
|
+
generation: this.#generations.get(id),
|
|
1158
|
+
conversationGeneration,
|
|
1159
|
+
};
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
async invalidateSessions(botId, { clearSessions } = {}) {
|
|
1164
|
+
const id = botIdOf(botId);
|
|
1165
|
+
return this.#enqueue(id, async () => {
|
|
1166
|
+
this.#generations.set(id, this.#freshGeneration());
|
|
1167
|
+
await clearSessions?.();
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
/** Fence one lifecycle and return the opaque token required to abort/finish it. */
|
|
1172
|
+
async beginRemoval(botId, { clearSessions } = {}) {
|
|
1173
|
+
const id = botIdOf(botId);
|
|
1174
|
+
return this.#enqueue(id, async () => {
|
|
1175
|
+
const existing = this.#removals.get(id);
|
|
1176
|
+
if (existing) return existing;
|
|
1177
|
+
const transaction = Object.freeze({});
|
|
1178
|
+
this.#removals.set(id, transaction);
|
|
1179
|
+
this.#removalDetails.set(transaction, {
|
|
1180
|
+
botId: id,
|
|
1181
|
+
incarnation: this.incarnationFor(id),
|
|
1182
|
+
});
|
|
1183
|
+
this.#generations.set(id, this.#freshGeneration());
|
|
1184
|
+
try {
|
|
1185
|
+
await clearSessions?.();
|
|
1186
|
+
} catch (error) {
|
|
1187
|
+
if (this.#removals.get(id) === transaction) this.#removals.delete(id);
|
|
1188
|
+
throw error;
|
|
1189
|
+
}
|
|
1190
|
+
return transaction;
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
/** Re-open only the lifecycle represented by transaction; stale tokens are no-ops. */
|
|
1195
|
+
async abortRemoval(transaction) {
|
|
1196
|
+
const { botId: id } = this.#removalDetailsFor(transaction);
|
|
1197
|
+
return this.#enqueue(id, async () => {
|
|
1198
|
+
if (this.#removals.get(id) !== transaction) return false;
|
|
1199
|
+
this.#removals.delete(id);
|
|
1200
|
+
if (Object.hasOwn(this.#workspaces, id)) {
|
|
1201
|
+
this.#generations.set(id, this.#freshGeneration());
|
|
1202
|
+
if (!this.#incarnations.has(id)) {
|
|
1203
|
+
this.#incarnations.set(id, this.#freshIncarnation());
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
return true;
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
/** Retire only the lifecycle represented by transaction; stale tokens are no-ops. */
|
|
1211
|
+
async finishRemoval(transaction) {
|
|
1212
|
+
const { botId: id, incarnation } = this.#removalDetailsFor(transaction);
|
|
1213
|
+
return this.#enqueue(id, async () => {
|
|
1214
|
+
if (this.#removals.get(id) !== transaction) {
|
|
1215
|
+
return { removed: false, persisted: true, error: null, stale: true };
|
|
1216
|
+
}
|
|
1217
|
+
if (this.incarnationFor(id) !== incarnation) {
|
|
1218
|
+
this.#removals.delete(id);
|
|
1219
|
+
return { removed: false, persisted: true, error: null, stale: true };
|
|
1220
|
+
}
|
|
1221
|
+
this.#removals.delete(id);
|
|
1222
|
+
return this.#retireCurrentIncarnation(id);
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
/** Commit the workspace lifecycle after the config store durably removed a bot. */
|
|
1227
|
+
async retireAfterConfigCommit(botId) {
|
|
1228
|
+
const id = botIdOf(botId);
|
|
1229
|
+
return this.#enqueue(id, async () => {
|
|
1230
|
+
this.#removals.delete(id);
|
|
1231
|
+
return this.#retireCurrentIncarnation(id);
|
|
1232
|
+
});
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
/** A failed retirement must reach disk before the same config ID can be rebound. */
|
|
1236
|
+
flushPendingRemoval(botId) {
|
|
1237
|
+
if (!this.#dirtyRemovals.has(botId)) return undefined;
|
|
1238
|
+
return this.#enqueue(botId, async () => {
|
|
1239
|
+
if (this.#dirtyRemovals.has(botId)) await this.#persistCurrentDocument();
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
async remove(botId) {
|
|
1244
|
+
const result = await this.retireAfterConfigCommit(botId);
|
|
1245
|
+
if (result.error) throw result.error;
|
|
1246
|
+
return result.removed;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
async reconcile(activeBotIds) {
|
|
1250
|
+
const active = new Set([...activeBotIds].map(botIdOf));
|
|
1251
|
+
const candidates = new Set([
|
|
1252
|
+
...Object.keys(this.#workspaces),
|
|
1253
|
+
...Object.keys(this.#agentPresets),
|
|
1254
|
+
...Object.keys(this.#models),
|
|
1255
|
+
...Object.keys(this.#aliases),
|
|
1256
|
+
...Object.keys(this.#contextEnhancement),
|
|
1257
|
+
...Object.keys(this.#deliveryTargets),
|
|
1258
|
+
...Object.keys(this.#accessPolicies),
|
|
1259
|
+
...Object.keys(this.#conversationWorkspaces),
|
|
1260
|
+
...this.#dirtyRemovals,
|
|
1261
|
+
]);
|
|
1262
|
+
for (const botId of candidates) {
|
|
1263
|
+
if (!active.has(botId)) await this.remove(botId);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
decorateStatus(status) {
|
|
1268
|
+
if (!status || typeof status !== 'object' || !Array.isArray(status.bots)) return status;
|
|
1269
|
+
return {
|
|
1270
|
+
...status,
|
|
1271
|
+
bots: status.bots.map((bot) => bot?.botId
|
|
1272
|
+
? {
|
|
1273
|
+
...bot,
|
|
1274
|
+
...(this.aliasFor(bot.botId) ? { bot: withBotAlias(bot.bot, this.aliasFor(bot.botId)) } : {}),
|
|
1275
|
+
workspace: this.workspaceFor(bot.botId),
|
|
1276
|
+
agentPreset: this.agentPresetFor(bot.botId),
|
|
1277
|
+
model: this.modelFor(bot.botId),
|
|
1278
|
+
contextEnhancement: this.contextEnhancementFor(bot.botId),
|
|
1279
|
+
accessPolicy: this.accessPolicyFor(bot.botId),
|
|
1280
|
+
}
|
|
1281
|
+
: bot),
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
#freshGeneration() {
|
|
1286
|
+
const generation = this.#nextGeneration;
|
|
1287
|
+
this.#nextGeneration += 1;
|
|
1288
|
+
return generation;
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
#freshIncarnation() {
|
|
1292
|
+
const incarnation = this.#nextIncarnation;
|
|
1293
|
+
this.#nextIncarnation += 1;
|
|
1294
|
+
return incarnation;
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
#freshConversationGeneration() {
|
|
1298
|
+
const generation = this.#nextConversationGeneration;
|
|
1299
|
+
this.#nextConversationGeneration += 1;
|
|
1300
|
+
return generation;
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
#removalDetailsFor(transaction) {
|
|
1304
|
+
if (!transaction || typeof transaction !== 'object') {
|
|
1305
|
+
throw new TypeError('Invalid workspace removal transaction');
|
|
1306
|
+
}
|
|
1307
|
+
const details = this.#removalDetails.get(transaction);
|
|
1308
|
+
if (!details) throw new TypeError('Invalid workspace removal transaction');
|
|
1309
|
+
return details;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
async #retireCurrentIncarnation(id) {
|
|
1313
|
+
const hadWorkspace = Object.hasOwn(this.#workspaces, id);
|
|
1314
|
+
const hadPreset = Object.hasOwn(this.#agentPresets, id);
|
|
1315
|
+
const hadModel = Object.hasOwn(this.#models, id);
|
|
1316
|
+
const hadAlias = Object.hasOwn(this.#aliases, id);
|
|
1317
|
+
const hadContextEnhancement = Object.hasOwn(this.#contextEnhancement, id);
|
|
1318
|
+
const hadDeliveryTargets = Object.hasOwn(this.#deliveryTargets, id);
|
|
1319
|
+
const hadAccessPolicy = Object.hasOwn(this.#accessPolicies, id);
|
|
1320
|
+
const hadConversationWorkspaces = Object.hasOwn(this.#conversationWorkspaces, id);
|
|
1321
|
+
const needsCleanup = hadWorkspace || hadPreset || hadModel || hadAlias || hadContextEnhancement
|
|
1322
|
+
|| hadDeliveryTargets || hadAccessPolicy || hadConversationWorkspaces
|
|
1323
|
+
|| this.#dirtyRemovals.has(id);
|
|
1324
|
+
delete this.#workspaces[id];
|
|
1325
|
+
delete this.#agentPresets[id];
|
|
1326
|
+
delete this.#models[id];
|
|
1327
|
+
delete this.#aliases[id];
|
|
1328
|
+
delete this.#contextEnhancement[id];
|
|
1329
|
+
delete this.#deliveryTargets[id];
|
|
1330
|
+
delete this.#accessPolicies[id];
|
|
1331
|
+
delete this.#conversationWorkspaces[id];
|
|
1332
|
+
this.#generations.delete(id);
|
|
1333
|
+
this.#incarnations.delete(id);
|
|
1334
|
+
if (!needsCleanup) return {
|
|
1335
|
+
removed: false, persisted: true, error: null, stale: false,
|
|
1336
|
+
};
|
|
1337
|
+
try {
|
|
1338
|
+
await this.#persistCurrentDocument();
|
|
1339
|
+
return {
|
|
1340
|
+
removed: hadWorkspace, persisted: true, error: null, stale: false,
|
|
1341
|
+
};
|
|
1342
|
+
} catch (error) {
|
|
1343
|
+
this.#dirtyRemovals.add(id);
|
|
1344
|
+
return {
|
|
1345
|
+
removed: hadWorkspace, persisted: false, error, stale: false,
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
async #enqueue(botId, operation) {
|
|
1351
|
+
const queued = this.#writeQueue.then(operation, operation);
|
|
1352
|
+
const settled = queued.then(() => undefined, () => undefined);
|
|
1353
|
+
this.#writeQueue = settled;
|
|
1354
|
+
this.#botQueues.set(botId, settled);
|
|
1355
|
+
void settled.finally(() => {
|
|
1356
|
+
if (this.#botQueues.get(botId) === settled) this.#botQueues.delete(botId);
|
|
1357
|
+
});
|
|
1358
|
+
return queued;
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
async #persist(
|
|
1362
|
+
contextEnhancement = this.#contextEnhancement,
|
|
1363
|
+
deliveryTargets = this.#deliveryTargets,
|
|
1364
|
+
version = this.#version,
|
|
1365
|
+
accessPolicies = this.#accessPolicies,
|
|
1366
|
+
aliases = this.#aliases,
|
|
1367
|
+
conversationWorkspaces = this.#conversationWorkspaces,
|
|
1368
|
+
) {
|
|
1369
|
+
await writeStoredDocument(this.#path, storedDocument({
|
|
1370
|
+
version,
|
|
1371
|
+
workspaces: this.#workspaces,
|
|
1372
|
+
conversationWorkspaces,
|
|
1373
|
+
agentPresets: this.#agentPresets,
|
|
1374
|
+
models: this.#models,
|
|
1375
|
+
contextEnhancement,
|
|
1376
|
+
deliveryTargets,
|
|
1377
|
+
accessPolicies,
|
|
1378
|
+
aliases,
|
|
1379
|
+
}));
|
|
1380
|
+
this.#dirtyRemovals.clear();
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
async #persistCurrentDocument() {
|
|
1384
|
+
if (Object.keys(this.#workspaces).length > 0
|
|
1385
|
+
|| Object.keys(this.#agentPresets).length > 0
|
|
1386
|
+
|| Object.keys(this.#models).length > 0
|
|
1387
|
+
|| Object.keys(this.#aliases).length > 0
|
|
1388
|
+
|| Object.keys(this.#contextEnhancement).length > 0
|
|
1389
|
+
|| Object.keys(this.#deliveryTargets).length > 0
|
|
1390
|
+
|| Object.keys(this.#accessPolicies).length > 0
|
|
1391
|
+
|| Object.keys(this.#conversationWorkspaces).length > 0) {
|
|
1392
|
+
await this.#persist();
|
|
1393
|
+
return;
|
|
1394
|
+
}
|
|
1395
|
+
try {
|
|
1396
|
+
const parent = await stat(dirname(this.#path));
|
|
1397
|
+
if (!parent.isDirectory()) {
|
|
1398
|
+
const error = new Error('workspace config parent is not a directory');
|
|
1399
|
+
error.code = 'ENOTDIR';
|
|
1400
|
+
throw error;
|
|
1401
|
+
}
|
|
1402
|
+
} catch (error) {
|
|
1403
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
1404
|
+
this.#dirtyRemovals.clear();
|
|
1405
|
+
return;
|
|
1406
|
+
}
|
|
1407
|
+
try {
|
|
1408
|
+
await unlink(this.#path);
|
|
1409
|
+
this.#dirtyRemovals.clear();
|
|
1410
|
+
} catch (error) {
|
|
1411
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
1412
|
+
this.#dirtyRemovals.clear();
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
function resolveAgentPresetCatalog(catalog) {
|
|
1418
|
+
if (!catalog) return null;
|
|
1419
|
+
const value = typeof catalog === 'function' ? catalog() : catalog;
|
|
1420
|
+
return value && typeof value.then === 'function'
|
|
1421
|
+
? value.then(normalizeAgentPresetCatalog)
|
|
1422
|
+
: normalizeAgentPresetCatalog(value);
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
function resolveModelCatalog(catalog) {
|
|
1426
|
+
if (!catalog) return null;
|
|
1427
|
+
const value = typeof catalog === 'function' ? catalog() : catalog;
|
|
1428
|
+
return value && typeof value.then === 'function'
|
|
1429
|
+
? value.then(normalizeModelCatalog)
|
|
1430
|
+
: normalizeModelCatalog(value);
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
function unavailableAgentPreset() {
|
|
1434
|
+
const error = new Error('Agent Preset 不存在或不可用。');
|
|
1435
|
+
error.code = 'agent-preset-unavailable';
|
|
1436
|
+
return error;
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
function unavailableModel() {
|
|
1440
|
+
const error = new Error('模型不存在或不可用。');
|
|
1441
|
+
error.code = 'model-selection-unavailable';
|
|
1442
|
+
return error;
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
function assertCurrentBotScope(isCurrentScope) {
|
|
1446
|
+
if (isCurrentScope()) return;
|
|
1447
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1448
|
+
error.code = 'workspace-bot-not-found';
|
|
1449
|
+
throw error;
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
function decorateResult(workspaces, result, agentPresetCatalogSource, modelCatalogSource) {
|
|
1453
|
+
const decorate = (value) => {
|
|
1454
|
+
const decorated = workspaces.decorateStatus(value);
|
|
1455
|
+
if ((!agentPresetCatalogSource && !modelCatalogSource)
|
|
1456
|
+
|| !decorated || typeof decorated !== 'object') return decorated;
|
|
1457
|
+
const attachCatalogs = ([agentPresetCatalog, modelCatalog]) => ({
|
|
1458
|
+
...decorated,
|
|
1459
|
+
...(agentPresetCatalog ? { agentPresetCatalog } : {}),
|
|
1460
|
+
...(modelCatalog ? { modelCatalog } : {}),
|
|
1461
|
+
});
|
|
1462
|
+
const catalogs = [
|
|
1463
|
+
resolveAgentPresetCatalog(agentPresetCatalogSource),
|
|
1464
|
+
resolveModelCatalog(modelCatalogSource),
|
|
1465
|
+
];
|
|
1466
|
+
return catalogs.some((catalog) => catalog && typeof catalog.then === 'function')
|
|
1467
|
+
? Promise.all(catalogs).then(attachCatalogs)
|
|
1468
|
+
: attachCatalogs(catalogs);
|
|
1469
|
+
};
|
|
1470
|
+
return result && typeof result.then === 'function'
|
|
1471
|
+
? result.then(decorate)
|
|
1472
|
+
: decorate(result);
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
function targetStatus(controller) {
|
|
1476
|
+
return Promise.resolve(controller.status());
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
/** Observe durable removals and finish failed cleanup before a same-ID config save. */
|
|
1480
|
+
export function observeBotWorkspaceRemovals(
|
|
1481
|
+
configStore,
|
|
1482
|
+
{
|
|
1483
|
+
workspaces,
|
|
1484
|
+
method = 'remove',
|
|
1485
|
+
botIdFromRemoved = (removed) => removed?.botId,
|
|
1486
|
+
saveMethod = 'save',
|
|
1487
|
+
botIdFromSave = (config) => config?.botId,
|
|
1488
|
+
},
|
|
1489
|
+
) {
|
|
1490
|
+
if (!configStore || !workspaces || typeof configStore[method] !== 'function') {
|
|
1491
|
+
throw new TypeError('configStore removal observer dependencies are required');
|
|
1492
|
+
}
|
|
1493
|
+
return new Proxy(configStore, {
|
|
1494
|
+
get(target, property) {
|
|
1495
|
+
const value = Reflect.get(target, property, target);
|
|
1496
|
+
if (property === method) {
|
|
1497
|
+
return async (...args) => {
|
|
1498
|
+
const removed = await value.apply(target, args);
|
|
1499
|
+
const botId = removed ? botIdFromRemoved(removed, args) : null;
|
|
1500
|
+
if (botId) {
|
|
1501
|
+
const cleanup = await atConnectionStage('workspace.cleanup', () => workspaces.retireAfterConfigCommit(botId), 'workspace-config');
|
|
1502
|
+
if (cleanup?.error) throw connectionStageError(cleanup.error, 'workspace.cleanup', 'workspace-config');
|
|
1503
|
+
}
|
|
1504
|
+
return removed;
|
|
1505
|
+
};
|
|
1506
|
+
}
|
|
1507
|
+
if (property === saveMethod && typeof value === 'function') {
|
|
1508
|
+
return (...args) => {
|
|
1509
|
+
const cleanup = workspaces.flushPendingRemoval(botIdFromSave(args[0], args));
|
|
1510
|
+
return cleanup ? cleanup.then(() => value.apply(target, args)) : value.apply(target, args);
|
|
1511
|
+
};
|
|
1512
|
+
}
|
|
1513
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
1514
|
+
},
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
export function createBotWorkspaceScope(
|
|
1519
|
+
harness,
|
|
1520
|
+
{ botId, workspaces, state, agentPresetCatalog } = {},
|
|
1521
|
+
) {
|
|
1522
|
+
if (!harness || !workspaces || !state) throw new TypeError('harness, workspaces, and state are required');
|
|
1523
|
+
const incarnation = workspaces.incarnationFor(botId);
|
|
1524
|
+
const isCurrentScope = () => workspaces.has(botId)
|
|
1525
|
+
&& workspaces.incarnationFor(botId) === incarnation;
|
|
1526
|
+
const presetSettings = async (catalog = agentPresetCatalog) => {
|
|
1527
|
+
let normalizedCatalog;
|
|
1528
|
+
try {
|
|
1529
|
+
normalizedCatalog = await resolveAgentPresetCatalog(catalog)
|
|
1530
|
+
?? normalizeAgentPresetCatalog(null);
|
|
1531
|
+
} catch (error) {
|
|
1532
|
+
assertCurrentBotScope(isCurrentScope);
|
|
1533
|
+
throw error;
|
|
1534
|
+
}
|
|
1535
|
+
assertCurrentBotScope(isCurrentScope);
|
|
1536
|
+
return {
|
|
1537
|
+
agentPreset: workspaces.agentPresetFor(botId),
|
|
1538
|
+
agentPresetCatalog: normalizedCatalog,
|
|
1539
|
+
};
|
|
1540
|
+
};
|
|
1541
|
+
const sessionGenerations = new Map();
|
|
1542
|
+
// A conversation-level switch/clear publishes an opaque mask token before it
|
|
1543
|
+
// starts its asynchronous work, so a bind or prompt that was already resolved
|
|
1544
|
+
// for that conversation is rejected instead of running in the old workspace.
|
|
1545
|
+
// The store keeps the same token as the conversation's generation, so the
|
|
1546
|
+
// scope marker and the durable generation never disagree.
|
|
1547
|
+
const conversationSwitchMasks = new Map();
|
|
1548
|
+
// The in-flight switch of each conversation, so a message that starts while
|
|
1549
|
+
// /conv is still committing waits for the new workspace instead of resolving
|
|
1550
|
+
// a session in the old one.
|
|
1551
|
+
const pendingConversationSwitches = new Map();
|
|
1552
|
+
|
|
1553
|
+
function trackConversationSwitch(conversationKey, promise) {
|
|
1554
|
+
pendingConversationSwitches.set(conversationKey, promise);
|
|
1555
|
+
return promise.finally(() => {
|
|
1556
|
+
if (pendingConversationSwitches.get(conversationKey) === promise) {
|
|
1557
|
+
pendingConversationSwitches.delete(conversationKey);
|
|
1558
|
+
if (isCurrentScope()) refreshRetainedSession(conversationKey);
|
|
1559
|
+
}
|
|
1560
|
+
});
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
function currentConversationGeneration(conversationKey) {
|
|
1564
|
+
// The store reports "no override recorded yet" as null; map it to an opaque
|
|
1565
|
+
// token so "before the first switch" is still a comparable state.
|
|
1566
|
+
const generation = workspaces.conversationGenerationFor(botId, conversationKey);
|
|
1567
|
+
return generation ?? 0;
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
function maskConversationSwitch(conversationKey, token) {
|
|
1571
|
+
if (!conversationKey) return;
|
|
1572
|
+
conversationSwitchMasks.set(
|
|
1573
|
+
conversationKey,
|
|
1574
|
+
token === undefined ? currentConversationGeneration(conversationKey) : token,
|
|
1575
|
+
);
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
function conversationGenerationIsStale(conversationKey, expected) {
|
|
1579
|
+
if (typeof conversationKey !== 'string' || !conversationKey) return false;
|
|
1580
|
+
const mask = conversationSwitchMasks.get(conversationKey);
|
|
1581
|
+
if (mask !== undefined && mask !== currentConversationGeneration(conversationKey)) {
|
|
1582
|
+
return true;
|
|
1583
|
+
}
|
|
1584
|
+
if (expected === undefined) return false;
|
|
1585
|
+
return expected !== currentConversationGeneration(conversationKey);
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
function generationIsStale(entry, conversationKey = entry?.conversationKey) {
|
|
1589
|
+
return Boolean(entry)
|
|
1590
|
+
&& ((entry.generation !== undefined && entry.generation !== workspaces.generationFor(botId))
|
|
1591
|
+
|| (entry.conversationKey === conversationKey
|
|
1592
|
+
&& conversationGenerationIsStale(conversationKey, entry.conversationGeneration)));
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
/**
|
|
1596
|
+
* Refresh provenance only for a mapping that survived an unchanged/failed
|
|
1597
|
+
* switch. Removed mappings and pending creates retain their old fence, so a
|
|
1598
|
+
* delayed setSession cannot resurrect them after the switch finishes.
|
|
1599
|
+
*/
|
|
1600
|
+
function refreshRetainedSession(conversationKey) {
|
|
1601
|
+
const sessionId = state.sessionFor?.(conversationKey);
|
|
1602
|
+
const entry = sessionGenerations.get(sessionId);
|
|
1603
|
+
if (entry?.conversationKey === conversationKey
|
|
1604
|
+
&& entry.generation === workspaces.generationFor(botId)) {
|
|
1605
|
+
sessionGenerations.set(sessionId, {
|
|
1606
|
+
...entry,
|
|
1607
|
+
conversationGeneration: currentConversationGeneration(conversationKey),
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
async function conversationSessionMatchesWorkspace(conversationKey, workspace) {
|
|
1613
|
+
const sessionId = state.sessionFor?.(conversationKey);
|
|
1614
|
+
if (!sessionId) return true;
|
|
1615
|
+
let sessionWorkspace = sessionGenerations.get(sessionId)?.workspace;
|
|
1616
|
+
let matches = false;
|
|
1617
|
+
let unregistered = true;
|
|
1618
|
+
if (!sessionWorkspace && typeof harness.rpc === 'function') {
|
|
1619
|
+
// Read registration metadata only: adopting a Session is not a lookup.
|
|
1620
|
+
// Resolve by id before comparing real paths so symlink pins remain valid.
|
|
1621
|
+
const listed = await harness.rpc('workspace.list', {}, 30_000);
|
|
1622
|
+
if (!Array.isArray(listed?.items)) {
|
|
1623
|
+
throw new TypeError('Harness returned an invalid workspace list');
|
|
1624
|
+
}
|
|
1625
|
+
const owners = listed.items.filter((item) => Array.isArray(item?.sessionIds)
|
|
1626
|
+
&& item.sessionIds.includes(sessionId));
|
|
1627
|
+
if (owners.length === 1 && typeof owners[0].path === 'string' && isAbsolute(owners[0].path)) {
|
|
1628
|
+
sessionWorkspace = owners[0].path;
|
|
1629
|
+
}
|
|
1630
|
+
unregistered = owners.length === 0;
|
|
1631
|
+
}
|
|
1632
|
+
if (!sessionWorkspace && unregistered && typeof harness.listWorkspaceSessions === 'function') {
|
|
1633
|
+
// After a restart, default IM sessions have no registry owner. Reuse
|
|
1634
|
+
// the read-only list, which also recognizes ungrouped default sessions.
|
|
1635
|
+
const listed = await harness.listWorkspaceSessions(await canonicalWorkspacePath(workspace));
|
|
1636
|
+
if (!Array.isArray(listed?.sessions)) {
|
|
1637
|
+
throw new TypeError('Harness returned an invalid workspace session list');
|
|
1638
|
+
}
|
|
1639
|
+
matches = listed.sessions.some((session) => session?.sessionId === sessionId);
|
|
1640
|
+
}
|
|
1641
|
+
if (sessionWorkspace) matches = await sameWorkspacePath(sessionWorkspace, workspace);
|
|
1642
|
+
if (state.sessionFor(conversationKey) !== sessionId) {
|
|
1643
|
+
throw workspaceSessionStale('The session binding changed while its workspace was being checked.');
|
|
1644
|
+
}
|
|
1645
|
+
return matches;
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
const scopedHarness = new Proxy(harness, {
|
|
1649
|
+
get(target, property) {
|
|
1650
|
+
if (property === 'agentPresetSettings') {
|
|
1651
|
+
return async (options = {}) => {
|
|
1652
|
+
options?.signal?.throwIfAborted();
|
|
1653
|
+
assertCurrentBotScope(isCurrentScope);
|
|
1654
|
+
const settings = await presetSettings();
|
|
1655
|
+
options?.signal?.throwIfAborted();
|
|
1656
|
+
return settings;
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
if (property === 'updateAgentPreset') {
|
|
1660
|
+
return async (value, options = {}) => {
|
|
1661
|
+
options?.signal?.throwIfAborted();
|
|
1662
|
+
assertCurrentBotScope(isCurrentScope);
|
|
1663
|
+
const agentPreset = value === '--default' ? null : validateAgentPresetId(value);
|
|
1664
|
+
let catalog = null;
|
|
1665
|
+
if (agentPreset) {
|
|
1666
|
+
({ agentPresetCatalog: catalog } = await presetSettings());
|
|
1667
|
+
options?.signal?.throwIfAborted();
|
|
1668
|
+
if (!catalog.items.some((item) => item.id === agentPreset)) {
|
|
1669
|
+
throw unavailableAgentPreset();
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
await workspaces.setAgentPreset(botId, agentPreset, { incarnation });
|
|
1673
|
+
assertCurrentBotScope(isCurrentScope);
|
|
1674
|
+
if (catalog) {
|
|
1675
|
+
return {
|
|
1676
|
+
agentPreset: workspaces.agentPresetFor(botId),
|
|
1677
|
+
agentPresetCatalog: catalog,
|
|
1678
|
+
};
|
|
1679
|
+
}
|
|
1680
|
+
try {
|
|
1681
|
+
return await presetSettings();
|
|
1682
|
+
} catch (error) {
|
|
1683
|
+
if (error?.code === 'workspace-bot-not-found') throw error;
|
|
1684
|
+
assertCurrentBotScope(isCurrentScope);
|
|
1685
|
+
return {
|
|
1686
|
+
agentPreset: workspaces.agentPresetFor(botId),
|
|
1687
|
+
agentPresetCatalog: normalizeAgentPresetCatalog(null),
|
|
1688
|
+
};
|
|
1689
|
+
}
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
if (property === 'currentWorkspace') {
|
|
1693
|
+
return () => {
|
|
1694
|
+
if (!isCurrentScope()) {
|
|
1695
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1696
|
+
error.code = 'workspace-bot-not-found';
|
|
1697
|
+
throw error;
|
|
1698
|
+
}
|
|
1699
|
+
return workspaces.workspaceFor(botId);
|
|
1700
|
+
};
|
|
1701
|
+
}
|
|
1702
|
+
if (property === 'assertWorkspaceScope') {
|
|
1703
|
+
return () => {
|
|
1704
|
+
if (!isCurrentScope()) {
|
|
1705
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1706
|
+
error.code = 'workspace-bot-not-found';
|
|
1707
|
+
throw error;
|
|
1708
|
+
}
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
if ((property === 'listWorkspaces'
|
|
1712
|
+
|| property === 'listWorkspaceSessions'
|
|
1713
|
+
|| property === 'listModels')
|
|
1714
|
+
&& typeof target[property] === 'function') {
|
|
1715
|
+
return async (...args) => {
|
|
1716
|
+
if (!isCurrentScope()) {
|
|
1717
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1718
|
+
error.code = 'workspace-bot-not-found';
|
|
1719
|
+
throw error;
|
|
1720
|
+
}
|
|
1721
|
+
const result = await target[property](...args);
|
|
1722
|
+
if (!isCurrentScope()) {
|
|
1723
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1724
|
+
error.code = 'workspace-bot-not-found';
|
|
1725
|
+
throw error;
|
|
1726
|
+
}
|
|
1727
|
+
return result;
|
|
1728
|
+
};
|
|
1729
|
+
}
|
|
1730
|
+
if (property === 'switchWorkspace') {
|
|
1731
|
+
return (workspace) => {
|
|
1732
|
+
if (!isCurrentScope()) {
|
|
1733
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1734
|
+
error.code = 'workspace-bot-not-found';
|
|
1735
|
+
return Promise.reject(error);
|
|
1736
|
+
}
|
|
1737
|
+
return workspaces.setWorkspace(botId, workspace, {
|
|
1738
|
+
clearSessions: () => state.clearSessions(),
|
|
1739
|
+
incarnation,
|
|
1740
|
+
});
|
|
1741
|
+
};
|
|
1742
|
+
}
|
|
1743
|
+
if (property === 'currentConversationWorkspace') {
|
|
1744
|
+
return (conversationKey) => {
|
|
1745
|
+
if (!isCurrentScope()) {
|
|
1746
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1747
|
+
error.code = 'workspace-bot-not-found';
|
|
1748
|
+
throw error;
|
|
1749
|
+
}
|
|
1750
|
+
return workspaces.conversationWorkspaceFor(botId, conversationKey);
|
|
1751
|
+
};
|
|
1752
|
+
}
|
|
1753
|
+
if (property === 'hasConversationWorkspaceOverride') {
|
|
1754
|
+
return (conversationKey) => {
|
|
1755
|
+
assertCurrentBotScope(isCurrentScope);
|
|
1756
|
+
return workspaces.hasConversationWorkspaceOverride(botId, conversationKey);
|
|
1757
|
+
};
|
|
1758
|
+
}
|
|
1759
|
+
if (property === 'pendingConversationWorkspaceSwitch') {
|
|
1760
|
+
// Read-only: callers in the message path wait for a switch that is
|
|
1761
|
+
// still committing before they resolve a session for this conversation.
|
|
1762
|
+
return (conversationKey) => pendingConversationSwitches.get(conversationKey) ?? null;
|
|
1763
|
+
}
|
|
1764
|
+
if (property === 'conversationWorkspaceGeneration') {
|
|
1765
|
+
// Read-only fence token for the conversation's effective workspace.
|
|
1766
|
+
// Callers outside this scope (message bridging) compare it across the
|
|
1767
|
+
// bind and the send so a late switch cannot be outrun.
|
|
1768
|
+
return (conversationKey) => currentConversationGeneration(conversationKey);
|
|
1769
|
+
}
|
|
1770
|
+
if (property === 'switchConversationWorkspace') {
|
|
1771
|
+
return (conversationKey, workspace) => {
|
|
1772
|
+
if (!isCurrentScope()) {
|
|
1773
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1774
|
+
error.code = 'workspace-bot-not-found';
|
|
1775
|
+
return Promise.reject(error);
|
|
1776
|
+
}
|
|
1777
|
+
const token = workspaces.publishConversationWorkspaceSwitch(botId, conversationKey);
|
|
1778
|
+
maskConversationSwitch(conversationKey, token);
|
|
1779
|
+
return trackConversationSwitch(conversationKey, workspaces.applyConversationWorkspaceSwitch(botId, conversationKey, workspace, {
|
|
1780
|
+
token,
|
|
1781
|
+
sessionMatchesWorkspace: (selected) => conversationSessionMatchesWorkspace(conversationKey, selected),
|
|
1782
|
+
clearSession: async () => {
|
|
1783
|
+
await state.clearSession(conversationKey);
|
|
1784
|
+
// A handle resolved before this switch must not stay usable: the
|
|
1785
|
+
// conversation now belongs to another workspace.
|
|
1786
|
+
},
|
|
1787
|
+
incarnation,
|
|
1788
|
+
}));
|
|
1789
|
+
};
|
|
1790
|
+
}
|
|
1791
|
+
if (property === 'clearConversationWorkspace') {
|
|
1792
|
+
return (conversationKey) => {
|
|
1793
|
+
if (!isCurrentScope()) {
|
|
1794
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1795
|
+
error.code = 'workspace-bot-not-found';
|
|
1796
|
+
return Promise.reject(error);
|
|
1797
|
+
}
|
|
1798
|
+
const token = workspaces.publishConversationWorkspaceSwitch(botId, conversationKey);
|
|
1799
|
+
maskConversationSwitch(conversationKey, token);
|
|
1800
|
+
return trackConversationSwitch(conversationKey, workspaces.applyConversationWorkspaceSwitch(botId, conversationKey, null, {
|
|
1801
|
+
token,
|
|
1802
|
+
sessionMatchesWorkspace: (selected) => conversationSessionMatchesWorkspace(conversationKey, selected),
|
|
1803
|
+
clearSession: async () => {
|
|
1804
|
+
await state.clearSession(conversationKey);
|
|
1805
|
+
},
|
|
1806
|
+
incarnation,
|
|
1807
|
+
}));
|
|
1808
|
+
};
|
|
1809
|
+
}
|
|
1810
|
+
if (property === 'bindWorkspaceSession') {
|
|
1811
|
+
return async (conversationKey, sessionId) => {
|
|
1812
|
+
if (typeof conversationKey !== 'string' || !conversationKey
|
|
1813
|
+
|| typeof sessionId !== 'string' || !sessionId) {
|
|
1814
|
+
throw new TypeError('conversationKey and sessionId are required');
|
|
1815
|
+
}
|
|
1816
|
+
if (!isCurrentScope()) {
|
|
1817
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1818
|
+
error.code = 'workspace-bot-not-found';
|
|
1819
|
+
throw error;
|
|
1820
|
+
}
|
|
1821
|
+
if (typeof target.adoptWorkspaceSession !== 'function') {
|
|
1822
|
+
throw new TypeError('Harness does not support adopting workspace sessions');
|
|
1823
|
+
}
|
|
1824
|
+
const expectedGeneration = workspaces.generationFor(botId);
|
|
1825
|
+
const expectedConversationGeneration = workspaces.conversationGenerationFor(botId, conversationKey);
|
|
1826
|
+
const adopted = await target.adoptWorkspaceSession(sessionId);
|
|
1827
|
+
if (!isCurrentScope()) {
|
|
1828
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1829
|
+
error.code = 'workspace-bot-not-found';
|
|
1830
|
+
throw error;
|
|
1831
|
+
}
|
|
1832
|
+
if (expectedGeneration !== workspaces.generationFor(botId)) {
|
|
1833
|
+
throw workspaceSessionStale(
|
|
1834
|
+
'The bot workspace changed while the session was being adopted.',
|
|
1835
|
+
);
|
|
1836
|
+
}
|
|
1837
|
+
if (expectedConversationGeneration
|
|
1838
|
+
!== workspaces.conversationGenerationFor(botId, conversationKey)) {
|
|
1839
|
+
throw workspaceSessionStale(
|
|
1840
|
+
'The conversation workspace changed while the session was being adopted.',
|
|
1841
|
+
);
|
|
1842
|
+
}
|
|
1843
|
+
if (!adopted || typeof adopted !== 'object'
|
|
1844
|
+
|| adopted.sessionId !== sessionId || typeof adopted.workspace !== 'string') {
|
|
1845
|
+
throw new TypeError('Harness returned an invalid adopted workspace session');
|
|
1846
|
+
}
|
|
1847
|
+
const bound = await workspaces.bindWorkspaceSession(botId, adopted.workspace, {
|
|
1848
|
+
conversationKey,
|
|
1849
|
+
sessionId,
|
|
1850
|
+
clearSessions: () => state.clearSessions(),
|
|
1851
|
+
clearSession: (key) => state.clearSession(key),
|
|
1852
|
+
setSession: (key, selectedSessionId) => state.setSession(key, selectedSessionId),
|
|
1853
|
+
onConversationGeneration: (generation) => maskConversationSwitch(conversationKey, generation),
|
|
1854
|
+
incarnation,
|
|
1855
|
+
expectedGeneration,
|
|
1856
|
+
expectedConversationGeneration,
|
|
1857
|
+
});
|
|
1858
|
+
if (!isCurrentScope()) {
|
|
1859
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1860
|
+
error.code = 'workspace-bot-not-found';
|
|
1861
|
+
throw error;
|
|
1862
|
+
}
|
|
1863
|
+
if (bound.generation !== workspaces.generationFor(botId)
|
|
1864
|
+
|| bound.conversationGeneration
|
|
1865
|
+
!== workspaces.conversationGenerationFor(botId, conversationKey)) {
|
|
1866
|
+
throw workspaceSessionStale(
|
|
1867
|
+
'The bot workspace changed before the session binding completed.',
|
|
1868
|
+
);
|
|
1869
|
+
}
|
|
1870
|
+
sessionGenerations.set(sessionId, {
|
|
1871
|
+
generation: bound.generation,
|
|
1872
|
+
workspace: bound.workspace,
|
|
1873
|
+
conversationKey,
|
|
1874
|
+
conversationGeneration: bound.conversationGeneration ?? 0,
|
|
1875
|
+
});
|
|
1876
|
+
return {
|
|
1877
|
+
...adopted,
|
|
1878
|
+
workspace: bound.workspace,
|
|
1879
|
+
sessionId: bound.sessionId,
|
|
1880
|
+
};
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
if (property === 'createSession') {
|
|
1884
|
+
return async (options = {}) => {
|
|
1885
|
+
const { inheritBotModel = true, conversationKey, ...createOptions } = options;
|
|
1886
|
+
// /conv publishes its generation before path validation enters the
|
|
1887
|
+
// bot queue. Wait for both phases before pairing a workspace with its
|
|
1888
|
+
// generation; otherwise a new session can carry a new fence but old cwd.
|
|
1889
|
+
while (true) {
|
|
1890
|
+
const pendingSwitch = pendingConversationSwitches.get(conversationKey);
|
|
1891
|
+
if (pendingSwitch) await pendingSwitch;
|
|
1892
|
+
await workspaces.whenBotIdle(botId);
|
|
1893
|
+
if (!pendingConversationSwitches.has(conversationKey)) break;
|
|
1894
|
+
}
|
|
1895
|
+
if (!isCurrentScope()) {
|
|
1896
|
+
const error = new Error('找不到要修改的机器人。');
|
|
1897
|
+
error.code = 'workspace-bot-not-found';
|
|
1898
|
+
throw error;
|
|
1899
|
+
}
|
|
1900
|
+
const generation = workspaces.generationFor(botId);
|
|
1901
|
+
const conversationGeneration = conversationKey
|
|
1902
|
+
? currentConversationGeneration(conversationKey)
|
|
1903
|
+
: null;
|
|
1904
|
+
const agentPreset = workspaces.agentPresetFor(botId);
|
|
1905
|
+
const model = inheritBotModel === false ? null : workspaces.modelFor(botId);
|
|
1906
|
+
const workspace = workspaces.conversationWorkspaceFor(botId, conversationKey);
|
|
1907
|
+
const sessionId = await target.createSession({
|
|
1908
|
+
...createOptions,
|
|
1909
|
+
workspace,
|
|
1910
|
+
...(agentPreset == null ? {} : { agentPreset }),
|
|
1911
|
+
});
|
|
1912
|
+
// A conversation-level workspace switch can commit while the session is
|
|
1913
|
+
// being created; never bind a session created in the stale workspace to
|
|
1914
|
+
// a conversation whose override already moved on.
|
|
1915
|
+
if (conversationGenerationIsStale(conversationKey, conversationGeneration)) {
|
|
1916
|
+
throw workspaceSessionStale(
|
|
1917
|
+
'The conversation workspace changed while the session was being created.',
|
|
1918
|
+
);
|
|
1919
|
+
}
|
|
1920
|
+
if (model) {
|
|
1921
|
+
if (typeof target.selectSessionModel !== 'function') {
|
|
1922
|
+
throw new TypeError('Harness does not support model selection');
|
|
1923
|
+
}
|
|
1924
|
+
const selected = await target.selectSessionModel(
|
|
1925
|
+
sessionId,
|
|
1926
|
+
model,
|
|
1927
|
+
options.signal ? { signal: options.signal } : {},
|
|
1928
|
+
);
|
|
1929
|
+
if (!confirmsModelSelection(selected?.selected, model)) {
|
|
1930
|
+
const error = new Error('Harness did not confirm the selected model');
|
|
1931
|
+
error.code = 'model-selection-mismatch';
|
|
1932
|
+
throw error;
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
sessionGenerations.set(sessionId, {
|
|
1936
|
+
generation,
|
|
1937
|
+
workspace,
|
|
1938
|
+
conversationKey,
|
|
1939
|
+
conversationGeneration,
|
|
1940
|
+
});
|
|
1941
|
+
return sessionId;
|
|
1942
|
+
};
|
|
1943
|
+
}
|
|
1944
|
+
if (property === 'workspaceSession') {
|
|
1945
|
+
return (sessionId, sessionConversationKey) => {
|
|
1946
|
+
if (typeof sessionId !== 'string' || !sessionId) {
|
|
1947
|
+
// A caller whose mapping was cleared under it must retry the
|
|
1948
|
+
// resolution instead of crashing on a handle it cannot use.
|
|
1949
|
+
return null;
|
|
1950
|
+
}
|
|
1951
|
+
const entry = sessionGenerations.get(sessionId);
|
|
1952
|
+
const generation = entry?.generation
|
|
1953
|
+
?? workspaces.generationFor(botId);
|
|
1954
|
+
// A session handle that names its conversation also fences the
|
|
1955
|
+
// conversation's effective workspace: a switch that starts after the
|
|
1956
|
+
// bind but before the prompt is sent must not run in the old workspace.
|
|
1957
|
+
const conversationKey = typeof sessionConversationKey === 'string'
|
|
1958
|
+
&& sessionConversationKey
|
|
1959
|
+
? sessionConversationKey
|
|
1960
|
+
: entry?.conversationKey ?? null;
|
|
1961
|
+
const conversationGeneration = conversationKey
|
|
1962
|
+
? (entry?.conversationKey === conversationKey
|
|
1963
|
+
? entry.conversationGeneration
|
|
1964
|
+
: currentConversationGeneration(conversationKey))
|
|
1965
|
+
: null;
|
|
1966
|
+
// Copy provenance into the immutable handle, but retain it for a later
|
|
1967
|
+
// setSession (notably /model, which binds after asynchronous selection).
|
|
1968
|
+
const isCurrentSession = () => isCurrentScope()
|
|
1969
|
+
&& generation === workspaces.generationFor(botId)
|
|
1970
|
+
&& !conversationGenerationIsStale(conversationKey, conversationGeneration);
|
|
1971
|
+
const invokeCurrentSession = async (method, args, action) => {
|
|
1972
|
+
if (!isCurrentSession()) {
|
|
1973
|
+
throw workspaceSessionStale(
|
|
1974
|
+
`The bot workspace changed before this ${action} started.`,
|
|
1975
|
+
);
|
|
1976
|
+
}
|
|
1977
|
+
const result = await target[method](sessionId, ...args);
|
|
1978
|
+
if (!isCurrentSession()) {
|
|
1979
|
+
throw workspaceSessionStale(
|
|
1980
|
+
`The bot workspace changed while this ${action} was running.`,
|
|
1981
|
+
);
|
|
1982
|
+
}
|
|
1983
|
+
return result;
|
|
1984
|
+
};
|
|
1985
|
+
const invokeStartedSessionMutation = async (method, args, action) => {
|
|
1986
|
+
if (!isCurrentSession()) {
|
|
1987
|
+
throw workspaceSessionStale(
|
|
1988
|
+
`The bot workspace changed before this ${action} started.`,
|
|
1989
|
+
);
|
|
1990
|
+
}
|
|
1991
|
+
// Once an irreversible control mutation has started, preserve its
|
|
1992
|
+
// actual outcome even if a workspace switch commits concurrently.
|
|
1993
|
+
return target[method](sessionId, ...args);
|
|
1994
|
+
};
|
|
1995
|
+
return Object.freeze({
|
|
1996
|
+
sessionId,
|
|
1997
|
+
async sessionExists(...args) {
|
|
1998
|
+
if (!isCurrentSession()) return false;
|
|
1999
|
+
const exists = await target.sessionExists(sessionId, ...args);
|
|
2000
|
+
return isCurrentSession() && exists;
|
|
2001
|
+
},
|
|
2002
|
+
models(...args) {
|
|
2003
|
+
return invokeCurrentSession('getSessionModels', args, 'model listing');
|
|
2004
|
+
},
|
|
2005
|
+
readHistory(...args) {
|
|
2006
|
+
return invokeCurrentSession('readSessionHistory', args, 'history read');
|
|
2007
|
+
},
|
|
2008
|
+
...(typeof target.renameSession === 'function' ? {
|
|
2009
|
+
renameTitle(...args) {
|
|
2010
|
+
return invokeStartedSessionMutation('renameSession', args, 'title rename');
|
|
2011
|
+
},
|
|
2012
|
+
} : {}),
|
|
2013
|
+
selectModel(...args) {
|
|
2014
|
+
return invokeCurrentSession('selectSessionModel', args, 'model selection');
|
|
2015
|
+
},
|
|
2016
|
+
isRunning(...args) {
|
|
2017
|
+
return invokeCurrentSession('isSessionRunning', args, 'run-state check');
|
|
2018
|
+
},
|
|
2019
|
+
hasActiveTurn(...args) {
|
|
2020
|
+
return invokeCurrentSession('hasActiveTurn', args, 'turn ownership check');
|
|
2021
|
+
},
|
|
2022
|
+
stopActiveTurn(...args) {
|
|
2023
|
+
return invokeStartedSessionMutation('stopActiveTurn', args, 'turn stop');
|
|
2024
|
+
},
|
|
2025
|
+
stopDeferredTurn(...args) {
|
|
2026
|
+
return invokeStartedSessionMutation('stopDeferredTurn', args, 'deferred turn stop');
|
|
2027
|
+
},
|
|
2028
|
+
steerActiveTurn(...args) {
|
|
2029
|
+
return invokeStartedSessionMutation('steerActiveTurn', args, 'turn steering');
|
|
2030
|
+
},
|
|
2031
|
+
...(typeof target.executeCommand === 'function' ? {
|
|
2032
|
+
executeCommand(...args) {
|
|
2033
|
+
return invokeStartedSessionMutation('executeCommand', args, 'command execution');
|
|
2034
|
+
},
|
|
2035
|
+
} : {}),
|
|
2036
|
+
ask(...args) {
|
|
2037
|
+
if (!isCurrentSession()) {
|
|
2038
|
+
throw workspaceSessionStale(
|
|
2039
|
+
'The bot workspace changed before this prompt started.',
|
|
2040
|
+
);
|
|
2041
|
+
}
|
|
2042
|
+
return target.ask(sessionId, ...args);
|
|
2043
|
+
},
|
|
2044
|
+
});
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
if (property === 'sessionExists') {
|
|
2048
|
+
return (sessionId, ...args) => {
|
|
2049
|
+
if (!isCurrentScope()) return false;
|
|
2050
|
+
const entry = sessionGenerations.get(sessionId);
|
|
2051
|
+
if (generationIsStale(entry)) {
|
|
2052
|
+
return false;
|
|
2053
|
+
}
|
|
2054
|
+
return target.sessionExists(sessionId, ...args);
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
if (property === 'ask') {
|
|
2058
|
+
return (sessionId, ...args) => {
|
|
2059
|
+
const entry = sessionGenerations.get(sessionId);
|
|
2060
|
+
if (!isCurrentScope() || generationIsStale(entry)) {
|
|
2061
|
+
const error = new Error('The bot workspace changed before this prompt started.');
|
|
2062
|
+
error.code = WORKSPACE_SESSION_STALE;
|
|
2063
|
+
throw error;
|
|
2064
|
+
}
|
|
2065
|
+
return target.ask(sessionId, ...args);
|
|
2066
|
+
};
|
|
2067
|
+
}
|
|
2068
|
+
if (property === 'executeCommand' && typeof target.executeCommand === 'function') {
|
|
2069
|
+
return (sessionId, ...args) => {
|
|
2070
|
+
const entry = sessionGenerations.get(sessionId);
|
|
2071
|
+
if (!isCurrentScope() || generationIsStale(entry)) {
|
|
2072
|
+
const error = new Error('The bot workspace changed before this command started.');
|
|
2073
|
+
error.code = WORKSPACE_SESSION_STALE;
|
|
2074
|
+
throw error;
|
|
2075
|
+
}
|
|
2076
|
+
return target.executeCommand(sessionId, ...args);
|
|
2077
|
+
};
|
|
2078
|
+
}
|
|
2079
|
+
const value = Reflect.get(target, property, target);
|
|
2080
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
2081
|
+
},
|
|
2082
|
+
});
|
|
2083
|
+
const scopedState = new Proxy(state, {
|
|
2084
|
+
get(target, property) {
|
|
2085
|
+
if (property === CONNECTION_TEST_STATE_IDENTITY) return target;
|
|
2086
|
+
if (property === 'sessionFor') {
|
|
2087
|
+
return (key, ...args) => {
|
|
2088
|
+
if (!isCurrentScope()) return null;
|
|
2089
|
+
const sessionId = target.sessionFor(key, ...args);
|
|
2090
|
+
if (sessionId) {
|
|
2091
|
+
const entry = sessionGenerations.get(sessionId);
|
|
2092
|
+
if (generationIsStale(entry, key)) {
|
|
2093
|
+
// The conversation's effective workspace already moved on, so the
|
|
2094
|
+
// stored mapping must not be treated as a usable session. The
|
|
2095
|
+
// caller re-resolves one in the current workspace instead.
|
|
2096
|
+
return null;
|
|
2097
|
+
}
|
|
2098
|
+
if (!entry) {
|
|
2099
|
+
sessionGenerations.set(sessionId, {
|
|
2100
|
+
generation: workspaces.generationFor(botId),
|
|
2101
|
+
conversationKey: key,
|
|
2102
|
+
conversationGeneration: currentConversationGeneration(key),
|
|
2103
|
+
});
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
return sessionId;
|
|
2107
|
+
};
|
|
2108
|
+
}
|
|
2109
|
+
if (property === 'setSession') {
|
|
2110
|
+
return (key, sessionId, ...args) => {
|
|
2111
|
+
const entry = sessionGenerations.get(sessionId);
|
|
2112
|
+
if (!isCurrentScope() || generationIsStale(entry, key)) {
|
|
2113
|
+
return false;
|
|
2114
|
+
}
|
|
2115
|
+
return target.setSession(key, sessionId, ...args);
|
|
2116
|
+
};
|
|
2117
|
+
}
|
|
2118
|
+
const value = Reflect.get(target, property, target);
|
|
2119
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
2120
|
+
},
|
|
2121
|
+
});
|
|
2122
|
+
return Object.freeze({ harness: scopedHarness, state: scopedState });
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
export function createBotScopedHarness(harness, options) {
|
|
2126
|
+
return createBotWorkspaceScope(harness, options).harness;
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
export function createWorkspaceAwareController(controller, {
|
|
2130
|
+
workspaces,
|
|
2131
|
+
stateFor,
|
|
2132
|
+
agentPresetCatalog,
|
|
2133
|
+
modelCatalog,
|
|
2134
|
+
} = {}) {
|
|
2135
|
+
if (!controller || !workspaces || typeof stateFor !== 'function') {
|
|
2136
|
+
throw new TypeError('controller, workspaces, and stateFor are required');
|
|
2137
|
+
}
|
|
2138
|
+
const transitions = new Map();
|
|
2139
|
+
const withBotTransition = (botId, operation) => {
|
|
2140
|
+
const previous = transitions.get(botId) ?? Promise.resolve();
|
|
2141
|
+
const current = previous.catch(() => undefined).then(operation);
|
|
2142
|
+
transitions.set(botId, current);
|
|
2143
|
+
return current.finally(() => {
|
|
2144
|
+
if (transitions.get(botId) === current) transitions.delete(botId);
|
|
2145
|
+
});
|
|
2146
|
+
};
|
|
2147
|
+
const decorate = (value) => decorateResult(
|
|
2148
|
+
workspaces,
|
|
2149
|
+
value,
|
|
2150
|
+
agentPresetCatalog,
|
|
2151
|
+
modelCatalog,
|
|
2152
|
+
);
|
|
2153
|
+
const updateWorkspace = (botId, workspace) => {
|
|
2154
|
+
// Capture at API invocation, before even waiting for an older outer
|
|
2155
|
+
// transition. A queued request still belongs to the incarnation that the
|
|
2156
|
+
// caller observed, not a deterministic same-id rebind that appears later.
|
|
2157
|
+
const incarnation = workspaces.incarnationFor(botId);
|
|
2158
|
+
return withBotTransition(botId, async () => {
|
|
2159
|
+
const snapshot = await controller.status();
|
|
2160
|
+
if (!snapshot?.bots?.some((bot) => bot?.botId === botId)) {
|
|
2161
|
+
const error = new Error('找不到要修改的机器人。');
|
|
2162
|
+
error.code = 'workspace-bot-not-found';
|
|
2163
|
+
throw error;
|
|
2164
|
+
}
|
|
2165
|
+
const state = await stateFor(botId);
|
|
2166
|
+
await workspaces.setWorkspace(botId, workspace, {
|
|
2167
|
+
clearSessions: () => state.clearSessions(),
|
|
2168
|
+
incarnation,
|
|
2169
|
+
});
|
|
2170
|
+
return decorate(await controller.status());
|
|
2171
|
+
});
|
|
2172
|
+
};
|
|
2173
|
+
const updateAgentPreset = (botId, agentPreset) => {
|
|
2174
|
+
const incarnation = workspaces.incarnationFor(botId);
|
|
2175
|
+
const normalizedAgentPreset = validateAgentPresetId(agentPreset);
|
|
2176
|
+
return withBotTransition(botId, async () => {
|
|
2177
|
+
const snapshot = await controller.status();
|
|
2178
|
+
if (!snapshot?.bots?.some((bot) => bot?.botId === botId)) {
|
|
2179
|
+
const error = new Error('找不到要修改的机器人。');
|
|
2180
|
+
error.code = 'workspace-bot-not-found';
|
|
2181
|
+
throw error;
|
|
2182
|
+
}
|
|
2183
|
+
const catalog = normalizedAgentPreset && agentPresetCatalog
|
|
2184
|
+
? await resolveAgentPresetCatalog(agentPresetCatalog)
|
|
2185
|
+
: null;
|
|
2186
|
+
if (normalizedAgentPreset && agentPresetCatalog
|
|
2187
|
+
&& !catalog?.items.some((item) => item.id === normalizedAgentPreset)) {
|
|
2188
|
+
throw unavailableAgentPreset();
|
|
2189
|
+
}
|
|
2190
|
+
await workspaces.setAgentPreset(botId, normalizedAgentPreset, { incarnation });
|
|
2191
|
+
return decorateResult(
|
|
2192
|
+
workspaces,
|
|
2193
|
+
await controller.status(),
|
|
2194
|
+
catalog ?? agentPresetCatalog,
|
|
2195
|
+
modelCatalog,
|
|
2196
|
+
);
|
|
2197
|
+
});
|
|
2198
|
+
};
|
|
2199
|
+
const updateModel = (botId, value) => {
|
|
2200
|
+
const incarnation = workspaces.incarnationFor(botId);
|
|
2201
|
+
const model = validateModelSelection(value);
|
|
2202
|
+
return withBotTransition(botId, async () => {
|
|
2203
|
+
const snapshot = await controller.status();
|
|
2204
|
+
if (!snapshot?.bots?.some((bot) => bot?.botId === botId)) {
|
|
2205
|
+
const error = new Error('找不到要修改的机器人。');
|
|
2206
|
+
error.code = 'workspace-bot-not-found';
|
|
2207
|
+
throw error;
|
|
2208
|
+
}
|
|
2209
|
+
const catalog = model && modelCatalog
|
|
2210
|
+
? await resolveModelCatalog(modelCatalog)
|
|
2211
|
+
: null;
|
|
2212
|
+
const entry = modelCatalogEntry(catalog, model);
|
|
2213
|
+
if (model && (!modelCatalog || !entry)) {
|
|
2214
|
+
throw unavailableModel();
|
|
2215
|
+
}
|
|
2216
|
+
if (model?.reasoningEffort !== undefined
|
|
2217
|
+
&& !entry.reasoning?.efforts.some((effort) => effort.id === model.reasoningEffort)) {
|
|
2218
|
+
const error = new Error('当前模型不支持所选思考强度,请重新选择。');
|
|
2219
|
+
error.code = 'model-reasoning-unavailable';
|
|
2220
|
+
throw error;
|
|
2221
|
+
}
|
|
2222
|
+
await workspaces.setModel(botId, model, { incarnation });
|
|
2223
|
+
return decorateResult(
|
|
2224
|
+
workspaces,
|
|
2225
|
+
await controller.status(),
|
|
2226
|
+
agentPresetCatalog,
|
|
2227
|
+
catalog ?? modelCatalog,
|
|
2228
|
+
);
|
|
2229
|
+
});
|
|
2230
|
+
};
|
|
2231
|
+
const updateAlias = (botId, value, projectStatus) => {
|
|
2232
|
+
const incarnation = workspaces.incarnationFor(botId);
|
|
2233
|
+
const alias = validateBotAlias(value);
|
|
2234
|
+
return withBotTransition(botId, async () => {
|
|
2235
|
+
const snapshot = await decorate(await controller.status());
|
|
2236
|
+
if (!snapshot?.bots?.some((bot) => bot?.botId === botId)) {
|
|
2237
|
+
const error = new Error('找不到要修改的机器人。');
|
|
2238
|
+
error.code = 'workspace-bot-not-found';
|
|
2239
|
+
throw error;
|
|
2240
|
+
}
|
|
2241
|
+
const updated = { ...snapshot, bots: snapshot.bots.map((bot) => bot.botId === botId
|
|
2242
|
+
? { ...bot, bot: withBotAlias(bot.bot, alias) } : bot) };
|
|
2243
|
+
const result = projectStatus ? await projectStatus(updated) : updated;
|
|
2244
|
+
await workspaces.setAlias(botId, alias, { incarnation });
|
|
2245
|
+
return result;
|
|
2246
|
+
});
|
|
2247
|
+
};
|
|
2248
|
+
const updateContextEnhancement = (botId, value, projectStatus) => {
|
|
2249
|
+
const incarnation = workspaces.incarnationFor(botId);
|
|
2250
|
+
const config = validateContextEnhancementConfig(value);
|
|
2251
|
+
return withBotTransition(botId, async () => {
|
|
2252
|
+
const snapshot = await controller.status();
|
|
2253
|
+
if (!snapshot?.bots?.some((bot) => bot?.botId === botId)) {
|
|
2254
|
+
const error = new Error('找不到要修改的机器人。');
|
|
2255
|
+
error.code = 'workspace-bot-not-found';
|
|
2256
|
+
throw error;
|
|
2257
|
+
}
|
|
2258
|
+
const [catalog, models] = await Promise.all([
|
|
2259
|
+
resolveAgentPresetCatalog(agentPresetCatalog),
|
|
2260
|
+
resolveModelCatalog(modelCatalog),
|
|
2261
|
+
]);
|
|
2262
|
+
const decorated = workspaces.decorateStatus(snapshot);
|
|
2263
|
+
const updated = {
|
|
2264
|
+
...decorated,
|
|
2265
|
+
bots: decorated.bots.map((bot) => bot?.botId === botId
|
|
2266
|
+
? { ...bot, contextEnhancement: config } : bot),
|
|
2267
|
+
...(catalog ? { agentPresetCatalog: catalog } : {}),
|
|
2268
|
+
...(models ? { modelCatalog: models } : {}),
|
|
2269
|
+
};
|
|
2270
|
+
// QR/status projection can fail too. Prepare the complete response before
|
|
2271
|
+
// commit so a failed save never publishes new running settings.
|
|
2272
|
+
const result = projectStatus ? await projectStatus(updated) : updated;
|
|
2273
|
+
await workspaces.setContextEnhancement(botId, config, { incarnation });
|
|
2274
|
+
return result;
|
|
2275
|
+
});
|
|
2276
|
+
};
|
|
2277
|
+
const updateAccessPolicy = (botId, value, projectStatus) => {
|
|
2278
|
+
const incarnation = workspaces.incarnationFor(botId);
|
|
2279
|
+
const policy = validateAccessPolicy(value);
|
|
2280
|
+
return withBotTransition(botId, async () => {
|
|
2281
|
+
const snapshot = await controller.status();
|
|
2282
|
+
if (!snapshot?.bots?.some((bot) => bot?.botId === botId)) {
|
|
2283
|
+
const error = new Error('找不到要修改的机器人。');
|
|
2284
|
+
error.code = 'workspace-bot-not-found';
|
|
2285
|
+
throw error;
|
|
2286
|
+
}
|
|
2287
|
+
const [catalog, models] = await Promise.all([
|
|
2288
|
+
resolveAgentPresetCatalog(agentPresetCatalog),
|
|
2289
|
+
resolveModelCatalog(modelCatalog),
|
|
2290
|
+
]);
|
|
2291
|
+
const decorated = workspaces.decorateStatus(snapshot);
|
|
2292
|
+
const updated = {
|
|
2293
|
+
...decorated,
|
|
2294
|
+
bots: decorated.bots.map((bot) => bot?.botId === botId
|
|
2295
|
+
? { ...bot, accessPolicy: policy } : bot),
|
|
2296
|
+
...(catalog ? { agentPresetCatalog: catalog } : {}),
|
|
2297
|
+
...(models ? { modelCatalog: models } : {}),
|
|
2298
|
+
};
|
|
2299
|
+
// Prepare the complete channel-specific response before commit. Failed
|
|
2300
|
+
// projections and disk writes must leave the live policy unchanged.
|
|
2301
|
+
const result = projectStatus ? await projectStatus(updated) : updated;
|
|
2302
|
+
await workspaces.setAccessPolicy(botId, policy, { incarnation });
|
|
2303
|
+
return result;
|
|
2304
|
+
});
|
|
2305
|
+
};
|
|
2306
|
+
const deleteWithWorkspace = (botId, invokeDelete) => withBotTransition(botId, async () => {
|
|
2307
|
+
const warnings = [];
|
|
2308
|
+
const cleanupWarning = (error, stage = 'workspace.cleanup') => {
|
|
2309
|
+
if (!controller.diagnostics) return;
|
|
2310
|
+
warnings.push(controller.diagnostics.report(error, { operation: 'bot.delete', stage, botId, warning: true,
|
|
2311
|
+
publicError: { code: 'workspace-cleanup-failed', message: stage === 'state.cleanup'
|
|
2312
|
+
? t('本地会话状态清理失败,请查看诊断详情。') : t('账号已移除,但本地状态清理失败。') } }).publicError);
|
|
2313
|
+
};
|
|
2314
|
+
const finishRemoval = async () => {
|
|
2315
|
+
const outcome = await workspaces.finishRemoval(removal);
|
|
2316
|
+
if (outcome?.error) cleanupWarning(outcome.error);
|
|
2317
|
+
};
|
|
2318
|
+
// Fence the old runtime without changing the durable mapping. A crash
|
|
2319
|
+
// before the controller removes its config therefore keeps the bot's
|
|
2320
|
+
// workspace, while a crash after that commit is healed by startup
|
|
2321
|
+
// reconciliation.
|
|
2322
|
+
const removal = await workspaces.beginRemoval(botId, {
|
|
2323
|
+
clearSessions: async () => {
|
|
2324
|
+
try {
|
|
2325
|
+
const state = await stateFor(botId);
|
|
2326
|
+
if (!state || typeof state.clearSessions !== 'function') {
|
|
2327
|
+
throw new TypeError('bot state does not support session cleanup');
|
|
2328
|
+
}
|
|
2329
|
+
await state.clearSessions();
|
|
2330
|
+
} catch (error) {
|
|
2331
|
+
if (controller.diagnostics) cleanupWarning(error, 'state.cleanup');
|
|
2332
|
+
else console.warn('[dsh-im] ignored session cleanup failure while deleting bot:', extractConnectionEvidence(error).details);
|
|
2333
|
+
}
|
|
2334
|
+
},
|
|
2335
|
+
});
|
|
2336
|
+
try {
|
|
2337
|
+
const result = await invokeDelete();
|
|
2338
|
+
await finishRemoval();
|
|
2339
|
+
return decorate({ ...result, ...(warnings.length ? { warnings: [...(result?.warnings ?? []), ...warnings] } : {}) });
|
|
2340
|
+
} catch (error) {
|
|
2341
|
+
const after = await targetStatus(controller).catch(() => null);
|
|
2342
|
+
const knownAbsent = Array.isArray(after?.bots)
|
|
2343
|
+
&& !after.bots.some((bot) => bot?.botId === botId);
|
|
2344
|
+
if (knownAbsent) {
|
|
2345
|
+
if (controller.diagnostics) {
|
|
2346
|
+
cleanupWarning(error);
|
|
2347
|
+
try { await finishRemoval(); } catch (cleanupError) { cleanupWarning(cleanupError); }
|
|
2348
|
+
return decorate({ ...after, warnings });
|
|
2349
|
+
}
|
|
2350
|
+
await workspaces.finishRemoval(removal);
|
|
2351
|
+
} else await workspaces.abortRemoval(removal);
|
|
2352
|
+
throw error;
|
|
2353
|
+
}
|
|
2354
|
+
});
|
|
2355
|
+
|
|
2356
|
+
return new Proxy(controller, {
|
|
2357
|
+
get(target, property) {
|
|
2358
|
+
if (property === 'updateWorkspace') return updateWorkspace;
|
|
2359
|
+
if (property === 'updateAgentPreset') return updateAgentPreset;
|
|
2360
|
+
if (property === 'updateModel') return updateModel;
|
|
2361
|
+
if (property === 'updateAlias') return updateAlias;
|
|
2362
|
+
if (property === 'updateContextEnhancement') return updateContextEnhancement;
|
|
2363
|
+
if (property === 'updateAccessPolicy') return updateAccessPolicy;
|
|
2364
|
+
const value = Reflect.get(target, property, target);
|
|
2365
|
+
if (typeof value !== 'function') return value;
|
|
2366
|
+
if (property === 'deleteBot') {
|
|
2367
|
+
return (botId, ...args) => deleteWithWorkspace(
|
|
2368
|
+
botId,
|
|
2369
|
+
() => value.call(target, botId, ...args),
|
|
2370
|
+
);
|
|
2371
|
+
}
|
|
2372
|
+
if (property === 'disconnect') {
|
|
2373
|
+
return async (...args) => {
|
|
2374
|
+
const before = await target.status();
|
|
2375
|
+
const botId = before?.bots?.[0]?.botId;
|
|
2376
|
+
if (!botId) return decorate(value.apply(target, args));
|
|
2377
|
+
return deleteWithWorkspace(botId, () => value.apply(target, args));
|
|
2378
|
+
};
|
|
2379
|
+
}
|
|
2380
|
+
return (...args) => decorate(value.apply(target, args));
|
|
2381
|
+
},
|
|
2382
|
+
});
|
|
2383
|
+
}
|