@botharness/im-provider 4.32.0-botharness.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/PROVENANCE.json +25 -0
- package/README.en.md +445 -0
- package/README.md +448 -0
- package/THIRD_PARTY_NOTICES.md +93 -0
- package/assets/dingtalk-menu-template.json +6 -0
- package/assets/logo-dsh-im-chinese-readme-3x2.png +0 -0
- package/assets/logo-dsh-im-connecting-readme-3x2.png +0 -0
- package/assets/logo-dsh-im-connecting-square-v4.png +0 -0
- package/assets/logo-icon.png +0 -0
- package/assets/logo-plugin-message-link-gradient.webp +0 -0
- package/assets/logo-plugin-phone.png +0 -0
- package/assets/logo.png +0 -0
- package/assets/logo_cn.png +0 -0
- package/assets/screenshot-menu-card.png +0 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +20330 -0
- package/lib/index.js +604 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +5 -0
- package/package.json +181 -0
- package/plugin-src/client/access-policy-settings.js +362 -0
- package/plugin-src/client/agent-preset.js +119 -0
- package/plugin-src/client/bot-alias.js +169 -0
- package/plugin-src/client/build.mjs +38 -0
- package/plugin-src/client/channel-card-meta.js +132 -0
- package/plugin-src/client/channel-logos.js +190 -0
- package/plugin-src/client/channels/dingtalk/api.js +267 -0
- package/plugin-src/client/channels/dingtalk/index.js +954 -0
- package/plugin-src/client/channels/dingtalk/styles.js +136 -0
- package/plugin-src/client/channels/discord/api.js +11 -0
- package/plugin-src/client/channels/discord/index.js +25 -0
- package/plugin-src/client/channels/discord/styles.js +19 -0
- package/plugin-src/client/channels/email/api.js +52 -0
- package/plugin-src/client/channels/email/index.js +728 -0
- package/plugin-src/client/channels/email/styles.js +51 -0
- package/plugin-src/client/channels/feishu/api.js +405 -0
- package/plugin-src/client/channels/feishu/group-settings.js +581 -0
- package/plugin-src/client/channels/feishu/index.js +1583 -0
- package/plugin-src/client/channels/feishu/slash-panel-settings.js +322 -0
- package/plugin-src/client/channels/feishu/styles.js +573 -0
- package/plugin-src/client/channels/feishu/voice-editor.js +115 -0
- package/plugin-src/client/channels/feishu/voice-settings.js +71 -0
- package/plugin-src/client/channels/imessage/api.js +12 -0
- package/plugin-src/client/channels/imessage/index.js +46 -0
- package/plugin-src/client/channels/imessage/styles.js +19 -0
- package/plugin-src/client/channels/matrix/api.js +11 -0
- package/plugin-src/client/channels/matrix/index.js +151 -0
- package/plugin-src/client/channels/matrix/styles.js +36 -0
- package/plugin-src/client/channels/office/api.js +46 -0
- package/plugin-src/client/channels/office/index.js +153 -0
- package/plugin-src/client/channels/office/styles.js +50 -0
- package/plugin-src/client/channels/qq/api.js +171 -0
- package/plugin-src/client/channels/qq/index.js +593 -0
- package/plugin-src/client/channels/qq/styles.js +19 -0
- package/plugin-src/client/channels/shared/collapsible-account.js +103 -0
- package/plugin-src/client/channels/shared/token-api.js +124 -0
- package/plugin-src/client/channels/shared/token-channel.js +495 -0
- package/plugin-src/client/channels/slack/api.js +11 -0
- package/plugin-src/client/channels/slack/index.js +131 -0
- package/plugin-src/client/channels/slack/styles.js +34 -0
- package/plugin-src/client/channels/telegram/api.js +11 -0
- package/plugin-src/client/channels/telegram/index.js +28 -0
- package/plugin-src/client/channels/telegram/styles.js +31 -0
- package/plugin-src/client/channels/telegram/thinking-traces.js +25 -0
- package/plugin-src/client/channels/wecom/api.js +160 -0
- package/plugin-src/client/channels/wecom/index.js +625 -0
- package/plugin-src/client/channels/wecom/styles.js +19 -0
- package/plugin-src/client/channels/wecom-app/api.js +132 -0
- package/plugin-src/client/channels/wecom-app/index.js +634 -0
- package/plugin-src/client/channels/wecom-app/styles.js +25 -0
- package/plugin-src/client/channels/weixin/api.js +211 -0
- package/plugin-src/client/channels/weixin/connection-error.js +1 -0
- package/plugin-src/client/channels/weixin/index.js +801 -0
- package/plugin-src/client/channels/weixin/styles.js +115 -0
- package/plugin-src/client/channels/whatsapp/api.js +152 -0
- package/plugin-src/client/channels/whatsapp/index.js +609 -0
- package/plugin-src/client/channels/whatsapp/styles.js +19 -0
- package/plugin-src/client/connection-error.js +87 -0
- package/plugin-src/client/context-enhancement.js +415 -0
- package/plugin-src/client/credential-binding.js +118 -0
- package/plugin-src/client/delivery-settings.js +905 -0
- package/plugin-src/client/global-settings.js +433 -0
- package/plugin-src/client/i18n.js +1314 -0
- package/plugin-src/client/index.js +624 -0
- package/plugin-src/client/interface-language.js +89 -0
- package/plugin-src/client/last-message-error.js +18 -0
- package/plugin-src/client/lifecycle.js +86 -0
- package/plugin-src/client/loopback-recovery.js +75 -0
- package/plugin-src/client/model-setting.js +172 -0
- package/plugin-src/client/panel-error-boundary.js +21 -0
- package/plugin-src/client/plugin-page.js +51 -0
- package/plugin-src/client/session-channel-logos.js +243 -0
- package/plugin-src/client/styles.js +770 -0
- package/plugin-src/client/update-panel.js +14 -0
- package/plugin-src/client/workspace-directory-picker.js +280 -0
- package/plugin-src/client/workspace-editor.js +69 -0
- package/plugin-src/client/workspace-snapshot-fence.js +28 -0
- package/plugin-src/host/build.mjs +52 -0
- package/plugin-src/host/channels/dingtalk/connection-supervisor.mjs +130 -0
- package/plugin-src/host/channels/dingtalk/index.mjs +35 -0
- package/plugin-src/host/channels/dingtalk/production.mjs +193 -0
- package/plugin-src/host/channels/dingtalk/rpc.mjs +359 -0
- package/plugin-src/host/channels/discord/index.mjs +33 -0
- package/plugin-src/host/channels/discord/production.mjs +18 -0
- package/plugin-src/host/channels/discord/rpc.mjs +21 -0
- package/plugin-src/host/channels/email/availability.mjs +60 -0
- package/plugin-src/host/channels/email/index.mjs +36 -0
- package/plugin-src/host/channels/email/production.mjs +58 -0
- package/plugin-src/host/channels/email/rpc.mjs +163 -0
- package/plugin-src/host/channels/feishu/connection-supervisor.mjs +167 -0
- package/plugin-src/host/channels/feishu/controller.mjs +172 -0
- package/plugin-src/host/channels/feishu/credential-store.mjs +84 -0
- package/plugin-src/host/channels/feishu/index.mjs +69 -0
- package/plugin-src/host/channels/feishu/production.mjs +319 -0
- package/plugin-src/host/channels/feishu/rpc.mjs +863 -0
- package/plugin-src/host/channels/imessage/index.mjs +21 -0
- package/plugin-src/host/channels/imessage/production.mjs +13 -0
- package/plugin-src/host/channels/imessage/rpc.mjs +78 -0
- package/plugin-src/host/channels/matrix/index.mjs +31 -0
- package/plugin-src/host/channels/matrix/production.mjs +241 -0
- package/plugin-src/host/channels/matrix/rpc.mjs +228 -0
- package/plugin-src/host/channels/office/index.mjs +14 -0
- package/plugin-src/host/channels/office/production.mjs +45 -0
- package/plugin-src/host/channels/office/rpc.mjs +51 -0
- package/plugin-src/host/channels/qq/connection-supervisor.mjs +124 -0
- package/plugin-src/host/channels/qq/index.mjs +28 -0
- package/plugin-src/host/channels/qq/production.mjs +181 -0
- package/plugin-src/host/channels/qq/rpc.mjs +250 -0
- package/plugin-src/host/channels/shared/access-policy-production.mjs +137 -0
- package/plugin-src/host/channels/shared/access-policy-rpc.mjs +17 -0
- package/plugin-src/host/channels/shared/agent-preset-rpc.mjs +25 -0
- package/plugin-src/host/channels/shared/bot-alias-rpc.mjs +15 -0
- package/plugin-src/host/channels/shared/connection-supervisor.mjs +133 -0
- package/plugin-src/host/channels/shared/context-enhancement-rpc.mjs +17 -0
- package/plugin-src/host/channels/shared/model-setting-rpc.mjs +18 -0
- package/plugin-src/host/channels/shared/production.mjs +239 -0
- package/plugin-src/host/channels/shared/rpc.mjs +226 -0
- package/plugin-src/host/channels/shared/startup-error.mjs +55 -0
- package/plugin-src/host/channels/shared/startup.mjs +76 -0
- package/plugin-src/host/channels/shared/thinking-traces-rpc.mjs +11 -0
- package/plugin-src/host/channels/shared/workspace-rpc.mjs +31 -0
- package/plugin-src/host/channels/slack/index.mjs +31 -0
- package/plugin-src/host/channels/slack/production.mjs +176 -0
- package/plugin-src/host/channels/slack/rpc.mjs +221 -0
- package/plugin-src/host/channels/telegram/index.mjs +33 -0
- package/plugin-src/host/channels/telegram/production.mjs +19 -0
- package/plugin-src/host/channels/telegram/rpc.mjs +22 -0
- package/plugin-src/host/channels/wecom/connection-supervisor.mjs +124 -0
- package/plugin-src/host/channels/wecom/index.mjs +34 -0
- package/plugin-src/host/channels/wecom/production.mjs +187 -0
- package/plugin-src/host/channels/wecom/rpc.mjs +255 -0
- package/plugin-src/host/channels/wecom-app/index.mjs +33 -0
- package/plugin-src/host/channels/wecom-app/production.mjs +221 -0
- package/plugin-src/host/channels/wecom-app/rpc.mjs +235 -0
- package/plugin-src/host/channels/weixin/connection-supervisor.mjs +139 -0
- package/plugin-src/host/channels/weixin/index.mjs +44 -0
- package/plugin-src/host/channels/weixin/production.mjs +258 -0
- package/plugin-src/host/channels/weixin/rpc.mjs +285 -0
- package/plugin-src/host/channels/whatsapp/index.mjs +33 -0
- package/plugin-src/host/channels/whatsapp/production.mjs +198 -0
- package/plugin-src/host/channels/whatsapp/rpc.mjs +242 -0
- package/plugin-src/host/delivery-adapter.mjs +411 -0
- package/plugin-src/host/delivery-http.mjs +132 -0
- package/plugin-src/host/delivery-rpc.mjs +173 -0
- package/plugin-src/host/delivery-service.mjs +618 -0
- package/plugin-src/host/delivery-suggestions.mjs +198 -0
- package/plugin-src/host/harness-command-executor.mjs +48 -0
- package/plugin-src/host/harness-connection.mjs +20 -0
- package/plugin-src/host/harness-session-coordinator.mjs +183 -0
- package/plugin-src/host/host-language-rpc.mjs +71 -0
- package/plugin-src/host/host-language.mjs +157 -0
- package/plugin-src/host/image-input-rpc.mjs +24 -0
- package/plugin-src/host/inbound-ttl-rpc.mjs +86 -0
- package/plugin-src/host/inbound-ttl-runtime.mjs +85 -0
- package/plugin-src/host/inbound-ttl-service.mjs +179 -0
- package/plugin-src/host/index.mjs +229 -0
- package/plugin-src/host/injected-context.mjs +104 -0
- package/plugin-src/host/lark-sdk-handshake-patch.mjs +181 -0
- package/plugin-src/host/modern-harness-api.mjs +738 -0
- package/plugin-src/host/rpc-authority.mjs +12 -0
- package/plugin-src/host/session-sync-coordinator.mjs +233 -0
- package/plugin-src/host/session-title-prefix.mjs +122 -0
- package/plugin-src/host/update-policy.mjs +31 -0
- package/plugin-src/host/update-rpc.mjs +16 -0
- package/plugin-src/host/update-runtime.mjs +339 -0
- package/plugin-src/host/update-service.mjs +392 -0
- package/plugin-src/management-rpc.mjs +87 -0
- package/src/channels/dingtalk/config-store.mjs +284 -0
- package/src/channels/dingtalk/connection-error.mjs +292 -0
- package/src/channels/dingtalk/device-auth.mjs +240 -0
- package/src/channels/dingtalk/dingtalk-api.mjs +1140 -0
- package/src/channels/dingtalk/dingtalk-bridge.mjs +1889 -0
- package/src/channels/dingtalk/dingtalk-card-stream.mjs +242 -0
- package/src/channels/dingtalk/dingtalk-controller.mjs +852 -0
- package/src/channels/dingtalk/dingtalk-menu.mjs +95 -0
- package/src/channels/dingtalk/dingtalk-runtime.mjs +482 -0
- package/src/channels/dingtalk/harness-client.mjs +19 -0
- package/src/channels/dingtalk/state-store.mjs +325 -0
- package/src/channels/discord/config-store.mjs +28 -0
- package/src/channels/discord/discord-api.mjs +423 -0
- package/src/channels/discord/discord-bridge.mjs +16 -0
- package/src/channels/discord/discord-controller.mjs +29 -0
- package/src/channels/discord/discord-runtime.mjs +1091 -0
- package/src/channels/discord/external-consumer.mjs +199 -0
- package/src/channels/discord/external-files.mjs +97 -0
- package/src/channels/discord/harness-client.mjs +11 -0
- package/src/channels/discord/history-reader.mjs +142 -0
- package/src/channels/discord/nearby-history.mjs +112 -0
- package/src/channels/discord/state-store.mjs +3 -0
- package/src/channels/email/config-store.mjs +194 -0
- package/src/channels/email/email-api.mjs +20 -0
- package/src/channels/email/email-bridge.mjs +17 -0
- package/src/channels/email/email-controller.mjs +824 -0
- package/src/channels/email/email-runtime.mjs +699 -0
- package/src/channels/email/harness-client.mjs +7 -0
- package/src/channels/email/mail-format.mjs +91 -0
- package/src/channels/email/state-store.mjs +176 -0
- package/src/channels/email/transport.mjs +64 -0
- package/src/channels/email/transports/agent-mail.mjs +604 -0
- package/src/channels/email/transports/agently-cli.mjs +288 -0
- package/src/channels/email/transports/imap-smtp.mjs +165 -0
- package/src/channels/feishu/bridge.mjs +6286 -0
- package/src/channels/feishu/config.mjs +71 -0
- package/src/channels/feishu/external-cards.mjs +87 -0
- package/src/channels/feishu/external-consumer.mjs +89 -0
- package/src/channels/feishu/external-files.mjs +115 -0
- package/src/channels/feishu/external-images.mjs +50 -0
- package/src/channels/feishu/external-names.mjs +99 -0
- package/src/channels/feishu/feishu-app.mjs +54 -0
- package/src/channels/feishu/feishu-cards.mjs +1285 -0
- package/src/channels/feishu/feishu-channel.mjs +651 -0
- package/src/channels/feishu/feishu-runtime.mjs +982 -0
- package/src/channels/feishu/group-message-permission-manager.mjs +72 -0
- package/src/channels/feishu/group-response-mode.mjs +15 -0
- package/src/channels/feishu/harness-client.mjs +19 -0
- package/src/channels/feishu/history-reader.mjs +77 -0
- package/src/channels/feishu/live-cot.mjs +260 -0
- package/src/channels/feishu/message-utils.mjs +613 -0
- package/src/channels/feishu/multi-bot-controller.mjs +1619 -0
- package/src/channels/feishu/nearby-history.mjs +72 -0
- package/src/channels/feishu/plugin-config-store.mjs +216 -0
- package/src/channels/feishu/plugin-controller.mjs +254 -0
- package/src/channels/feishu/registration-manager.mjs +349 -0
- package/src/channels/feishu/repair-manager.mjs +138 -0
- package/src/channels/feishu/reply-context.mjs +22 -0
- package/src/channels/feishu/slash-command-panel.mjs +155 -0
- package/src/channels/feishu/slash-command-registry.mjs +495 -0
- package/src/channels/feishu/state-store.mjs +214 -0
- package/src/channels/feishu/step-push-mode.mjs +25 -0
- package/src/channels/feishu/voice-config.mjs +34 -0
- package/src/channels/feishu/voice.mjs +134 -0
- package/src/channels/imessage/config-store.mjs +24 -0
- package/src/channels/imessage/controller.mjs +37 -0
- package/src/channels/imessage/harness-client.mjs +7 -0
- package/src/channels/imessage/imessage-api.mjs +194 -0
- package/src/channels/imessage/imessage-bridge.mjs +16 -0
- package/src/channels/imessage/runtime.mjs +102 -0
- package/src/channels/imessage/state-store.mjs +3 -0
- package/src/channels/matrix/matrix-api.mjs +696 -0
- package/src/channels/matrix/matrix-bridge.mjs +20 -0
- package/src/channels/matrix/matrix-config-store.mjs +368 -0
- package/src/channels/matrix/matrix-controller.mjs +404 -0
- package/src/channels/matrix/matrix-crypto-store.mjs +279 -0
- package/src/channels/matrix/matrix-crypto.mjs +1014 -0
- package/src/channels/matrix/matrix-harness-client.mjs +11 -0
- package/src/channels/matrix/matrix-normalize.mjs +357 -0
- package/src/channels/matrix/matrix-rich-text.mjs +313 -0
- package/src/channels/matrix/matrix-room-history.mjs +316 -0
- package/src/channels/matrix/matrix-runtime.mjs +1014 -0
- package/src/channels/office/config-store.mjs +107 -0
- package/src/channels/office/office-controller.mjs +178 -0
- package/src/channels/office/office-job-executor.mjs +391 -0
- package/src/channels/office/office-runtime.mjs +175 -0
- package/src/channels/office/office-transport.mjs +171 -0
- package/src/channels/office/protocol.mjs +43 -0
- package/src/channels/qq/config-store.mjs +173 -0
- package/src/channels/qq/harness-client.mjs +11 -0
- package/src/channels/qq/markdown-reply.mjs +446 -0
- package/src/channels/qq/qq-bridge.mjs +1507 -0
- package/src/channels/qq/qq-controller.mjs +514 -0
- package/src/channels/qq/qq-menu.mjs +208 -0
- package/src/channels/qq/qq-runtime.mjs +303 -0
- package/src/channels/qq/qr-auth.mjs +24 -0
- package/src/channels/qq/state-error.mjs +17 -0
- package/src/channels/qq/state-store.mjs +143 -0
- package/src/channels/shared/access-policy.mjs +210 -0
- package/src/channels/shared/agent-preset.mjs +76 -0
- package/src/channels/shared/batch-input.mjs +229 -0
- package/src/channels/shared/bot-alias.mjs +29 -0
- package/src/channels/shared/bot-workspace-store.mjs +2383 -0
- package/src/channels/shared/command-catalog.mjs +107 -0
- package/src/channels/shared/command-permission.mjs +32 -0
- package/src/channels/shared/compact-command.mjs +109 -0
- package/src/channels/shared/config-read-error.mjs +24 -0
- package/src/channels/shared/connection-error.mjs +191 -0
- package/src/channels/shared/connection-test.mjs +58 -0
- package/src/channels/shared/context-enhancement.mjs +372 -0
- package/src/channels/shared/control-command.mjs +111 -0
- package/src/channels/shared/conversation-state-store.mjs +165 -0
- package/src/channels/shared/default-workspace.mjs +31 -0
- package/src/channels/shared/deferred-delivery-coordinator.mjs +241 -0
- package/src/channels/shared/deferred-delivery.mjs +161 -0
- package/src/channels/shared/deferred-state.mjs +53 -0
- package/src/channels/shared/diagnostic-details.mjs +95 -0
- package/src/channels/shared/editable-message-stream.mjs +100 -0
- package/src/channels/shared/exclusive-inbound-consumers.mjs +91 -0
- package/src/channels/shared/file-download.mjs +64 -0
- package/src/channels/shared/harness-approval.mjs +508 -0
- package/src/channels/shared/harness-client.mjs +2143 -0
- package/src/channels/shared/harness-mux.mjs +123 -0
- package/src/channels/shared/harness-question.mjs +95 -0
- package/src/channels/shared/harness-session-binding.mjs +119 -0
- package/src/channels/shared/history-command.mjs +193 -0
- package/src/channels/shared/i18n-en/diagnostics.mjs +55 -0
- package/src/channels/shared/i18n-en/dingtalk.mjs +81 -0
- package/src/channels/shared/i18n-en/discord.mjs +10 -0
- package/src/channels/shared/i18n-en/email.mjs +25 -0
- package/src/channels/shared/i18n-en/feishu.mjs +404 -0
- package/src/channels/shared/i18n-en/image-input.mjs +18 -0
- package/src/channels/shared/i18n-en/matrix.mjs +85 -0
- package/src/channels/shared/i18n-en/office.mjs +23 -0
- package/src/channels/shared/i18n-en/qq.mjs +96 -0
- package/src/channels/shared/i18n-en/shared-a.mjs +241 -0
- package/src/channels/shared/i18n-en/shared-b.mjs +263 -0
- package/src/channels/shared/i18n-en/shared-c.mjs +203 -0
- package/src/channels/shared/i18n-en/slack.mjs +27 -0
- package/src/channels/shared/i18n-en/telegram.mjs +27 -0
- package/src/channels/shared/i18n-en/wecom-app.mjs +33 -0
- package/src/channels/shared/i18n-en/wecom.mjs +62 -0
- package/src/channels/shared/i18n-en/weixin.mjs +88 -0
- package/src/channels/shared/i18n-en/whatsapp.mjs +17 -0
- package/src/channels/shared/i18n-en.mjs +45 -0
- package/src/channels/shared/i18n.mjs +78 -0
- package/src/channels/shared/im-source-guidance.mjs +65 -0
- package/src/channels/shared/image-input-policy.mjs +35 -0
- package/src/channels/shared/image-input-settings-store.mjs +60 -0
- package/src/channels/shared/image-input.mjs +124 -0
- package/src/channels/shared/image-prompt.mjs +360 -0
- package/src/channels/shared/inbound-access.mjs +43 -0
- package/src/channels/shared/inbound-file.mjs +323 -0
- package/src/channels/shared/inbound-ttl-store.mjs +110 -0
- package/src/channels/shared/inbound-ttl.mjs +22 -0
- package/src/channels/shared/injected-context.mjs +362 -0
- package/src/channels/shared/interface-language-store.mjs +127 -0
- package/src/channels/shared/interface-language.mjs +51 -0
- package/src/channels/shared/message-failure.mjs +257 -0
- package/src/channels/shared/model-command.mjs +741 -0
- package/src/channels/shared/model-setting.mjs +145 -0
- package/src/channels/shared/preset-command.mjs +308 -0
- package/src/channels/shared/semantic/artifact-delivery.mjs +177 -0
- package/src/channels/shared/semantic/artifact.mjs +750 -0
- package/src/channels/shared/semantic/delivery.mjs +193 -0
- package/src/channels/shared/semantic/reply-reference.mjs +148 -0
- package/src/channels/shared/session-binding-lock.mjs +40 -0
- package/src/channels/shared/session-channel-labels.mjs +28 -0
- package/src/channels/shared/session-reply-recovery.mjs +104 -0
- package/src/channels/shared/session-sync-registry.mjs +22 -0
- package/src/channels/shared/session-title.mjs +74 -0
- package/src/channels/shared/status-reaction.mjs +107 -0
- package/src/channels/shared/text-harness-bridge.mjs +1623 -0
- package/src/channels/shared/token-bot-controller.mjs +529 -0
- package/src/channels/shared/token-config-store.mjs +208 -0
- package/src/channels/shared/video-media.mjs +9 -0
- package/src/channels/shared/workspace-command.mjs +532 -0
- package/src/channels/shared/workspace-session.mjs +196 -0
- package/src/channels/slack/config-store.mjs +177 -0
- package/src/channels/slack/external-consumer.mjs +93 -0
- package/src/channels/slack/external-files.mjs +90 -0
- package/src/channels/slack/harness-client.mjs +11 -0
- package/src/channels/slack/history-reader.mjs +203 -0
- package/src/channels/slack/manifest.mjs +37 -0
- package/src/channels/slack/slack-api.mjs +644 -0
- package/src/channels/slack/slack-bridge.mjs +20 -0
- package/src/channels/slack/slack-controller.mjs +468 -0
- package/src/channels/slack/slack-runtime.mjs +895 -0
- package/src/channels/slack/state-store.mjs +3 -0
- package/src/channels/telegram/config-store.mjs +89 -0
- package/src/channels/telegram/harness-client.mjs +11 -0
- package/src/channels/telegram/state-store.mjs +3 -0
- package/src/channels/telegram/telegram-api.mjs +486 -0
- package/src/channels/telegram/telegram-bridge.mjs +81 -0
- package/src/channels/telegram/telegram-controller.mjs +52 -0
- package/src/channels/telegram/telegram-http.mjs +21 -0
- package/src/channels/telegram/telegram-rich-message.mjs +149 -0
- package/src/channels/telegram/telegram-runtime.mjs +1471 -0
- package/src/channels/wecom/config-store.mjs +172 -0
- package/src/channels/wecom/harness-client.mjs +11 -0
- package/src/channels/wecom/qr-auth.mjs +95 -0
- package/src/channels/wecom/send-error.mjs +31 -0
- package/src/channels/wecom/state-store.mjs +107 -0
- package/src/channels/wecom/wecom-bridge.mjs +1833 -0
- package/src/channels/wecom/wecom-cards.mjs +101 -0
- package/src/channels/wecom/wecom-controller.mjs +530 -0
- package/src/channels/wecom/wecom-runtime.mjs +269 -0
- package/src/channels/wecom-app/callback-server.mjs +471 -0
- package/src/channels/wecom-app/config-store.mjs +242 -0
- package/src/channels/wecom-app/harness-client.mjs +11 -0
- package/src/channels/wecom-app/state-store.mjs +107 -0
- package/src/channels/wecom-app/wecom-app-api.mjs +432 -0
- package/src/channels/wecom-app/wecom-app-bridge.mjs +1072 -0
- package/src/channels/wecom-app/wecom-app-controller.mjs +453 -0
- package/src/channels/wecom-app/wecom-app-runtime.mjs +222 -0
- package/src/channels/weixin/config-store.mjs +194 -0
- package/src/channels/weixin/connection-error.en.mjs +137 -0
- package/src/channels/weixin/connection-error.mjs +153 -0
- package/src/channels/weixin/diagnostic-details.mjs +1 -0
- package/src/channels/weixin/external-consumer.mjs +160 -0
- package/src/channels/weixin/external-files.mjs +84 -0
- package/src/channels/weixin/external-typing.mjs +120 -0
- package/src/channels/weixin/harness-client.mjs +19 -0
- package/src/channels/weixin/state-store.mjs +316 -0
- package/src/channels/weixin/weixin-api.mjs +1009 -0
- package/src/channels/weixin/weixin-bridge.mjs +1537 -0
- package/src/channels/weixin/weixin-controller.mjs +779 -0
- package/src/channels/weixin/weixin-runtime.mjs +507 -0
- package/src/channels/whatsapp/config-store.mjs +210 -0
- package/src/channels/whatsapp/harness-client.mjs +11 -0
- package/src/channels/whatsapp/state-store.mjs +3 -0
- package/src/channels/whatsapp/whatsapp-bridge.mjs +18 -0
- package/src/channels/whatsapp/whatsapp-controller.mjs +470 -0
- package/src/channels/whatsapp/whatsapp-runtime.mjs +917 -0
- package/src/channels/whatsapp/whatsapp-web-session.mjs +214 -0
|
@@ -0,0 +1,2143 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdir } from 'node:fs/promises';
|
|
4
|
+
import { isAbsolute } from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { adoptRegisteredWorkspaceSession } from './harness-session-binding.mjs';
|
|
7
|
+
import { sameWorkspacePath } from './default-workspace.mjs';
|
|
8
|
+
import {
|
|
9
|
+
appendInboundFilesToPrompt,
|
|
10
|
+
InboundFileError,
|
|
11
|
+
} from './inbound-file.mjs';
|
|
12
|
+
import {
|
|
13
|
+
IMAGE_FILE_FALLBACK_PROMPT,
|
|
14
|
+
contentWithoutImages,
|
|
15
|
+
imageFileSourcesFromContent,
|
|
16
|
+
isModelImageRejection,
|
|
17
|
+
} from './image-prompt.mjs';
|
|
18
|
+
import { imageInputLimits } from './image-input-policy.mjs';
|
|
19
|
+
import { inboundImagesAsFiles, imageContentFromStaged, isImageAdmissionRejection, IMAGE_HOST_LIMIT_FALLBACK_PROMPT } from './image-input.mjs';
|
|
20
|
+
import { imSourceGuidance } from './im-source-guidance.mjs';
|
|
21
|
+
import { outboundArtifactRegistry } from './semantic/artifact.mjs';
|
|
22
|
+
import { t } from './i18n.mjs';
|
|
23
|
+
import { watchHarnessMux } from './harness-mux.mjs';
|
|
24
|
+
|
|
25
|
+
// Every channel plugin runs in the same Host process. Sharing ownership by
|
|
26
|
+
// Host identity (or an explicitly configured HTTP origin) prevents clients
|
|
27
|
+
// bound to one Session
|
|
28
|
+
// from claiming or cancelling each other's interactions.
|
|
29
|
+
const interactionRegistries = new Map();
|
|
30
|
+
const hostInteractionRegistries = new WeakMap();
|
|
31
|
+
const MAX_ERROR_CLASSIFICATION_BYTES = 64;
|
|
32
|
+
const IM_INPUT_ORIGIN_TTL_MS = 30 * 60 * 1000;
|
|
33
|
+
const MAX_IM_INPUT_ORIGINS = 4096;
|
|
34
|
+
|
|
35
|
+
async function smallResponseText(response) {
|
|
36
|
+
const stream = response?.body;
|
|
37
|
+
if (!stream || typeof stream.getReader !== 'function') return null;
|
|
38
|
+
|
|
39
|
+
const reader = stream.getReader();
|
|
40
|
+
const chunks = [];
|
|
41
|
+
let length = 0;
|
|
42
|
+
try {
|
|
43
|
+
while (true) {
|
|
44
|
+
const { done, value } = await reader.read();
|
|
45
|
+
if (done) break;
|
|
46
|
+
if (!(value instanceof Uint8Array)
|
|
47
|
+
|| length + value.byteLength > MAX_ERROR_CLASSIFICATION_BYTES) return null;
|
|
48
|
+
chunks.push(value);
|
|
49
|
+
length += value.byteLength;
|
|
50
|
+
}
|
|
51
|
+
} catch {
|
|
52
|
+
return null;
|
|
53
|
+
} finally {
|
|
54
|
+
try {
|
|
55
|
+
await reader.cancel();
|
|
56
|
+
} catch {
|
|
57
|
+
// The response body is diagnostic-only; cancellation failures do not
|
|
58
|
+
// replace the HTTP status that caused the transport error.
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const bytes = new Uint8Array(length);
|
|
63
|
+
let offset = 0;
|
|
64
|
+
for (const chunk of chunks) {
|
|
65
|
+
bytes.set(chunk, offset);
|
|
66
|
+
offset += chunk.byteLength;
|
|
67
|
+
}
|
|
68
|
+
return new TextDecoder().decode(bytes);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function isLoopbackHarnessHostname(hostname) {
|
|
72
|
+
if (hostname === 'localhost' || hostname === '[::1]') return true;
|
|
73
|
+
const parts = hostname.split('.');
|
|
74
|
+
return parts.length === 4
|
|
75
|
+
&& parts[0] === '127'
|
|
76
|
+
&& parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function harnessHttpErrorCode(response, hostname) {
|
|
80
|
+
if (response.status === 401) return 'harness-auth-required';
|
|
81
|
+
if (response.status === 407) return 'harness-proxy-auth-required';
|
|
82
|
+
if (response.status === 403) {
|
|
83
|
+
const body = await smallResponseText(response);
|
|
84
|
+
if (body?.trim() !== 'forbidden') return 'harness-request-forbidden';
|
|
85
|
+
return isLoopbackHarnessHostname(hostname)
|
|
86
|
+
? 'harness-loopback-forbidden'
|
|
87
|
+
: 'harness-host-untrusted';
|
|
88
|
+
}
|
|
89
|
+
if (response.status === 404) return 'harness-api-not-found';
|
|
90
|
+
return 'harness-http-failed';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function interactionRegistry(scope) {
|
|
94
|
+
const registries = typeof scope === 'string' ? interactionRegistries : hostInteractionRegistries;
|
|
95
|
+
let registry = registries.get(scope);
|
|
96
|
+
if (!registry) {
|
|
97
|
+
registry = {
|
|
98
|
+
ownerships: new Map(),
|
|
99
|
+
claims: new Map(),
|
|
100
|
+
controls: new WeakMap(),
|
|
101
|
+
imInputOrigins: new Map(),
|
|
102
|
+
nextOrder: 0,
|
|
103
|
+
};
|
|
104
|
+
registries.set(scope, registry);
|
|
105
|
+
}
|
|
106
|
+
return registry;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function pruneImInputOrigins(origins, now = Date.now()) {
|
|
110
|
+
for (const [rpcId, expiresAt] of origins) {
|
|
111
|
+
if (expiresAt > now) continue;
|
|
112
|
+
origins.delete(rpcId);
|
|
113
|
+
}
|
|
114
|
+
while (origins.size > MAX_IM_INPUT_ORIGINS) {
|
|
115
|
+
origins.delete(origins.keys().next().value);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function registerImInputOrigin(registry, rpcId) {
|
|
120
|
+
const origins = registry.imInputOrigins;
|
|
121
|
+
pruneImInputOrigins(origins);
|
|
122
|
+
origins.delete(rpcId);
|
|
123
|
+
origins.set(rpcId, Date.now() + IM_INPUT_ORIGIN_TTL_MS);
|
|
124
|
+
pruneImInputOrigins(origins);
|
|
125
|
+
return () => origins.delete(rpcId);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Consume a dsh-im prompt id while handling its durable user/message event. */
|
|
129
|
+
export function consumeDshImInputOrigin(scope, rpcId) {
|
|
130
|
+
if (!scope || !['object', 'function', 'string'].includes(typeof scope)
|
|
131
|
+
|| typeof rpcId !== 'string' || !rpcId) return false;
|
|
132
|
+
const origins = interactionRegistry(scope).imInputOrigins;
|
|
133
|
+
pruneImInputOrigins(origins);
|
|
134
|
+
return origins.delete(rpcId);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// A Host RPC may not accept cancellation itself. Bound the caller's wait
|
|
138
|
+
// without retrying an operation that the Host may already have accepted.
|
|
139
|
+
function callWithSignal(call, signal) {
|
|
140
|
+
return new Promise((resolve, reject) => {
|
|
141
|
+
const cleanup = () => signal.removeEventListener('abort', handleAbort);
|
|
142
|
+
const handleAbort = () => {
|
|
143
|
+
cleanup();
|
|
144
|
+
reject(signal.reason);
|
|
145
|
+
};
|
|
146
|
+
if (signal.aborted) {
|
|
147
|
+
handleAbort();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
signal.addEventListener('abort', handleAbort, { once: true });
|
|
151
|
+
Promise.resolve().then(() => {
|
|
152
|
+
signal.throwIfAborted();
|
|
153
|
+
return call();
|
|
154
|
+
}).then((value) => {
|
|
155
|
+
cleanup();
|
|
156
|
+
resolve(value);
|
|
157
|
+
}, (error) => {
|
|
158
|
+
cleanup();
|
|
159
|
+
reject(error);
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function normalizeControl(control) {
|
|
165
|
+
const ownerType = typeof control?.owner;
|
|
166
|
+
if ((ownerType !== 'object' && ownerType !== 'function')
|
|
167
|
+
|| control.owner === null
|
|
168
|
+
|| typeof control.key !== 'string'
|
|
169
|
+
|| !control.key) return null;
|
|
170
|
+
return { owner: control.owner, key: control.key };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function validModelSelection(value) {
|
|
174
|
+
return value !== null
|
|
175
|
+
&& typeof value === 'object'
|
|
176
|
+
&& typeof value.provider === 'string'
|
|
177
|
+
&& Boolean(value.provider)
|
|
178
|
+
&& typeof value.model === 'string'
|
|
179
|
+
&& Boolean(value.model)
|
|
180
|
+
&& (value.reasoningEffort === undefined
|
|
181
|
+
|| (typeof value.reasoningEffort === 'string' && Boolean(value.reasoningEffort)));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function validModelReasoning(value) {
|
|
185
|
+
return value !== null
|
|
186
|
+
&& typeof value === 'object'
|
|
187
|
+
&& Array.isArray(value.efforts)
|
|
188
|
+
&& value.efforts.length > 0
|
|
189
|
+
&& value.efforts.every((effort) => (
|
|
190
|
+
effort !== null
|
|
191
|
+
&& typeof effort === 'object'
|
|
192
|
+
&& typeof effort.id === 'string'
|
|
193
|
+
&& Boolean(effort.id)
|
|
194
|
+
&& typeof effort.name === 'string'
|
|
195
|
+
&& Boolean(effort.name)
|
|
196
|
+
&& (effort.description === undefined || typeof effort.description === 'string')
|
|
197
|
+
))
|
|
198
|
+
&& (value.defaultEffort === undefined
|
|
199
|
+
|| (typeof value.defaultEffort === 'string' && Boolean(value.defaultEffort)));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function validateModelCatalog(value, method, { session = false } = {}) {
|
|
203
|
+
if (!value || typeof value !== 'object'
|
|
204
|
+
|| !Array.isArray(value.groups)
|
|
205
|
+
|| !Array.isArray(value.failures)) {
|
|
206
|
+
throw new Error(`Harness returned an invalid response for ${method}`);
|
|
207
|
+
}
|
|
208
|
+
for (const group of value.groups) {
|
|
209
|
+
if (!group || typeof group !== 'object'
|
|
210
|
+
|| typeof group.id !== 'string' || !group.id
|
|
211
|
+
|| typeof group.name !== 'string' || !group.name
|
|
212
|
+
|| !Array.isArray(group.models)) {
|
|
213
|
+
throw new Error(`Harness returned an invalid response for ${method}`);
|
|
214
|
+
}
|
|
215
|
+
for (const model of group.models) {
|
|
216
|
+
if (!model || typeof model !== 'object'
|
|
217
|
+
|| typeof model.id !== 'string' || !model.id
|
|
218
|
+
|| typeof model.name !== 'string' || !model.name
|
|
219
|
+
|| (model.description !== undefined && typeof model.description !== 'string')
|
|
220
|
+
|| (model.reasoning !== undefined && !validModelReasoning(model.reasoning))) {
|
|
221
|
+
throw new Error(`Harness returned an invalid response for ${method}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
for (const failure of value.failures) {
|
|
226
|
+
if (!failure || typeof failure !== 'object'
|
|
227
|
+
|| typeof failure.id !== 'string' || !failure.id
|
|
228
|
+
|| typeof failure.name !== 'string' || !failure.name
|
|
229
|
+
|| (failure.message !== undefined && typeof failure.message !== 'string')) {
|
|
230
|
+
throw new Error(`Harness returned an invalid response for ${method}`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (session && (!validModelSelection(value.current) || typeof value.routable !== 'boolean')) {
|
|
234
|
+
throw new Error(`Harness returned an invalid response for ${method}`);
|
|
235
|
+
}
|
|
236
|
+
return value;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function turnStoppedError() {
|
|
240
|
+
const error = new Error('Harness turn was stopped before producing a text reply');
|
|
241
|
+
error.code = 'turn-stopped';
|
|
242
|
+
return error;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function workspacePaths(value) {
|
|
246
|
+
if (!Array.isArray(value?.items)) return [];
|
|
247
|
+
return value.items.flatMap((item) => (
|
|
248
|
+
typeof item?.path === 'string' && isAbsolute(item.path) ? [item.path] : []
|
|
249
|
+
));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function workspaceFromList(workspacePath, workspaceList) {
|
|
253
|
+
if (!Array.isArray(workspaceList?.items)
|
|
254
|
+
|| !Array.isArray(workspaceList?.archivedSessionIds)) {
|
|
255
|
+
throw new Error('Harness returned an invalid response for workspace.list');
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const workspace = workspaceList.items.find((item) => item?.path === workspacePath);
|
|
259
|
+
if (!workspace) return null;
|
|
260
|
+
if (!Array.isArray(workspace.sessionIds)
|
|
261
|
+
|| workspace.sessionIds.some((sessionId) => typeof sessionId !== 'string')) {
|
|
262
|
+
throw new Error('Harness returned invalid session IDs for workspace.list');
|
|
263
|
+
}
|
|
264
|
+
return workspace;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function toEpochMs(value) {
|
|
268
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
269
|
+
return value < 1e12 ? value * 1000 : value;
|
|
270
|
+
}
|
|
271
|
+
if (typeof value === 'string' && value) {
|
|
272
|
+
const parsed = Date.parse(value);
|
|
273
|
+
if (!Number.isNaN(parsed)) return parsed;
|
|
274
|
+
}
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function sessionTimeMs(summary) {
|
|
279
|
+
if (!summary || typeof summary !== 'object') return null;
|
|
280
|
+
const candidates = [
|
|
281
|
+
summary?.header?.lastActivityAt,
|
|
282
|
+
summary?.header?.updatedAt,
|
|
283
|
+
summary?.header?.createdAt,
|
|
284
|
+
summary?.projections?.values?.lastActivityAt,
|
|
285
|
+
summary?.projections?.values?.updatedAt,
|
|
286
|
+
summary?.projections?.values?.createdAt,
|
|
287
|
+
summary?.lastActivityAt,
|
|
288
|
+
summary?.updatedAt,
|
|
289
|
+
summary?.createdAt,
|
|
290
|
+
];
|
|
291
|
+
for (const value of candidates) {
|
|
292
|
+
const ms = toEpochMs(value);
|
|
293
|
+
if (ms !== null) return ms;
|
|
294
|
+
}
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function workspaceSessions(workspace, archivedSessionIds, sessionList) {
|
|
299
|
+
if (!Array.isArray(sessionList?.items)) {
|
|
300
|
+
throw new Error('Harness returned an invalid response for session.list');
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const archived = new Set(archivedSessionIds);
|
|
304
|
+
const summaries = new Map(sessionList.items.flatMap((item) => (
|
|
305
|
+
typeof item?.sessionId === 'string' ? [[item.sessionId, item]] : []
|
|
306
|
+
)));
|
|
307
|
+
return {
|
|
308
|
+
workspace: workspace.path,
|
|
309
|
+
sessions: workspace.sessionIds.map((sessionId) => {
|
|
310
|
+
const summary = summaries.get(sessionId);
|
|
311
|
+
const title = summary?.projections?.values?.title;
|
|
312
|
+
const session = {
|
|
313
|
+
sessionId,
|
|
314
|
+
title: typeof title === 'string' ? title : null,
|
|
315
|
+
archived: archived.has(sessionId),
|
|
316
|
+
blank: summary?.blank === true,
|
|
317
|
+
origin: summary?.origin === 'subagent' ? 'subagent' : null,
|
|
318
|
+
summaryAvailable: summary !== undefined,
|
|
319
|
+
};
|
|
320
|
+
const lastSeq = summary?.projections?.asOfSeq;
|
|
321
|
+
// This is the projection's durable lower bound, not necessarily the live
|
|
322
|
+
// log tail for a cold session. Harness uses -1 as the legitimate bound
|
|
323
|
+
// for a session with no projected events yet.
|
|
324
|
+
if (Number.isSafeInteger(lastSeq) && lastSeq >= -1) session.lastSeq = lastSeq;
|
|
325
|
+
const time = sessionTimeMs(summary);
|
|
326
|
+
if (time !== null) session.time = time;
|
|
327
|
+
return session;
|
|
328
|
+
}),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function sleep(ms, signal) {
|
|
333
|
+
return new Promise((resolve, reject) => {
|
|
334
|
+
if (signal?.aborted) {
|
|
335
|
+
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
const timer = setTimeout(() => {
|
|
339
|
+
signal?.removeEventListener('abort', onAbort);
|
|
340
|
+
resolve();
|
|
341
|
+
}, ms);
|
|
342
|
+
const onAbort = () => {
|
|
343
|
+
clearTimeout(timer);
|
|
344
|
+
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
|
|
345
|
+
};
|
|
346
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Join only visible text blocks from one Harness message payload. */
|
|
351
|
+
export function textFromHarnessContent(content) {
|
|
352
|
+
return (Array.isArray(content) ? content : [])
|
|
353
|
+
.filter((part) => part?.type === 'text' && typeof part.text === 'string')
|
|
354
|
+
.map((part) => part.text)
|
|
355
|
+
.join('\n')
|
|
356
|
+
.trim();
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Join only reasoning blocks from one Harness message payload. */
|
|
360
|
+
export function reasoningFromHarnessContent(content) {
|
|
361
|
+
return (Array.isArray(content) ? content : [])
|
|
362
|
+
.filter((part) => part?.type === 'reasoning' && typeof part.text === 'string')
|
|
363
|
+
.map((part) => part.text)
|
|
364
|
+
.join('\n')
|
|
365
|
+
.trim();
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function assistantMessageText(event) {
|
|
369
|
+
return textFromHarnessContent(event?.data?.message?.content);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function assistantReasoningText(event) {
|
|
373
|
+
return reasoningFromHarnessContent(event?.data?.message?.content);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Aggregate assistant text in stable step/index order for one Harness Turn. */
|
|
377
|
+
export class AssistantTextAccumulator {
|
|
378
|
+
#steps = new Map();
|
|
379
|
+
#legacyText = '';
|
|
380
|
+
|
|
381
|
+
appendDelta(step, index, text) {
|
|
382
|
+
if (typeof text !== 'string' || !text) return;
|
|
383
|
+
const stepNumber = Number.isSafeInteger(step) ? step : 0;
|
|
384
|
+
const partIndex = Number.isSafeInteger(index) ? index : 0;
|
|
385
|
+
this.#legacyText = '';
|
|
386
|
+
const parts = this.#steps.get(stepNumber) ?? new Map();
|
|
387
|
+
parts.set(partIndex, (parts.get(partIndex) ?? '') + text);
|
|
388
|
+
this.#steps.set(stepNumber, parts);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
setCanonical(step, text) {
|
|
392
|
+
if (typeof text !== 'string' || !text.trim()) return;
|
|
393
|
+
if (!Number.isSafeInteger(step)) {
|
|
394
|
+
this.#steps.clear();
|
|
395
|
+
this.#legacyText = text.trim();
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
this.#legacyText = '';
|
|
399
|
+
this.#steps.set(step, new Map([[0, text.trim()]]));
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
get text() {
|
|
403
|
+
if (this.#steps.size === 0) return this.#legacyText;
|
|
404
|
+
return [...this.#steps.entries()]
|
|
405
|
+
.sort(([left], [right]) => left - right)
|
|
406
|
+
.map(([, parts]) => [...parts.entries()]
|
|
407
|
+
.sort(([left], [right]) => left - right)
|
|
408
|
+
.map(([, text]) => text)
|
|
409
|
+
.join('\n')
|
|
410
|
+
.trim())
|
|
411
|
+
.filter(Boolean)
|
|
412
|
+
.join('\n\n');
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function nonEmptyText(value) {
|
|
417
|
+
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Flatten a tool/result error payload into a displayable one-line reason. */
|
|
421
|
+
function toolResultErrorText(error) {
|
|
422
|
+
if (!error || typeof error !== 'object') return null;
|
|
423
|
+
const message = nonEmptyText(error.message);
|
|
424
|
+
if (message) return message;
|
|
425
|
+
const name = nonEmptyText(error.name);
|
|
426
|
+
const code = nonEmptyText(error.code);
|
|
427
|
+
if (name || code) return [name ?? 'Error', code].filter(Boolean).join(': ');
|
|
428
|
+
return null;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Join the visible text carried by a Harness tool result. */
|
|
432
|
+
function toolResultText(data) {
|
|
433
|
+
const blocks = Array.isArray(data?.message?.content) ? data.message.content : [];
|
|
434
|
+
const nested = blocks.flatMap((block) => (
|
|
435
|
+
Array.isArray(block?.content) ? block.content : [block]
|
|
436
|
+
));
|
|
437
|
+
const text = nested
|
|
438
|
+
.filter((block) => block?.type === 'text' && typeof block.text === 'string')
|
|
439
|
+
.map((block) => block.text)
|
|
440
|
+
.join('');
|
|
441
|
+
return text || nonEmptyText(data?.text) || toolResultErrorText(data?.error) || '';
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function toolResultCallId(data) {
|
|
445
|
+
const blocks = Array.isArray(data?.message?.content) ? data.message.content : [];
|
|
446
|
+
return blocks
|
|
447
|
+
.map((block) => nonEmptyText(block?.toolCallId))
|
|
448
|
+
.find(Boolean)
|
|
449
|
+
?? nonEmptyText(data?.message?.source?.callId)
|
|
450
|
+
?? nonEmptyText(data?.callId)
|
|
451
|
+
?? nonEmptyText(data?.subCallId);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function consumeInteractionOwnership(ownership, entries) {
|
|
455
|
+
const ordered = [...entries]
|
|
456
|
+
.map((entry) => entry?.event ?? entry)
|
|
457
|
+
.filter(Boolean)
|
|
458
|
+
.sort((left, right) => (left.seq ?? -1) - (right.seq ?? -1));
|
|
459
|
+
|
|
460
|
+
for (const event of ordered) {
|
|
461
|
+
const seq = event.seq ?? -1;
|
|
462
|
+
if (seq <= ownership.lastSeq) continue;
|
|
463
|
+
ownership.lastSeq = seq;
|
|
464
|
+
|
|
465
|
+
if (event.type === 'turn/start') {
|
|
466
|
+
const turn = event.data?.turn ?? null;
|
|
467
|
+
if (ownership.active && turn !== ownership.turn) ownership.active = false;
|
|
468
|
+
if (ownership.turn !== null && turn !== ownership.turn) ownership.completed = true;
|
|
469
|
+
ownership.openTurn = turn;
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (event.type === 'user/message' && event.data?.source?.rpcId === ownership.promptRpcId) {
|
|
473
|
+
ownership.active = true;
|
|
474
|
+
ownership.started = true;
|
|
475
|
+
ownership.completed = false;
|
|
476
|
+
ownership.turn = event.data?.turn ?? ownership.openTurn;
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
if (event.type === 'turn/end' && event.data?.turn === ownership.turn) {
|
|
480
|
+
ownership.active = false;
|
|
481
|
+
ownership.completed = true;
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
let toolCall = null;
|
|
485
|
+
if (event.type === 'tool/call'
|
|
486
|
+
&& ownership.active
|
|
487
|
+
&& event.data?.turn === ownership.turn
|
|
488
|
+
&& typeof event.data?.callId === 'string'
|
|
489
|
+
&& event.data.callId) {
|
|
490
|
+
toolCall = {
|
|
491
|
+
callId: event.data.callId,
|
|
492
|
+
name: event.data?.name,
|
|
493
|
+
arguments: event.data?.arguments,
|
|
494
|
+
};
|
|
495
|
+
} else if (event.type === 'tool/code-dispatch-start'
|
|
496
|
+
&& ownership.active
|
|
497
|
+
&& typeof event.data?.subCallId === 'string'
|
|
498
|
+
&& event.data.subCallId) {
|
|
499
|
+
let argumentsText;
|
|
500
|
+
try {
|
|
501
|
+
argumentsText = JSON.stringify(event.data?.arguments);
|
|
502
|
+
} catch {
|
|
503
|
+
argumentsText = undefined;
|
|
504
|
+
}
|
|
505
|
+
toolCall = {
|
|
506
|
+
callId: event.data.subCallId,
|
|
507
|
+
name: event.data?.name,
|
|
508
|
+
arguments: argumentsText,
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
if (toolCall) ownership.toolCalls.set(toolCall.callId, Object.freeze(toolCall));
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Decide whether the current Host has a live dsh-im interaction watcher for
|
|
517
|
+
* this Session. The modern Harness adapter uses the same ownership registry
|
|
518
|
+
* as HarnessClient so it never steals a browser-owned question or approval.
|
|
519
|
+
*/
|
|
520
|
+
export function hasActiveHarnessInteractionOwner(scope, sessionId, entries = []) {
|
|
521
|
+
if (!scope || !['object', 'function', 'string'].includes(typeof scope)
|
|
522
|
+
|| typeof sessionId !== 'string' || !sessionId) return false;
|
|
523
|
+
const owners = interactionRegistry(scope).ownerships.get(sessionId);
|
|
524
|
+
if (!owners || owners.size === 0) return false;
|
|
525
|
+
for (const ownership of owners) consumeInteractionOwnership(ownership, entries);
|
|
526
|
+
return [...owners].some((ownership) => (
|
|
527
|
+
ownership.active
|
|
528
|
+
&& !ownership.completed
|
|
529
|
+
&& typeof ownership.reconnect === 'function'
|
|
530
|
+
));
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
export class HarnessReplyTracker {
|
|
534
|
+
#promptRpcId;
|
|
535
|
+
#lastSeq;
|
|
536
|
+
#openTurn = null;
|
|
537
|
+
#targetTurn = null;
|
|
538
|
+
#assistantText = new AssistantTextAccumulator();
|
|
539
|
+
#latestText = '';
|
|
540
|
+
#finished = false;
|
|
541
|
+
#reason = null;
|
|
542
|
+
#toolNames = new Map();
|
|
543
|
+
#lastToolName = null;
|
|
544
|
+
#transientSeqs = new Set();
|
|
545
|
+
#pendingReasoning = new Map();
|
|
546
|
+
#pendingReasoningChars = 0;
|
|
547
|
+
#reasoning = false;
|
|
548
|
+
|
|
549
|
+
constructor({ promptRpcId, afterSeq = -1, reasoning = false }) {
|
|
550
|
+
this.#promptRpcId = promptRpcId;
|
|
551
|
+
this.#lastSeq = afterSeq;
|
|
552
|
+
// Reasoning updates are opt-in per consumer: only channels that surface
|
|
553
|
+
// thinking traces (Telegram thinking mode) subscribe; every other channel
|
|
554
|
+
// keeps its pre-thinking-traces update stream untouched.
|
|
555
|
+
this.#reasoning = reasoning === true;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
get finished() {
|
|
559
|
+
return this.#finished;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** The highest event seq consumed so far; advances as the turn produces events. */
|
|
563
|
+
get lastSeq() {
|
|
564
|
+
return this.#lastSeq;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
get answer() {
|
|
568
|
+
return this.#latestText.trim();
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
get reason() {
|
|
572
|
+
return this.#reason;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
get tracking() {
|
|
576
|
+
return this.#targetTurn !== null && !this.#finished;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
get turn() {
|
|
580
|
+
return this.#targetTurn;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
#commitText(text, pushUpdate) {
|
|
584
|
+
if (!text || text === this.#latestText) return;
|
|
585
|
+
this.#latestText = text;
|
|
586
|
+
pushUpdate({ type: 'text', text });
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
#bufferReasoning(event) {
|
|
590
|
+
const text = event.data?.chunk?.text;
|
|
591
|
+
if (typeof text !== 'string' || !text || text.length > 65536
|
|
592
|
+
|| this.#pendingReasoning.has(event.seq)) return;
|
|
593
|
+
this.#pendingReasoning.set(event.seq, event);
|
|
594
|
+
this.#pendingReasoningChars += text.length;
|
|
595
|
+
while (this.#pendingReasoning.size > 256 || this.#pendingReasoningChars > 65536) {
|
|
596
|
+
const [seq, oldest] = this.#pendingReasoning.entries().next().value;
|
|
597
|
+
this.#pendingReasoning.delete(seq);
|
|
598
|
+
this.#pendingReasoningChars -= oldest.data.chunk.text.length;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
#takePendingReasoning() {
|
|
603
|
+
const events = [...this.#pendingReasoning.values()];
|
|
604
|
+
this.#pendingReasoning.clear();
|
|
605
|
+
this.#pendingReasoningChars = 0;
|
|
606
|
+
return events;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
#emitReasoning(event, pushUpdate) {
|
|
610
|
+
const text = event.data?.chunk?.text;
|
|
611
|
+
if (event.data?.turn !== this.#targetTurn || this.#transientSeqs.has(event.seq)
|
|
612
|
+
|| typeof text !== 'string' || !text) return;
|
|
613
|
+
this.#transientSeqs.add(event.seq);
|
|
614
|
+
pushUpdate({ type: 'reasoning', turn: this.#targetTurn, text });
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
consumeAll(entries, { live = false, fromMux = false } = {}) {
|
|
618
|
+
const updates = [];
|
|
619
|
+
// 同一批轮询内的 text 帧只保留最新累积,其余事件逐帧透出,
|
|
620
|
+
// 让消费方能按顺序看到每个工具调用与结果。
|
|
621
|
+
const pushUpdate = (update) => {
|
|
622
|
+
if (update.type === 'text' && updates.length > 0) {
|
|
623
|
+
const last = updates[updates.length - 1];
|
|
624
|
+
if (last.type === 'text') {
|
|
625
|
+
updates[updates.length - 1] = update;
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
updates.push(update);
|
|
630
|
+
};
|
|
631
|
+
const ordered = [...(fromMux ? [] : this.#takePendingReasoning()), ...entries]
|
|
632
|
+
.map((entry) => entry?.event ?? entry)
|
|
633
|
+
.filter(Boolean)
|
|
634
|
+
.sort((left, right) => (left.seq ?? -1) - (right.seq ?? -1));
|
|
635
|
+
|
|
636
|
+
for (const event of ordered) {
|
|
637
|
+
if (this.#finished) break;
|
|
638
|
+
const seq = event.seq ?? -1;
|
|
639
|
+
const isReasoning = event.type === 'assistant/chunk'
|
|
640
|
+
&& event.data?.chunk?.type === 'reasoning-delta';
|
|
641
|
+
// The mux is lossy across reconnects. Only history may advance the
|
|
642
|
+
// durable cursor or finish the reply; the mux supplements reasoning.
|
|
643
|
+
if (fromMux && !isReasoning) continue;
|
|
644
|
+
if (isReasoning) {
|
|
645
|
+
if (!live || !Number.isFinite(seq)) continue;
|
|
646
|
+
if (this.#targetTurn === null) this.#bufferReasoning(event);
|
|
647
|
+
else this.#emitReasoning(event, pushUpdate);
|
|
648
|
+
continue;
|
|
649
|
+
}
|
|
650
|
+
if (this.#targetTurn === null) {
|
|
651
|
+
if (seq <= this.#lastSeq) continue;
|
|
652
|
+
if (event.type === 'turn/start') {
|
|
653
|
+
this.#openTurn = event.data?.turn ?? null;
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
656
|
+
if (event.type === 'user/message' && event.data?.source?.rpcId === this.#promptRpcId) {
|
|
657
|
+
this.#lastSeq = seq;
|
|
658
|
+
this.#targetTurn = event.data?.turn ?? this.#openTurn;
|
|
659
|
+
if (live && this.#targetTurn !== null) {
|
|
660
|
+
pushUpdate({ type: 'turn-start', turn: this.#targetTurn });
|
|
661
|
+
// Only earlier fragments flush here. Later steps remain in the
|
|
662
|
+
// sorted batch, interleaved with their tool calls and results.
|
|
663
|
+
for (const pending of this.#takePendingReasoning()) {
|
|
664
|
+
this.#emitReasoning(pending, pushUpdate);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
if (seq <= this.#lastSeq) continue;
|
|
671
|
+
this.#lastSeq = seq;
|
|
672
|
+
|
|
673
|
+
if (event.type === 'turn/start') this.#openTurn = event.data?.turn ?? null;
|
|
674
|
+
|
|
675
|
+
if (event.type === 'user/message' && event.data?.source?.rpcId === this.#promptRpcId) {
|
|
676
|
+
this.#targetTurn = event.data?.turn ?? this.#openTurn;
|
|
677
|
+
if (live) pushUpdate({ type: 'turn-start', turn: this.#targetTurn });
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
680
|
+
if (this.#targetTurn === null) continue;
|
|
681
|
+
|
|
682
|
+
if (event.type === 'turn/end') {
|
|
683
|
+
if (event.data?.turn !== this.#targetTurn) continue;
|
|
684
|
+
this.#finished = true;
|
|
685
|
+
this.#reason = event.data?.reason ?? null;
|
|
686
|
+
this.#openTurn = null;
|
|
687
|
+
if (live) {
|
|
688
|
+
pushUpdate({
|
|
689
|
+
type: 'turn-end',
|
|
690
|
+
turn: this.#targetTurn,
|
|
691
|
+
reason: this.#reason,
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
if (event.data?.turn !== this.#targetTurn) continue;
|
|
697
|
+
|
|
698
|
+
if (event.type === 'assistant/chunk' && event.data?.chunk?.type === 'text-delta') {
|
|
699
|
+
const step = event.data?.step ?? 0;
|
|
700
|
+
const index = event.data.chunk.index ?? 0;
|
|
701
|
+
this.#assistantText.appendDelta(step, index, event.data.chunk.text);
|
|
702
|
+
this.#commitText(this.#assistantText.text, pushUpdate);
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
if (event.type === 'assistant/message') {
|
|
707
|
+
const text = assistantMessageText(event);
|
|
708
|
+
const step = Number.isSafeInteger(event.data?.step) ? event.data.step : null;
|
|
709
|
+
this.#assistantText.setCanonical(step, text);
|
|
710
|
+
// canonical 定稿且非空时按 step 透出,供分步推送消费方使用;
|
|
711
|
+
// 先于 commitText 透出,保持 text 更新作为批次末尾的既有语义。
|
|
712
|
+
if (text) {
|
|
713
|
+
pushUpdate({
|
|
714
|
+
type: 'assistant-message',
|
|
715
|
+
step,
|
|
716
|
+
text,
|
|
717
|
+
...(live ? { turn: this.#targetTurn } : {}),
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
// Thinking-trace channels consume this as the 💭 line that precedes the
|
|
721
|
+
// tool call it explains; only consumers that explicitly subscribed
|
|
722
|
+
// (reasoning: true) see these updates, so default-mode channels keep
|
|
723
|
+
// their pre-thinking-traces progress stream.
|
|
724
|
+
if (this.#reasoning) {
|
|
725
|
+
const reasoning = assistantReasoningText(event);
|
|
726
|
+
if (reasoning) pushUpdate({ type: 'reasoning', step, text: reasoning });
|
|
727
|
+
}
|
|
728
|
+
this.#commitText(this.#assistantText.text, pushUpdate);
|
|
729
|
+
continue;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
if (event.type === 'tool/call') {
|
|
733
|
+
const name = nonEmptyText(event.data?.name) ?? t('工具');
|
|
734
|
+
const callId = nonEmptyText(event.data?.callId)
|
|
735
|
+
?? nonEmptyText(event.data?.subCallId);
|
|
736
|
+
if (callId) this.#toolNames.set(callId, name);
|
|
737
|
+
this.#lastToolName = name;
|
|
738
|
+
let argsText = null;
|
|
739
|
+
if (event.data?.arguments !== undefined && event.data?.arguments !== null) {
|
|
740
|
+
if (typeof event.data.arguments === 'string') {
|
|
741
|
+
argsText = event.data.arguments;
|
|
742
|
+
} else {
|
|
743
|
+
try {
|
|
744
|
+
argsText = JSON.stringify(event.data.arguments);
|
|
745
|
+
} catch {
|
|
746
|
+
argsText = undefined;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
pushUpdate({
|
|
751
|
+
type: 'tool',
|
|
752
|
+
name,
|
|
753
|
+
...(argsText ? { arguments: argsText } : {}),
|
|
754
|
+
...(callId ? { callId } : {}),
|
|
755
|
+
...(live ? { turn: this.#targetTurn } : {}),
|
|
756
|
+
});
|
|
757
|
+
} else if (event.type === 'tool/result') {
|
|
758
|
+
const callId = toolResultCallId(event.data);
|
|
759
|
+
const toolName = (callId ? this.#toolNames.get(callId) : null)
|
|
760
|
+
?? this.#lastToolName;
|
|
761
|
+
const error = toolResultErrorText(event.data?.error);
|
|
762
|
+
if (live) {
|
|
763
|
+
const providerErrorCode = event.data?.error?.code;
|
|
764
|
+
pushUpdate({
|
|
765
|
+
type: 'tool-result',
|
|
766
|
+
turn: this.#targetTurn,
|
|
767
|
+
...(callId ? { callId } : {}),
|
|
768
|
+
...(toolName ? { toolName } : {}),
|
|
769
|
+
text: toolResultText(event.data),
|
|
770
|
+
...(providerErrorCode !== undefined && providerErrorCode !== null
|
|
771
|
+
? { errorCode: String(providerErrorCode) }
|
|
772
|
+
: {}),
|
|
773
|
+
});
|
|
774
|
+
} else {
|
|
775
|
+
pushUpdate({
|
|
776
|
+
type: 'status',
|
|
777
|
+
text: t('正在整理结果…'),
|
|
778
|
+
...(toolName ? { toolName } : {}),
|
|
779
|
+
...(error ? { error } : {}),
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return updates;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
consume(entries) {
|
|
788
|
+
return this.consumeAll(entries).at(-1) ?? null;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/**
|
|
793
|
+
* Progress updates an ask() consumer actually receives. latest 模式只投递一条
|
|
794
|
+
* 最新进展;assistant-message 是分步推送专用更新,且 canonical 去重后可能成为
|
|
795
|
+
* 批次唯一变化,绝不能冒充进度投给全部渠道。reasoning 同为思考留痕渠道专用,
|
|
796
|
+
* 默认模式下不得冒充进度(钉钉、企微等会展示其 text)。
|
|
797
|
+
*/
|
|
798
|
+
export function visibleProgressUpdates(updates, progressMode) {
|
|
799
|
+
if (progressMode === 'all') return updates;
|
|
800
|
+
return updates
|
|
801
|
+
.filter((update) => update.type !== 'assistant-message' && update.type !== 'reasoning')
|
|
802
|
+
.slice(-1);
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
export class HarnessRpcError extends Error {
|
|
806
|
+
constructor(method, error) {
|
|
807
|
+
super(`${method}: ${error?.message ?? 'unknown Harness RPC error'}`);
|
|
808
|
+
this.name = 'HarnessRpcError';
|
|
809
|
+
this.method = method;
|
|
810
|
+
this.code = error?.code ?? 'internal';
|
|
811
|
+
this.details = error?.details ?? {};
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
export class HarnessTransportError extends Error {
|
|
816
|
+
constructor(code, method, { cause, status } = {}) {
|
|
817
|
+
const statusDetail = Number.isInteger(status) ? `, HTTP ${status}` : '';
|
|
818
|
+
super(`Harness ${method} transport failed (${code}${statusDetail})`, { cause });
|
|
819
|
+
this.name = 'HarnessTransportError';
|
|
820
|
+
this.code = code;
|
|
821
|
+
this.method = method;
|
|
822
|
+
if (Number.isInteger(status)) this.status = status;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
export class HarnessHealthError extends Error {
|
|
827
|
+
constructor(cause) {
|
|
828
|
+
super('Harness health RPC was rejected', { cause });
|
|
829
|
+
this.name = 'HarnessHealthError';
|
|
830
|
+
this.code = 'harness-rpc-rejected';
|
|
831
|
+
this.method = 'host.describe';
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
export class HarnessInteractionError extends Error {
|
|
836
|
+
constructor(code, message) {
|
|
837
|
+
super(message);
|
|
838
|
+
this.name = 'HarnessInteractionError';
|
|
839
|
+
this.code = code;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
export class HarnessTurnError extends Error {
|
|
844
|
+
constructor(code, { reason, providerCode } = {}) {
|
|
845
|
+
super(`Harness turn failed (${code})`);
|
|
846
|
+
this.name = 'HarnessTurnError';
|
|
847
|
+
this.code = code;
|
|
848
|
+
this.promptAccepted = true;
|
|
849
|
+
if (reason && typeof reason === 'object') this.reason = reason;
|
|
850
|
+
if (typeof providerCode === 'string' && providerCode) this.providerCode = providerCode;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
function harnessTurnError(reason) {
|
|
855
|
+
const kind = nonEmptyText(reason?.kind) ?? nonEmptyText(reason);
|
|
856
|
+
if (kind === 'error') {
|
|
857
|
+
const failure = reason?.error ?? reason?.failure;
|
|
858
|
+
return new HarnessTurnError('harness-turn-failed', {
|
|
859
|
+
reason,
|
|
860
|
+
providerCode: nonEmptyText(failure?.code) ?? undefined,
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
if (kind === 'max-tokens') return new HarnessTurnError('model-max-tokens', { reason });
|
|
864
|
+
if (kind === 'blocked') return new HarnessTurnError('turn-blocked', { reason });
|
|
865
|
+
if (['interrupted', 'stopped', 'cancelled', 'canceled'].includes(kind)) {
|
|
866
|
+
return new HarnessTurnError('turn-interrupted', { reason });
|
|
867
|
+
}
|
|
868
|
+
if (kind === 'aborted') return new HarnessTurnError('turn-aborted', { reason });
|
|
869
|
+
return new HarnessTurnError('harness-turn-failed', { reason });
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
function harnessTurnSucceeded(reason) {
|
|
873
|
+
if (reason === null || reason === undefined) return true;
|
|
874
|
+
return (nonEmptyText(reason?.kind) ?? nonEmptyText(reason)) === 'completed';
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
export class HarnessClient {
|
|
878
|
+
#baseUrl;
|
|
879
|
+
#apiProxy;
|
|
880
|
+
#workspace;
|
|
881
|
+
#ungroupedWorkspace;
|
|
882
|
+
#agentPreset;
|
|
883
|
+
#autostart;
|
|
884
|
+
#dshBin;
|
|
885
|
+
#fetch;
|
|
886
|
+
#createWebSocket;
|
|
887
|
+
#interactionReconnectDelayMs;
|
|
888
|
+
#rpcIdPrefix;
|
|
889
|
+
#logPrefix;
|
|
890
|
+
#commandExecutor;
|
|
891
|
+
#controlExecutor;
|
|
892
|
+
#sessionMaintenanceExecutor;
|
|
893
|
+
#fileIngressExecutor;
|
|
894
|
+
#imageInputPolicy;
|
|
895
|
+
#managedProcess = null;
|
|
896
|
+
#interactionRegistry;
|
|
897
|
+
#interactionOwnerships;
|
|
898
|
+
#interactionClaims;
|
|
899
|
+
#controlOwnerships;
|
|
900
|
+
|
|
901
|
+
constructor({
|
|
902
|
+
baseUrl,
|
|
903
|
+
apiProxy,
|
|
904
|
+
interactionScope = apiProxy,
|
|
905
|
+
workspace,
|
|
906
|
+
ungroupedWorkspace,
|
|
907
|
+
agentPreset,
|
|
908
|
+
autostart = false,
|
|
909
|
+
dshBin = 'dsh',
|
|
910
|
+
fetchImpl = fetch,
|
|
911
|
+
createWebSocket = (url) => new WebSocket(url),
|
|
912
|
+
interactionReconnectDelayMs = 500,
|
|
913
|
+
rpcIdPrefix = 'im',
|
|
914
|
+
logPrefix = 'dsh-im',
|
|
915
|
+
commandExecutor,
|
|
916
|
+
controlExecutor,
|
|
917
|
+
sessionMaintenanceExecutor,
|
|
918
|
+
fileIngressExecutor,
|
|
919
|
+
imageInputPolicy = () => undefined,
|
|
920
|
+
}) {
|
|
921
|
+
if (typeof createWebSocket !== 'function') {
|
|
922
|
+
throw new TypeError('createWebSocket must be a function');
|
|
923
|
+
}
|
|
924
|
+
if (!Number.isFinite(interactionReconnectDelayMs) || interactionReconnectDelayMs < 0) {
|
|
925
|
+
throw new TypeError('interactionReconnectDelayMs must be a non-negative number');
|
|
926
|
+
}
|
|
927
|
+
if (typeof rpcIdPrefix !== 'string' || !rpcIdPrefix.trim()) {
|
|
928
|
+
throw new TypeError('rpcIdPrefix must be a non-empty string');
|
|
929
|
+
}
|
|
930
|
+
if (typeof logPrefix !== 'string' || !logPrefix.trim()) {
|
|
931
|
+
throw new TypeError('logPrefix must be a non-empty string');
|
|
932
|
+
}
|
|
933
|
+
if (commandExecutor !== undefined && typeof commandExecutor !== 'function') {
|
|
934
|
+
throw new TypeError('commandExecutor must be a function');
|
|
935
|
+
}
|
|
936
|
+
if (controlExecutor !== undefined && typeof controlExecutor !== 'function') {
|
|
937
|
+
throw new TypeError('controlExecutor must be a function');
|
|
938
|
+
}
|
|
939
|
+
if (sessionMaintenanceExecutor !== undefined
|
|
940
|
+
&& typeof sessionMaintenanceExecutor !== 'function') {
|
|
941
|
+
throw new TypeError('sessionMaintenanceExecutor must be a function');
|
|
942
|
+
}
|
|
943
|
+
if (fileIngressExecutor !== undefined && typeof fileIngressExecutor !== 'function') {
|
|
944
|
+
throw new TypeError('fileIngressExecutor must be a function');
|
|
945
|
+
}
|
|
946
|
+
this.#baseUrl = baseUrl === undefined ? null : new URL(baseUrl);
|
|
947
|
+
this.#apiProxy = this.#baseUrl ? null : apiProxy;
|
|
948
|
+
if (!this.#baseUrl && (!this.#apiProxy || typeof this.#apiProxy !== 'object')) {
|
|
949
|
+
throw new TypeError('HarnessClient requires the current Host apiProxy or an explicit baseUrl');
|
|
950
|
+
}
|
|
951
|
+
if (this.#apiProxy && (!interactionScope
|
|
952
|
+
|| !['object', 'function'].includes(typeof interactionScope))) {
|
|
953
|
+
throw new TypeError('interactionScope must identify the current Host');
|
|
954
|
+
}
|
|
955
|
+
this.#workspace = workspace;
|
|
956
|
+
// Only the reserved IM directory bypasses grouping, even after /ws switches.
|
|
957
|
+
this.#ungroupedWorkspace = ungroupedWorkspace;
|
|
958
|
+
// Keep an omitted preset absent so session.create resolves the Host's current default.
|
|
959
|
+
this.#agentPreset = agentPreset ?? undefined;
|
|
960
|
+
this.#autostart = Boolean(this.#baseUrl && autostart);
|
|
961
|
+
this.#dshBin = dshBin;
|
|
962
|
+
this.#fetch = fetchImpl;
|
|
963
|
+
this.#createWebSocket = createWebSocket;
|
|
964
|
+
this.#interactionReconnectDelayMs = interactionReconnectDelayMs;
|
|
965
|
+
this.#rpcIdPrefix = rpcIdPrefix.trim();
|
|
966
|
+
this.#logPrefix = logPrefix.trim();
|
|
967
|
+
this.#commandExecutor = commandExecutor;
|
|
968
|
+
this.#controlExecutor = controlExecutor;
|
|
969
|
+
this.#sessionMaintenanceExecutor = sessionMaintenanceExecutor;
|
|
970
|
+
this.#fileIngressExecutor = fileIngressExecutor;
|
|
971
|
+
this.#imageInputPolicy = imageInputPolicy;
|
|
972
|
+
this.#interactionRegistry = interactionRegistry(this.#baseUrl?.origin ?? interactionScope);
|
|
973
|
+
this.#interactionOwnerships = this.#interactionRegistry.ownerships;
|
|
974
|
+
this.#interactionClaims = this.#interactionRegistry.claims;
|
|
975
|
+
this.#controlOwnerships = this.#interactionRegistry.controls;
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
async rpc(method, payload = {}, timeoutMs = 30_000, options = {}) {
|
|
979
|
+
const rpcId = options.rpcId ?? `${this.#rpcIdPrefix}-${randomUUID()}`;
|
|
980
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
981
|
+
const signal = options.signal
|
|
982
|
+
? AbortSignal.any([options.signal, timeoutSignal])
|
|
983
|
+
: timeoutSignal;
|
|
984
|
+
let body;
|
|
985
|
+
try {
|
|
986
|
+
if (this.#apiProxy) {
|
|
987
|
+
const [domain, action, extra] = method.split('.');
|
|
988
|
+
const namespace = { host: 'host', workspace: 'workspace', session: 'sessions', llm: 'llm' }[domain];
|
|
989
|
+
const api = namespace && this.#apiProxy[namespace];
|
|
990
|
+
if (extra !== undefined || !Object.hasOwn(api ?? {}, action)
|
|
991
|
+
|| typeof api[action] !== 'function') {
|
|
992
|
+
throw new HarnessTransportError('harness-api-not-found', method);
|
|
993
|
+
}
|
|
994
|
+
const response = await callWithSignal(() => api[action]({ rpcId, payload }, signal), signal);
|
|
995
|
+
body = { type: 'server-response', ...response };
|
|
996
|
+
} else {
|
|
997
|
+
const response = await this.#fetch(new URL(`/api/${method}`, this.#baseUrl), {
|
|
998
|
+
method: 'POST',
|
|
999
|
+
headers: { 'content-type': 'application/json' },
|
|
1000
|
+
body: JSON.stringify({ type: 'client-request', rpcId, method, payload }),
|
|
1001
|
+
signal,
|
|
1002
|
+
});
|
|
1003
|
+
if (!response.ok) {
|
|
1004
|
+
const code = await harnessHttpErrorCode(response, this.#baseUrl.hostname);
|
|
1005
|
+
throw new HarnessTransportError(code, method, { status: response.status });
|
|
1006
|
+
}
|
|
1007
|
+
try {
|
|
1008
|
+
body = await response.json();
|
|
1009
|
+
} catch (error) {
|
|
1010
|
+
throw new HarnessTransportError('harness-response-invalid', method, { cause: error });
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
// Preserve an explicit caller cancellation; it is control flow, not a
|
|
1015
|
+
// Harness availability diagnosis.
|
|
1016
|
+
if (options.signal?.aborted) throw error;
|
|
1017
|
+
if (error instanceof HarnessTransportError) throw error;
|
|
1018
|
+
throw new HarnessTransportError(
|
|
1019
|
+
timeoutSignal.aborted ? 'harness-timeout' : 'harness-connect-failed',
|
|
1020
|
+
method,
|
|
1021
|
+
{ cause: error },
|
|
1022
|
+
);
|
|
1023
|
+
}
|
|
1024
|
+
if (body?.type !== 'server-response' || body?.rpcId !== rpcId) {
|
|
1025
|
+
throw new HarnessTransportError('harness-response-invalid', method, {
|
|
1026
|
+
cause: new Error(`Harness returned an invalid response for ${method}`),
|
|
1027
|
+
});
|
|
1028
|
+
}
|
|
1029
|
+
if (!body.result || typeof body.result !== 'object' || typeof body.result.ok !== 'boolean') {
|
|
1030
|
+
throw new HarnessTransportError('harness-response-invalid', method, {
|
|
1031
|
+
cause: new Error(`Harness returned an invalid result for ${method}`),
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
if (!body.result?.ok) throw new HarnessRpcError(method, body.result?.error);
|
|
1035
|
+
return body.result.value;
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
async health(options = {}) {
|
|
1039
|
+
try {
|
|
1040
|
+
await this.rpc('host.describe', {}, 5_000, options);
|
|
1041
|
+
return true;
|
|
1042
|
+
} catch (error) {
|
|
1043
|
+
if (error instanceof HarnessRpcError) throw new HarnessHealthError(error);
|
|
1044
|
+
throw error;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
async ensureRunning(options = {}) {
|
|
1049
|
+
try {
|
|
1050
|
+
return await this.health(options);
|
|
1051
|
+
} catch (firstError) {
|
|
1052
|
+
if (!this.#autostart) throw firstError;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
if (!this.#managedProcess || this.#managedProcess.exitCode !== null) {
|
|
1056
|
+
const port = this.#baseUrl.port || (this.#baseUrl.protocol === 'https:' ? '443' : '80');
|
|
1057
|
+
this.#managedProcess = spawn(this.#dshBin, [
|
|
1058
|
+
'web', '--host', this.#baseUrl.hostname, '--port', port,
|
|
1059
|
+
], {
|
|
1060
|
+
cwd: this.#workspace,
|
|
1061
|
+
env: process.env,
|
|
1062
|
+
stdio: ['ignore', 'inherit', 'inherit'],
|
|
1063
|
+
});
|
|
1064
|
+
this.#managedProcess.on('error', (error) => {
|
|
1065
|
+
console.error('[dsh-im] failed to start Harness:', this.#logPrefix, error.message);
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
const deadline = Date.now() + 60_000;
|
|
1070
|
+
let lastError;
|
|
1071
|
+
while (Date.now() < deadline) {
|
|
1072
|
+
await sleep(1_000, options.signal);
|
|
1073
|
+
try {
|
|
1074
|
+
return await this.health(options);
|
|
1075
|
+
} catch (error) {
|
|
1076
|
+
lastError = error;
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
if (lastError) throw lastError;
|
|
1080
|
+
throw new HarnessTransportError('harness-timeout', 'host.describe');
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
async listWorkspaces(options = {}) {
|
|
1084
|
+
await this.ensureRunning(options);
|
|
1085
|
+
return workspacePaths(await this.rpc('workspace.list', {}, 30_000, options));
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
async listWorkspaceSessions(workspacePath, options = {}) {
|
|
1089
|
+
await this.ensureRunning(options);
|
|
1090
|
+
const workspaceList = await this.rpc('workspace.list', {}, 30_000, options);
|
|
1091
|
+
const workspace = workspaceFromList(workspacePath, workspaceList);
|
|
1092
|
+
if (await this.isUngroupedWorkspace(workspacePath)) {
|
|
1093
|
+
const sessionList = await this.rpc('session.list', {}, 30_000, options);
|
|
1094
|
+
if (!Array.isArray(sessionList?.items)) {
|
|
1095
|
+
throw new Error('Harness returned an invalid response for session.list');
|
|
1096
|
+
}
|
|
1097
|
+
const registered = new Set();
|
|
1098
|
+
const selected = new Set();
|
|
1099
|
+
for (const item of workspaceList.items) {
|
|
1100
|
+
if (!Array.isArray(item?.sessionIds)
|
|
1101
|
+
|| item.sessionIds.some((id) => typeof id !== 'string' || !id)) {
|
|
1102
|
+
throw new Error('Harness returned invalid session IDs for workspace.list');
|
|
1103
|
+
}
|
|
1104
|
+
for (const id of item.sessionIds) registered.add(id);
|
|
1105
|
+
if (await sameWorkspacePath(item.path, workspacePath)) {
|
|
1106
|
+
for (const id of item.sessionIds) selected.add(id);
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
for (const item of sessionList.items) {
|
|
1110
|
+
if (typeof item?.sessionId !== 'string' || !item.sessionId) {
|
|
1111
|
+
throw new Error('Harness returned an invalid response for session.list');
|
|
1112
|
+
}
|
|
1113
|
+
// A matching cwd never overrides an explicit group assignment.
|
|
1114
|
+
if (!registered.has(item.sessionId) && await this.isUngroupedWorkspace(item.cwd)) {
|
|
1115
|
+
selected.add(item.sessionId);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
return workspaceSessions(
|
|
1119
|
+
{ path: workspacePath, sessionIds: [...selected] },
|
|
1120
|
+
workspaceList.archivedSessionIds,
|
|
1121
|
+
sessionList,
|
|
1122
|
+
);
|
|
1123
|
+
}
|
|
1124
|
+
if (!workspace) return { workspace: workspacePath, sessions: [] };
|
|
1125
|
+
const sessionList = await this.rpc('session.list', {}, 30_000, options);
|
|
1126
|
+
return workspaceSessions(workspace, workspaceList.archivedSessionIds, sessionList);
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
async listModels(options = {}) {
|
|
1130
|
+
await this.ensureRunning(options);
|
|
1131
|
+
const value = await this.rpc('llm.models', {}, 30_000, options);
|
|
1132
|
+
return validateModelCatalog(value, 'llm.models');
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
async getSessionModels(sessionId, options = {}) {
|
|
1136
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
|
|
1137
|
+
await this.ensureRunning(options);
|
|
1138
|
+
const value = await this.rpc('session.models', { sessionId }, 30_000, options);
|
|
1139
|
+
return validateModelCatalog(value, 'session.models', { session: true });
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
async selectSessionModel(sessionId, selection, options = {}) {
|
|
1143
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
|
|
1144
|
+
if (!validModelSelection(selection)) {
|
|
1145
|
+
throw new TypeError('A provider and model are required');
|
|
1146
|
+
}
|
|
1147
|
+
await this.ensureRunning(options);
|
|
1148
|
+
const operation = (maintenanceSignal) => {
|
|
1149
|
+
const signal = maintenanceSignal && options.signal
|
|
1150
|
+
? AbortSignal.any([maintenanceSignal, options.signal])
|
|
1151
|
+
: (maintenanceSignal ?? options.signal);
|
|
1152
|
+
return this.rpc('session.selectModel', {
|
|
1153
|
+
sessionId,
|
|
1154
|
+
provider: selection.provider,
|
|
1155
|
+
model: selection.model,
|
|
1156
|
+
...(selection.reasoningEffort === undefined
|
|
1157
|
+
? {}
|
|
1158
|
+
: { reasoningEffort: selection.reasoningEffort }),
|
|
1159
|
+
}, 30_000, signal ? { ...options, signal } : options);
|
|
1160
|
+
};
|
|
1161
|
+
const value = this.#sessionMaintenanceExecutor
|
|
1162
|
+
? await this.#sessionMaintenanceExecutor({ sessionId, operation })
|
|
1163
|
+
: await operation();
|
|
1164
|
+
if (!value || typeof value !== 'object' || !validModelSelection(value.selected)) {
|
|
1165
|
+
throw new Error('Harness returned an invalid response for session.selectModel');
|
|
1166
|
+
}
|
|
1167
|
+
return value;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
async isSessionRunning(sessionId, options = {}) {
|
|
1171
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
|
|
1172
|
+
await this.ensureRunning(options);
|
|
1173
|
+
const value = await this.rpc('session.list', {}, 30_000, options);
|
|
1174
|
+
if (!value || typeof value !== 'object' || !Array.isArray(value.items)) {
|
|
1175
|
+
throw new Error('Harness returned an invalid response for session.list');
|
|
1176
|
+
}
|
|
1177
|
+
for (const item of value.items) {
|
|
1178
|
+
if (!item || typeof item !== 'object'
|
|
1179
|
+
|| typeof item.sessionId !== 'string' || !item.sessionId
|
|
1180
|
+
|| typeof item.running !== 'boolean') {
|
|
1181
|
+
throw new Error('Harness returned an invalid response for session.list');
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
return value.items.find((item) => item.sessionId === sessionId)?.running ?? false;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
async adoptWorkspaceSession(value, options = {}) {
|
|
1188
|
+
return adoptRegisteredWorkspaceSession(this, value, options);
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
async isUngroupedWorkspace(workspace) {
|
|
1192
|
+
return sameWorkspacePath(workspace, this.#ungroupedWorkspace);
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
async workspaceId(options = {}) {
|
|
1196
|
+
const { workspace = this.#workspace, ...rpcOptions } = options;
|
|
1197
|
+
const { items } = await this.rpc('workspace.list', {}, 30_000, rpcOptions);
|
|
1198
|
+
const existing = items.find((item) => item.path === workspace);
|
|
1199
|
+
if (existing) return existing.workspaceId;
|
|
1200
|
+
const created = await this.rpc('workspace.create', { path: workspace }, 30_000, rpcOptions);
|
|
1201
|
+
return created.workspace.workspaceId;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
async createSession(options = {}) {
|
|
1205
|
+
const { agentPreset: requestedPreset, ...rpcOptions } = options;
|
|
1206
|
+
const workspace = rpcOptions.workspace ?? this.#workspace;
|
|
1207
|
+
const ungrouped = await this.isUngroupedWorkspace(workspace);
|
|
1208
|
+
if (ungrouped) await mkdir(workspace, { recursive: true });
|
|
1209
|
+
await this.ensureRunning(rpcOptions);
|
|
1210
|
+
const payload = ungrouped
|
|
1211
|
+
? { cwd: workspace }
|
|
1212
|
+
: { workspaceId: await this.workspaceId(rpcOptions) };
|
|
1213
|
+
const agentPreset = requestedPreset !== undefined ? requestedPreset : this.#agentPreset;
|
|
1214
|
+
if (agentPreset != null) payload.agentPreset = agentPreset;
|
|
1215
|
+
const created = await this.rpc('session.create', payload, 30_000, rpcOptions);
|
|
1216
|
+
return created.sessionId;
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
async renameSession(sessionId, title, options = {}) {
|
|
1220
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
|
|
1221
|
+
if (typeof title !== 'string' || !title.trim()) throw new TypeError('session title is required');
|
|
1222
|
+
return this.rpc('session.rename', { sessionId, title }, 30_000, options);
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
async executeCommand(sessionId, line, options = {}) {
|
|
1226
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
|
|
1227
|
+
if (typeof line !== 'string' || !line) throw new TypeError('command line is required');
|
|
1228
|
+
if (!this.#commandExecutor) {
|
|
1229
|
+
const error = new Error('Harness command execution is unavailable');
|
|
1230
|
+
error.code = 'commands-unavailable';
|
|
1231
|
+
throw error;
|
|
1232
|
+
}
|
|
1233
|
+
try {
|
|
1234
|
+
return await this.#commandExecutor(sessionId, line, options);
|
|
1235
|
+
} catch (error) {
|
|
1236
|
+
if (error?.failure && typeof error.failure === 'object') {
|
|
1237
|
+
throw new HarnessRpcError('commands.execute', error.failure);
|
|
1238
|
+
}
|
|
1239
|
+
throw error;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
async readSessionHistory(sessionId, { maxMessages = 50, beforeSeq, timeoutMs = 10_000, ...options } = {}) {
|
|
1244
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
|
|
1245
|
+
if (!Number.isSafeInteger(maxMessages) || maxMessages < 1
|
|
1246
|
+
|| (beforeSeq !== undefined && (!Number.isSafeInteger(beforeSeq) || beforeSeq < 0))) {
|
|
1247
|
+
throw new TypeError('Invalid history pagination');
|
|
1248
|
+
}
|
|
1249
|
+
return this.rpc('session.history', {
|
|
1250
|
+
sessionId,
|
|
1251
|
+
maxMessages,
|
|
1252
|
+
...(beforeSeq === undefined ? {} : { beforeSeq }),
|
|
1253
|
+
}, timeoutMs, options);
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
async sessionExists(sessionId, options = {}) {
|
|
1257
|
+
try {
|
|
1258
|
+
await this.rpc('session.history', { sessionId, maxMessages: 1 }, 30_000, options);
|
|
1259
|
+
return true;
|
|
1260
|
+
} catch (error) {
|
|
1261
|
+
if (error instanceof HarnessRpcError && error.code === 'session-not-found') return false;
|
|
1262
|
+
throw error;
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
async respondInteraction(rpcId, result, options = {}) {
|
|
1267
|
+
if (typeof rpcId !== 'string' || !rpcId) throw new TypeError('rpcId is required');
|
|
1268
|
+
if (!result || typeof result !== 'object' || typeof result.ok !== 'boolean') {
|
|
1269
|
+
throw new TypeError('A Harness RPC result is required');
|
|
1270
|
+
}
|
|
1271
|
+
const timeoutSignal = AbortSignal.timeout(options.timeoutMs ?? 30_000);
|
|
1272
|
+
const signal = options.signal
|
|
1273
|
+
? AbortSignal.any([options.signal, timeoutSignal])
|
|
1274
|
+
: timeoutSignal;
|
|
1275
|
+
const envelope = { type: 'client-response', rpcId, result };
|
|
1276
|
+
let receipt;
|
|
1277
|
+
if (this.#apiProxy) {
|
|
1278
|
+
receipt = await callWithSignal(() => this.#apiProxy.respond(envelope), signal);
|
|
1279
|
+
} else {
|
|
1280
|
+
const response = await this.#fetch(new URL('/api/respond', this.#baseUrl), {
|
|
1281
|
+
method: 'POST',
|
|
1282
|
+
headers: { 'content-type': 'application/json' },
|
|
1283
|
+
body: JSON.stringify(envelope),
|
|
1284
|
+
signal,
|
|
1285
|
+
});
|
|
1286
|
+
if (!response.ok) {
|
|
1287
|
+
throw new Error(`Harness transport respond failed: HTTP ${response.status}`);
|
|
1288
|
+
}
|
|
1289
|
+
receipt = await response.json();
|
|
1290
|
+
}
|
|
1291
|
+
if (receipt?.accepted === true) return receipt;
|
|
1292
|
+
if (receipt?.accepted !== false
|
|
1293
|
+
|| (receipt.reason !== 'bad-response' && receipt.reason !== 'not-pending')) {
|
|
1294
|
+
throw new Error('Harness returned an invalid interaction response receipt');
|
|
1295
|
+
}
|
|
1296
|
+
const reason = receipt.reason;
|
|
1297
|
+
throw new HarnessInteractionError(
|
|
1298
|
+
`interaction-${reason}`,
|
|
1299
|
+
`Harness interaction response was rejected (${reason})`,
|
|
1300
|
+
);
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
async watchInteractions(sessionId, {
|
|
1304
|
+
signal,
|
|
1305
|
+
onInteraction,
|
|
1306
|
+
onResolved,
|
|
1307
|
+
onSessionEvent,
|
|
1308
|
+
onOpen,
|
|
1309
|
+
ownership,
|
|
1310
|
+
} = {}) {
|
|
1311
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
|
|
1312
|
+
if (!signal || typeof signal.addEventListener !== 'function') {
|
|
1313
|
+
throw new TypeError('watchInteractions requires an AbortSignal');
|
|
1314
|
+
}
|
|
1315
|
+
if (onInteraction !== undefined && typeof onInteraction !== 'function') {
|
|
1316
|
+
throw new TypeError('onInteraction must be a function');
|
|
1317
|
+
}
|
|
1318
|
+
if (onResolved !== undefined && typeof onResolved !== 'function') {
|
|
1319
|
+
throw new TypeError('onResolved must be a function');
|
|
1320
|
+
}
|
|
1321
|
+
if (onSessionEvent !== undefined && typeof onSessionEvent !== 'function') {
|
|
1322
|
+
throw new TypeError('onSessionEvent must be a function');
|
|
1323
|
+
}
|
|
1324
|
+
if (onOpen !== undefined && typeof onOpen !== 'function') {
|
|
1325
|
+
throw new TypeError('onOpen must be a function');
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
while (!signal.aborted) {
|
|
1329
|
+
try {
|
|
1330
|
+
await this.#watchInteractionStream(sessionId, {
|
|
1331
|
+
signal,
|
|
1332
|
+
onInteraction,
|
|
1333
|
+
onResolved,
|
|
1334
|
+
onSessionEvent,
|
|
1335
|
+
onOpen,
|
|
1336
|
+
ownership,
|
|
1337
|
+
});
|
|
1338
|
+
} catch (error) {
|
|
1339
|
+
if (signal.aborted) return;
|
|
1340
|
+
console.warn('[dsh-im] Harness interaction stream disconnected:', this.#logPrefix, error.message);
|
|
1341
|
+
}
|
|
1342
|
+
if (signal.aborted) return;
|
|
1343
|
+
try {
|
|
1344
|
+
await sleep(this.#interactionReconnectDelayMs, signal);
|
|
1345
|
+
} catch {
|
|
1346
|
+
if (signal.aborted) return;
|
|
1347
|
+
throw new Error('Harness interaction reconnect wait failed');
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
#registerInteractionOwnership(sessionId, ownership) {
|
|
1353
|
+
const owners = this.#interactionOwnerships.get(sessionId) ?? new Set();
|
|
1354
|
+
ownership.order = this.#interactionRegistry.nextOrder;
|
|
1355
|
+
this.#interactionRegistry.nextOrder += 1;
|
|
1356
|
+
owners.add(ownership);
|
|
1357
|
+
this.#interactionOwnerships.set(sessionId, owners);
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
#unregisterInteractionOwnership(sessionId, ownership) {
|
|
1361
|
+
const owners = this.#interactionOwnerships.get(sessionId);
|
|
1362
|
+
owners?.delete(ownership);
|
|
1363
|
+
if (owners?.size === 0) this.#interactionOwnerships.delete(sessionId);
|
|
1364
|
+
for (const [key, claim] of this.#interactionClaims) {
|
|
1365
|
+
if (claim.ownership === ownership) this.#interactionClaims.delete(key);
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
#registerControlOwnership(ownership) {
|
|
1370
|
+
if (!ownership.control) return;
|
|
1371
|
+
let routes = this.#controlOwnerships.get(ownership.control.owner);
|
|
1372
|
+
if (!routes) {
|
|
1373
|
+
routes = new Map();
|
|
1374
|
+
this.#controlOwnerships.set(ownership.control.owner, routes);
|
|
1375
|
+
}
|
|
1376
|
+
const owners = routes.get(ownership.control.key) ?? new Set();
|
|
1377
|
+
owners.add(ownership);
|
|
1378
|
+
routes.set(ownership.control.key, owners);
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
#unregisterControlOwnership(ownership) {
|
|
1382
|
+
if (!ownership.control) return;
|
|
1383
|
+
const routes = this.#controlOwnerships.get(ownership.control.owner);
|
|
1384
|
+
const owners = routes?.get(ownership.control.key);
|
|
1385
|
+
owners?.delete(ownership);
|
|
1386
|
+
if (owners?.size === 0) routes.delete(ownership.control.key);
|
|
1387
|
+
if (routes?.size === 0) this.#controlOwnerships.delete(ownership.control.owner);
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
#controlCandidates(sessionId, control) {
|
|
1391
|
+
const normalized = normalizeControl(control);
|
|
1392
|
+
if (!normalized) return [];
|
|
1393
|
+
const owners = this.#controlOwnerships.get(normalized.owner)?.get(normalized.key);
|
|
1394
|
+
return [...(owners ?? [])]
|
|
1395
|
+
.filter((ownership) => ownership.sessionId === sessionId)
|
|
1396
|
+
.sort((left, right) => left.order - right.order);
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
#activeControlOwnership(sessionId, control) {
|
|
1400
|
+
return this.#controlCandidates(sessionId, control).find((ownership) => (
|
|
1401
|
+
ownership.started
|
|
1402
|
+
&& ownership.active
|
|
1403
|
+
&& !ownership.completed
|
|
1404
|
+
&& ownership.turn !== null
|
|
1405
|
+
)) ?? null;
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
async #refreshControlOwnership(sessionId, control, options) {
|
|
1409
|
+
const candidates = this.#controlCandidates(sessionId, control);
|
|
1410
|
+
// An exact local owner is mandatory before even observing the Session.
|
|
1411
|
+
// This prevents an unrelated chat bound to the same Session from using
|
|
1412
|
+
// run state as authority to cancel or steer somebody else's turn.
|
|
1413
|
+
if (candidates.length === 0) return null;
|
|
1414
|
+
try {
|
|
1415
|
+
const history = await this.rpc(
|
|
1416
|
+
'session.history',
|
|
1417
|
+
{ sessionId, maxMessages: 50 },
|
|
1418
|
+
30_000,
|
|
1419
|
+
options,
|
|
1420
|
+
);
|
|
1421
|
+
this.#consumeInteractionOwnerships(sessionId, history.events ?? []);
|
|
1422
|
+
} catch (error) {
|
|
1423
|
+
if (!(error instanceof HarnessRpcError) || error.code !== 'session-not-found') throw error;
|
|
1424
|
+
for (const ownership of candidates) {
|
|
1425
|
+
ownership.active = false;
|
|
1426
|
+
ownership.completed = true;
|
|
1427
|
+
}
|
|
1428
|
+
return null;
|
|
1429
|
+
}
|
|
1430
|
+
return this.#activeControlOwnership(sessionId, control);
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
async hasActiveTurn(sessionId, control, options = {}) {
|
|
1434
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
|
|
1435
|
+
return Boolean(await this.#refreshControlOwnership(sessionId, control, options));
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
/** Cancel only the persisted prompt's exact live turn, in the host's JS tick.
|
|
1439
|
+
* HTTP session.cancel cannot express this precondition, so never fall back to it.
|
|
1440
|
+
*/
|
|
1441
|
+
stopDeferredTurn(sessionId, { turn, promptRpcId } = {}, { signal, isCurrent } = {}) {
|
|
1442
|
+
signal?.throwIfAborted();
|
|
1443
|
+
if (typeof sessionId !== 'string' || !sessionId
|
|
1444
|
+
|| !Number.isSafeInteger(turn) || turn < 0
|
|
1445
|
+
|| typeof promptRpcId !== 'string' || !promptRpcId
|
|
1446
|
+
|| typeof this.#controlExecutor !== 'function') return false;
|
|
1447
|
+
if (isCurrent && !isCurrent()) return false;
|
|
1448
|
+
const accepted = this.#controlExecutor({ sessionId, expectedTurn: turn, promptRpcId, action: 'stop' });
|
|
1449
|
+
if (accepted && typeof accepted.then === 'function') {
|
|
1450
|
+
throw new TypeError('controlExecutor must return synchronously');
|
|
1451
|
+
}
|
|
1452
|
+
return accepted === true;
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
async stopActiveTurn(sessionId, control, options = {}) {
|
|
1456
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
|
|
1457
|
+
const ownership = await this.#refreshControlOwnership(sessionId, control, options);
|
|
1458
|
+
if (!ownership) return false;
|
|
1459
|
+
if (ownership.stopRequested) return true;
|
|
1460
|
+
// Re-check after the refresh await. The owning ask may have completed and
|
|
1461
|
+
// unregistered while session.history was in flight.
|
|
1462
|
+
if (this.#activeControlOwnership(sessionId, control) !== ownership) return false;
|
|
1463
|
+
ownership.stopRequested = true;
|
|
1464
|
+
try {
|
|
1465
|
+
if (this.#controlExecutor) {
|
|
1466
|
+
const accepted = this.#controlExecutor({
|
|
1467
|
+
sessionId,
|
|
1468
|
+
expectedTurn: ownership.turn,
|
|
1469
|
+
promptRpcId: ownership.promptRpcId,
|
|
1470
|
+
action: 'stop',
|
|
1471
|
+
});
|
|
1472
|
+
if (accepted && typeof accepted.then === 'function') {
|
|
1473
|
+
throw new TypeError('controlExecutor must return synchronously');
|
|
1474
|
+
}
|
|
1475
|
+
if (accepted !== undefined) {
|
|
1476
|
+
if (typeof accepted !== 'boolean') {
|
|
1477
|
+
throw new TypeError('controlExecutor must return a boolean or undefined');
|
|
1478
|
+
}
|
|
1479
|
+
if (!accepted) ownership.stopRequested = false;
|
|
1480
|
+
return accepted;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
await this.rpc(
|
|
1484
|
+
'session.cancel',
|
|
1485
|
+
{ sessionId, keepInbox: true },
|
|
1486
|
+
30_000,
|
|
1487
|
+
options,
|
|
1488
|
+
);
|
|
1489
|
+
return true;
|
|
1490
|
+
} catch (error) {
|
|
1491
|
+
if (this.#activeControlOwnership(sessionId, control) === ownership) {
|
|
1492
|
+
ownership.stopRequested = false;
|
|
1493
|
+
}
|
|
1494
|
+
if (error instanceof HarnessRpcError && error.code === 'session-not-found') return false;
|
|
1495
|
+
throw error;
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
async steerActiveTurn(sessionId, text, control, options = {}) {
|
|
1500
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('sessionId is required');
|
|
1501
|
+
if (typeof text !== 'string' || !text.trim()) {
|
|
1502
|
+
throw new TypeError('Steering text is required');
|
|
1503
|
+
}
|
|
1504
|
+
const ownership = await this.#refreshControlOwnership(sessionId, control, options);
|
|
1505
|
+
if (!ownership || ownership.stopRequested) return false;
|
|
1506
|
+
if (this.#activeControlOwnership(sessionId, control) !== ownership) return false;
|
|
1507
|
+
const inputRpcId = `${this.#rpcIdPrefix}-steer-${randomUUID()}`;
|
|
1508
|
+
const releaseInputOrigin = registerImInputOrigin(this.#interactionRegistry, inputRpcId);
|
|
1509
|
+
try {
|
|
1510
|
+
if (this.#controlExecutor) {
|
|
1511
|
+
const accepted = this.#controlExecutor({
|
|
1512
|
+
sessionId,
|
|
1513
|
+
expectedTurn: ownership.turn,
|
|
1514
|
+
promptRpcId: ownership.promptRpcId,
|
|
1515
|
+
inputRpcId,
|
|
1516
|
+
action: 'steer',
|
|
1517
|
+
text,
|
|
1518
|
+
});
|
|
1519
|
+
if (accepted && typeof accepted.then === 'function') {
|
|
1520
|
+
throw new TypeError('controlExecutor must return synchronously');
|
|
1521
|
+
}
|
|
1522
|
+
if (accepted !== undefined) {
|
|
1523
|
+
if (typeof accepted !== 'boolean') {
|
|
1524
|
+
throw new TypeError('controlExecutor must return a boolean or undefined');
|
|
1525
|
+
}
|
|
1526
|
+
if (!accepted) releaseInputOrigin();
|
|
1527
|
+
return accepted;
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
await this.rpc('session.prompt', {
|
|
1531
|
+
sessionId,
|
|
1532
|
+
mode: 'steer',
|
|
1533
|
+
content: [{ type: 'text', text }],
|
|
1534
|
+
clientTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
1535
|
+
}, 30_000, { ...options, rpcId: inputRpcId });
|
|
1536
|
+
return true;
|
|
1537
|
+
} catch (error) {
|
|
1538
|
+
releaseInputOrigin();
|
|
1539
|
+
throw error;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
#consumeInteractionOwnerships(sessionId, entries) {
|
|
1544
|
+
for (const ownership of this.#interactionOwnerships.get(sessionId) ?? []) {
|
|
1545
|
+
consumeInteractionOwnership(ownership, entries);
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
async #refreshInteractionOwnerships(sessionId, signal) {
|
|
1550
|
+
const history = await this.rpc(
|
|
1551
|
+
'session.history',
|
|
1552
|
+
{ sessionId, maxMessages: 50 },
|
|
1553
|
+
30_000,
|
|
1554
|
+
{ signal },
|
|
1555
|
+
);
|
|
1556
|
+
this.#consumeInteractionOwnerships(sessionId, history.events ?? []);
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
#interactionOwner(sessionId, claimKey, kind) {
|
|
1560
|
+
const claim = this.#interactionClaims.get(claimKey);
|
|
1561
|
+
if (claim && this.#interactionOwnerships.get(sessionId)?.has(claim.ownership)) return claim;
|
|
1562
|
+
|
|
1563
|
+
const owners = [...(this.#interactionOwnerships.get(sessionId) ?? [])];
|
|
1564
|
+
const active = owners
|
|
1565
|
+
.filter((ownership) => ownership.active)
|
|
1566
|
+
.sort((left, right) => left.order - right.order);
|
|
1567
|
+
if (active.length > 0) return { ownership: active[0], recovered: false };
|
|
1568
|
+
|
|
1569
|
+
// A newly attached IM conversation may encounter a question left by
|
|
1570
|
+
// an earlier runtime before its queued prompt starts. Let the oldest such
|
|
1571
|
+
// ask adopt that replay so the Session can recover instead of deadlocking.
|
|
1572
|
+
// Approval adopters receive recovered=true and must reject it without ever
|
|
1573
|
+
// presenting it as approvable; the original actor/route cannot be proven
|
|
1574
|
+
// after a runtime restart.
|
|
1575
|
+
const ownership = owners
|
|
1576
|
+
.filter((ownership) => !ownership.started && !ownership.completed)
|
|
1577
|
+
.sort((left, right) => left.order - right.order)[0] ?? null;
|
|
1578
|
+
return ownership ? { ownership, recovered: true } : null;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
/** Stage inbound file sources into the Session workspace via the Host executor. */
|
|
1582
|
+
async #stageWorkspaceFiles(sessionId, files, signal) {
|
|
1583
|
+
if (!this.#fileIngressExecutor) {
|
|
1584
|
+
throw new InboundFileError(
|
|
1585
|
+
'inbound-file-ingress-unavailable',
|
|
1586
|
+
'Harness file ingress is unavailable in this Host process.',
|
|
1587
|
+
);
|
|
1588
|
+
}
|
|
1589
|
+
const sessionList = await this.rpc(
|
|
1590
|
+
'session.list',
|
|
1591
|
+
{},
|
|
1592
|
+
30_000,
|
|
1593
|
+
{ signal },
|
|
1594
|
+
);
|
|
1595
|
+
const sessionWorkspace = sessionList?.items?.find(
|
|
1596
|
+
(item) => item?.sessionId === sessionId,
|
|
1597
|
+
)?.cwd;
|
|
1598
|
+
return this.#fileIngressExecutor({
|
|
1599
|
+
sessionId,
|
|
1600
|
+
workspace: sessionWorkspace,
|
|
1601
|
+
files,
|
|
1602
|
+
signal,
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
async getImageInputLimits() {
|
|
1607
|
+
return imageInputLimits(await this.#imageInputPolicy());
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
async ask(sessionId, prompt, options = {}) {
|
|
1611
|
+
if (typeof options === 'number') options = { timeoutMs: options };
|
|
1612
|
+
const timeoutMs = options.timeoutMs ?? 600_000;
|
|
1613
|
+
const signal = options.signal;
|
|
1614
|
+
const onUpdate = typeof options.onUpdate === 'function' ? options.onUpdate : null;
|
|
1615
|
+
const progressMode = options.progressMode === 'live'
|
|
1616
|
+
? 'live'
|
|
1617
|
+
: options.progressMode === 'all' ? 'all' : 'latest';
|
|
1618
|
+
// Reasoning updates only exist for consumers that opt in (thinking-trace
|
|
1619
|
+
// mode); default ask() consumers keep the pre-thinking-traces stream.
|
|
1620
|
+
const reasoning = options.reasoning === true;
|
|
1621
|
+
const onArtifact = typeof options.onArtifact === 'function' ? options.onArtifact : null;
|
|
1622
|
+
const onInteraction = typeof options.onInteraction === 'function'
|
|
1623
|
+
? options.onInteraction
|
|
1624
|
+
: undefined;
|
|
1625
|
+
const onInteractionResolved = typeof options.onInteractionResolved === 'function'
|
|
1626
|
+
? options.onInteractionResolved
|
|
1627
|
+
: undefined;
|
|
1628
|
+
const control = normalizeControl(options.control);
|
|
1629
|
+
const inboundFiles = Array.isArray(options.files) ? options.files.filter(Boolean) : [];
|
|
1630
|
+
const inboundImages = Array.isArray(options.images) ? options.images.filter(Boolean) : [];
|
|
1631
|
+
await this.ensureRunning({ signal });
|
|
1632
|
+
const before = await this.rpc(
|
|
1633
|
+
'session.history',
|
|
1634
|
+
{ sessionId, maxMessages: 1 },
|
|
1635
|
+
30_000,
|
|
1636
|
+
{ signal },
|
|
1637
|
+
);
|
|
1638
|
+
const baselineSeq = Math.max(-1, ...(before.events ?? []).map(({ event }) => event.seq ?? -1));
|
|
1639
|
+
const promptRpcId = `${this.#rpcIdPrefix}-${randomUUID()}`;
|
|
1640
|
+
const releasePromptInputOrigin = registerImInputOrigin(this.#interactionRegistry, promptRpcId);
|
|
1641
|
+
const tracker = new HarnessReplyTracker({ promptRpcId, afterSeq: baselineSeq, reasoning });
|
|
1642
|
+
let lastProgressAt = Date.now();
|
|
1643
|
+
let lastPollSeq = tracker.lastSeq;
|
|
1644
|
+
let progressTail = Promise.resolve();
|
|
1645
|
+
const consumeProgress = (entries, { fromMux = false } = {}) => {
|
|
1646
|
+
const updates = tracker.consumeAll(entries, {
|
|
1647
|
+
live: progressMode === 'live',
|
|
1648
|
+
fromMux,
|
|
1649
|
+
});
|
|
1650
|
+
const seqAdvanced = tracker.lastSeq > lastPollSeq;
|
|
1651
|
+
lastPollSeq = tracker.lastSeq;
|
|
1652
|
+
if (seqAdvanced) lastProgressAt = Date.now();
|
|
1653
|
+
if (!onUpdate) return progressTail;
|
|
1654
|
+
const visibleUpdates = progressMode === 'all' || progressMode === 'live'
|
|
1655
|
+
? updates
|
|
1656
|
+
: updates
|
|
1657
|
+
.filter((update) => update.type !== 'assistant-message' && update.type !== 'reasoning')
|
|
1658
|
+
.slice(-1);
|
|
1659
|
+
for (const update of visibleUpdates) {
|
|
1660
|
+
progressTail = progressTail
|
|
1661
|
+
.then(() => onUpdate(update))
|
|
1662
|
+
.catch((error) => {
|
|
1663
|
+
console.warn(
|
|
1664
|
+
'[dsh-im] ignored a progress update failure:',
|
|
1665
|
+
this.#logPrefix,
|
|
1666
|
+
error.message,
|
|
1667
|
+
);
|
|
1668
|
+
});
|
|
1669
|
+
}
|
|
1670
|
+
return progressTail;
|
|
1671
|
+
};
|
|
1672
|
+
const interactionController = onInteraction || onInteractionResolved
|
|
1673
|
+
|| (progressMode === 'live' && onUpdate)
|
|
1674
|
+
? new AbortController()
|
|
1675
|
+
: null;
|
|
1676
|
+
const interactionSignal = interactionController
|
|
1677
|
+
? (signal
|
|
1678
|
+
? AbortSignal.any([signal, interactionController.signal])
|
|
1679
|
+
: interactionController.signal)
|
|
1680
|
+
: null;
|
|
1681
|
+
// The mux is host-global. A prompt RPC becomes the owner only when its
|
|
1682
|
+
// durable user/message starts a turn, so two chats bound to one Session
|
|
1683
|
+
// cannot answer each other's questions or approvals.
|
|
1684
|
+
const ownership = interactionController || control
|
|
1685
|
+
? {
|
|
1686
|
+
sessionId,
|
|
1687
|
+
promptRpcId,
|
|
1688
|
+
active: false,
|
|
1689
|
+
started: false,
|
|
1690
|
+
completed: false,
|
|
1691
|
+
stopRequested: false,
|
|
1692
|
+
turn: null,
|
|
1693
|
+
openTurn: null,
|
|
1694
|
+
lastSeq: baselineSeq,
|
|
1695
|
+
reconnect: null,
|
|
1696
|
+
order: -1,
|
|
1697
|
+
toolCalls: new Map(),
|
|
1698
|
+
control,
|
|
1699
|
+
}
|
|
1700
|
+
: null;
|
|
1701
|
+
let interactionTask = null;
|
|
1702
|
+
let artifactsDelivered = false;
|
|
1703
|
+
let deliveredArtifactCount = 0;
|
|
1704
|
+
let artifactHandoffError = null;
|
|
1705
|
+
const stagedBatches = [];
|
|
1706
|
+
let promptAccepted = false;
|
|
1707
|
+
let turnFinished = false;
|
|
1708
|
+
|
|
1709
|
+
const deliverArtifacts = async () => {
|
|
1710
|
+
if (!onArtifact || artifactsDelivered || tracker.turn === null) {
|
|
1711
|
+
return deliveredArtifactCount;
|
|
1712
|
+
}
|
|
1713
|
+
artifactsDelivered = true;
|
|
1714
|
+
const artifacts = outboundArtifactRegistry.take(sessionId, tracker.turn, { signal });
|
|
1715
|
+
for (const artifact of artifacts) {
|
|
1716
|
+
try {
|
|
1717
|
+
await onArtifact(artifact);
|
|
1718
|
+
deliveredArtifactCount += 1;
|
|
1719
|
+
} catch (error) {
|
|
1720
|
+
artifactHandoffError ??= error;
|
|
1721
|
+
outboundArtifactRegistry.release(artifact);
|
|
1722
|
+
console.warn('[dsh-im] ignored an artifact handoff failure:', this.#logPrefix, error.message);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
return deliveredArtifactCount;
|
|
1726
|
+
};
|
|
1727
|
+
|
|
1728
|
+
if (ownership) {
|
|
1729
|
+
this.#registerInteractionOwnership(sessionId, ownership);
|
|
1730
|
+
this.#registerControlOwnership(ownership);
|
|
1731
|
+
}
|
|
1732
|
+
// This is resource ownership, not a feature Gate: it lets the Host retain
|
|
1733
|
+
// this Turn's snapshots until the channel has polled and claimed them.
|
|
1734
|
+
const closeArtifactConsumer = outboundArtifactRegistry.openConsumer(sessionId, promptRpcId);
|
|
1735
|
+
|
|
1736
|
+
try {
|
|
1737
|
+
const basePrompt = prompt;
|
|
1738
|
+
if (inboundFiles.length > 0) {
|
|
1739
|
+
const staged = await this.#stageWorkspaceFiles(sessionId, inboundFiles, signal);
|
|
1740
|
+
stagedBatches.push(staged);
|
|
1741
|
+
prompt = appendInboundFilesToPrompt(prompt, staged);
|
|
1742
|
+
}
|
|
1743
|
+
if (inboundImages.length > 0) {
|
|
1744
|
+
const limits = await this.getImageInputLimits();
|
|
1745
|
+
const sources = inboundImagesAsFiles(inboundImages, limits);
|
|
1746
|
+
let staged;
|
|
1747
|
+
try {
|
|
1748
|
+
staged = await this.#stageWorkspaceFiles(sessionId, sources, signal);
|
|
1749
|
+
} catch (error) {
|
|
1750
|
+
// Ingress wraps loader errors; retain the original image diagnostic.
|
|
1751
|
+
if (signal?.aborted) throw signal.reason ?? error;
|
|
1752
|
+
if (error?.cause?.name === 'ImagePromptError') throw error.cause;
|
|
1753
|
+
throw error;
|
|
1754
|
+
}
|
|
1755
|
+
stagedBatches.push(staged);
|
|
1756
|
+
const images = await imageContentFromStaged(staged, limits, { signal });
|
|
1757
|
+
const originalContent = typeof basePrompt === 'string'
|
|
1758
|
+
? [{ type: 'text', text: basePrompt }] : basePrompt;
|
|
1759
|
+
prompt = appendInboundFilesToPrompt([...originalContent, ...images], {
|
|
1760
|
+
files: stagedBatches.flatMap((batch) => batch.files),
|
|
1761
|
+
});
|
|
1762
|
+
}
|
|
1763
|
+
if (interactionSignal) {
|
|
1764
|
+
let markOpen;
|
|
1765
|
+
const opened = new Promise((resolve) => { markOpen = resolve; });
|
|
1766
|
+
interactionTask = this.watchInteractions(sessionId, {
|
|
1767
|
+
signal: interactionSignal,
|
|
1768
|
+
onInteraction,
|
|
1769
|
+
onResolved: onInteractionResolved,
|
|
1770
|
+
onSessionEvent: progressMode === 'live'
|
|
1771
|
+
? (event) => { consumeProgress([event], { fromMux: true }); }
|
|
1772
|
+
: undefined,
|
|
1773
|
+
onOpen: markOpen,
|
|
1774
|
+
ownership,
|
|
1775
|
+
});
|
|
1776
|
+
void interactionTask.catch(() => undefined);
|
|
1777
|
+
await Promise.race([
|
|
1778
|
+
opened,
|
|
1779
|
+
sleep(30_000, interactionSignal).then(() => {
|
|
1780
|
+
throw new Error('Harness interaction stream did not open within 30 seconds');
|
|
1781
|
+
}),
|
|
1782
|
+
]);
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
const content = typeof prompt === 'string'
|
|
1786
|
+
? [{ type: 'text', text: prompt }]
|
|
1787
|
+
: prompt;
|
|
1788
|
+
if (!Array.isArray(content) || content.length === 0) {
|
|
1789
|
+
throw new TypeError('Harness prompt content is required');
|
|
1790
|
+
}
|
|
1791
|
+
// Publish the guidance the channel's own captured settings produced, so
|
|
1792
|
+
// the Host materializes it once per Session as prompt context instead of
|
|
1793
|
+
// per user message. It is passed in and never parsed back out of
|
|
1794
|
+
// `content`: the prompt also carries whatever the user typed, and a
|
|
1795
|
+
// message that merely looks like a guidance block is not configuration.
|
|
1796
|
+
imSourceGuidance.publish(sessionId, options.sourceGuidance);
|
|
1797
|
+
const clientTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
1798
|
+
const sendPrompt = (promptContent) => this.rpc('session.prompt', {
|
|
1799
|
+
sessionId,
|
|
1800
|
+
mode: 'queue',
|
|
1801
|
+
content: promptContent,
|
|
1802
|
+
clientTimeZone,
|
|
1803
|
+
}, 30_000, { rpcId: promptRpcId, signal });
|
|
1804
|
+
try {
|
|
1805
|
+
await sendPrompt(content);
|
|
1806
|
+
} catch (error) {
|
|
1807
|
+
// The Host refuses image blocks for a non-vision model before any
|
|
1808
|
+
// durable user message exists. Re-deliver the same bytes the way
|
|
1809
|
+
// ordinary uploads (zip, documents) already travel — staged into the
|
|
1810
|
+
// Session workspace and named in a text manifest — then retry once
|
|
1811
|
+
// with a text-only prompt. The retry reuses promptRpcId so reply
|
|
1812
|
+
// tracking, control and interaction ownership stay bound to this ask.
|
|
1813
|
+
const originalsStaged = inboundImages.length > 0 && isImageAdmissionRejection(error)
|
|
1814
|
+
&& content.some((part) => part.type === 'image');
|
|
1815
|
+
const imageSources = !originalsStaged && isModelImageRejection(error)
|
|
1816
|
+
? imageFileSourcesFromContent(content) : [];
|
|
1817
|
+
if (!originalsStaged && imageSources.length === 0) throw error;
|
|
1818
|
+
if (!originalsStaged) {
|
|
1819
|
+
let stagedImages;
|
|
1820
|
+
try {
|
|
1821
|
+
stagedImages = await this.#stageWorkspaceFiles(sessionId, imageSources, signal);
|
|
1822
|
+
} catch (stagingError) {
|
|
1823
|
+
if (signal?.aborted) throw signal.reason ?? stagingError;
|
|
1824
|
+
console.warn(
|
|
1825
|
+
'[dsh-im] unable to restage rejected images as workspace files:',
|
|
1826
|
+
this.#logPrefix,
|
|
1827
|
+
stagingError?.message ?? String(stagingError),
|
|
1828
|
+
);
|
|
1829
|
+
throw error;
|
|
1830
|
+
}
|
|
1831
|
+
stagedBatches.push(stagedImages);
|
|
1832
|
+
}
|
|
1833
|
+
const baseContent = typeof basePrompt === 'string'
|
|
1834
|
+
? [{ type: 'text', text: basePrompt }]
|
|
1835
|
+
: basePrompt;
|
|
1836
|
+
const fallbackPrompt = appendInboundFilesToPrompt([
|
|
1837
|
+
...contentWithoutImages(baseContent),
|
|
1838
|
+
{ type: 'text', text: t(isModelImageRejection(error) ? IMAGE_FILE_FALLBACK_PROMPT : IMAGE_HOST_LIMIT_FALLBACK_PROMPT) },
|
|
1839
|
+
], { files: stagedBatches.flatMap((batch) => batch?.files ?? []) });
|
|
1840
|
+
await sendPrompt(fallbackPrompt);
|
|
1841
|
+
}
|
|
1842
|
+
promptAccepted = true;
|
|
1843
|
+
|
|
1844
|
+
try {
|
|
1845
|
+
// Treat timeoutMs as a stall window rather than a hard runtime limit.
|
|
1846
|
+
// Durable events are direct progress. Once a full quiet window elapses,
|
|
1847
|
+
// confirm the Session is still running before renewing the wait.
|
|
1848
|
+
// Interaction ownership is intentionally not a liveness signal: it stays
|
|
1849
|
+
// active until turn/end and can therefore outlive a stalled turn.
|
|
1850
|
+
while (true) {
|
|
1851
|
+
await sleep(300, signal);
|
|
1852
|
+
const history = await this.rpc(
|
|
1853
|
+
'session.history',
|
|
1854
|
+
{ sessionId, maxMessages: 50 },
|
|
1855
|
+
30_000,
|
|
1856
|
+
{ signal },
|
|
1857
|
+
);
|
|
1858
|
+
const wasActive = ownership?.active === true;
|
|
1859
|
+
if (ownership) {
|
|
1860
|
+
this.#consumeInteractionOwnerships(sessionId, history.events ?? []);
|
|
1861
|
+
if (!wasActive && ownership.active) ownership.reconnect?.();
|
|
1862
|
+
}
|
|
1863
|
+
await consumeProgress(history.events ?? []);
|
|
1864
|
+
if (tracker.finished) {
|
|
1865
|
+
turnFinished = true;
|
|
1866
|
+
if (!ownership?.stopRequested && !harnessTurnSucceeded(tracker.reason)) {
|
|
1867
|
+
throw harnessTurnError(tracker.reason);
|
|
1868
|
+
}
|
|
1869
|
+
// An accepted /stop revokes attachment delivery even when Harness
|
|
1870
|
+
// preserved a useful partial text answer for the existing UX.
|
|
1871
|
+
const artifactCount = ownership?.stopRequested
|
|
1872
|
+
? 0
|
|
1873
|
+
: await deliverArtifacts();
|
|
1874
|
+
if (tracker.answer) {
|
|
1875
|
+
return tracker.answer;
|
|
1876
|
+
}
|
|
1877
|
+
if (artifactCount > 0) return '';
|
|
1878
|
+
if (ownership?.stopRequested) throw turnStoppedError();
|
|
1879
|
+
if (artifactHandoffError) throw artifactHandoffError;
|
|
1880
|
+
// A completed turn can do all its work through tools without text.
|
|
1881
|
+
// Missing end reasons retain the existing empty-reply failure.
|
|
1882
|
+
if (tracker.reason != null && harnessTurnSucceeded(tracker.reason)) {
|
|
1883
|
+
return t('本轮处理已结束,没有文本回复。');
|
|
1884
|
+
}
|
|
1885
|
+
throw harnessTurnError(tracker.reason);
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
if (Date.now() - lastProgressAt < timeoutMs) continue;
|
|
1889
|
+
|
|
1890
|
+
let running = false;
|
|
1891
|
+
try {
|
|
1892
|
+
running = await this.isSessionRunning(sessionId, { signal });
|
|
1893
|
+
} catch (error) {
|
|
1894
|
+
if (signal?.aborted) throw signal.reason ?? error;
|
|
1895
|
+
// A failed liveness probe is not evidence of progress.
|
|
1896
|
+
}
|
|
1897
|
+
if (running) {
|
|
1898
|
+
lastProgressAt = Date.now();
|
|
1899
|
+
continue;
|
|
1900
|
+
}
|
|
1901
|
+
const timeoutError = new HarnessTurnError('harness-reply-timeout');
|
|
1902
|
+
// Data-only context for deferred delivery; timeout semantics unchanged.
|
|
1903
|
+
timeoutError.details = { sessionId, promptRpcId, baselineSeq, turn: tracker.turn, lastSeq: tracker.lastSeq };
|
|
1904
|
+
throw timeoutError;
|
|
1905
|
+
}
|
|
1906
|
+
} catch (error) {
|
|
1907
|
+
if (error instanceof HarnessTurnError) {
|
|
1908
|
+
error.details ??= {
|
|
1909
|
+
sessionId, promptRpcId, baselineSeq, turn: tracker.turn, lastSeq: tracker.lastSeq,
|
|
1910
|
+
};
|
|
1911
|
+
}
|
|
1912
|
+
// Once cancellation was accepted, transport/poll failures and timeouts
|
|
1913
|
+
// describe the convergence of that stop, not an unrelated ask failure.
|
|
1914
|
+
if (!ownership?.stopRequested) throw error;
|
|
1915
|
+
if (tracker.answer) {
|
|
1916
|
+
return tracker.answer;
|
|
1917
|
+
}
|
|
1918
|
+
if (error?.code === 'turn-stopped') throw error;
|
|
1919
|
+
throw turnStoppedError();
|
|
1920
|
+
}
|
|
1921
|
+
} finally {
|
|
1922
|
+
releasePromptInputOrigin();
|
|
1923
|
+
if (!promptAccepted || turnFinished) {
|
|
1924
|
+
for (const staged of stagedBatches) {
|
|
1925
|
+
try {
|
|
1926
|
+
await staged?.cleanup?.();
|
|
1927
|
+
} catch (error) {
|
|
1928
|
+
console.warn('[dsh-im] unable to clean inbound files:', this.#logPrefix, error.message);
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
closeArtifactConsumer();
|
|
1933
|
+
if (ownership) {
|
|
1934
|
+
this.#unregisterControlOwnership(ownership);
|
|
1935
|
+
this.#unregisterInteractionOwnership(sessionId, ownership);
|
|
1936
|
+
}
|
|
1937
|
+
if (tracker.turn !== null) outboundArtifactRegistry.discard(sessionId, tracker.turn);
|
|
1938
|
+
interactionController?.abort(new DOMException('Harness turn finished', 'AbortError'));
|
|
1939
|
+
if (interactionTask) await interactionTask.catch(() => undefined);
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
async #watchInteractionStream(sessionId, {
|
|
1944
|
+
signal,
|
|
1945
|
+
onInteraction,
|
|
1946
|
+
onResolved,
|
|
1947
|
+
onSessionEvent,
|
|
1948
|
+
onOpen,
|
|
1949
|
+
ownership,
|
|
1950
|
+
}) {
|
|
1951
|
+
let settled = false;
|
|
1952
|
+
let callbackFailure = null;
|
|
1953
|
+
let callbackTail = Promise.resolve();
|
|
1954
|
+
let ownershipReady = ownership === undefined || ownership === null;
|
|
1955
|
+
const bufferedEnvelopes = [];
|
|
1956
|
+
let close = () => {};
|
|
1957
|
+
const handleOpen = (closeStream) => {
|
|
1958
|
+
close = closeStream;
|
|
1959
|
+
if (ownership) ownership.reconnect = close;
|
|
1960
|
+
try {
|
|
1961
|
+
onOpen?.();
|
|
1962
|
+
} catch (error) {
|
|
1963
|
+
console.warn('[dsh-im] ignored an interaction open callback failure:', this.#logPrefix, error.message);
|
|
1964
|
+
}
|
|
1965
|
+
if (ownership) {
|
|
1966
|
+
void this.#refreshInteractionOwnerships(sessionId, signal).then(() => {
|
|
1967
|
+
if (settled) return;
|
|
1968
|
+
ownershipReady = true;
|
|
1969
|
+
for (const envelope of bufferedEnvelopes.splice(0)) processEnvelope(envelope);
|
|
1970
|
+
}).catch((error) => {
|
|
1971
|
+
callbackFailure ??= error;
|
|
1972
|
+
close();
|
|
1973
|
+
});
|
|
1974
|
+
}
|
|
1975
|
+
};
|
|
1976
|
+
const dispatch = (callback, value) => {
|
|
1977
|
+
if (!callback) return;
|
|
1978
|
+
callbackTail = callbackTail
|
|
1979
|
+
.then(() => callback(value))
|
|
1980
|
+
.catch((error) => {
|
|
1981
|
+
callbackFailure ??= error;
|
|
1982
|
+
close();
|
|
1983
|
+
});
|
|
1984
|
+
};
|
|
1985
|
+
const processEnvelope = (envelope) => {
|
|
1986
|
+
const payload = envelope.payload;
|
|
1987
|
+
if (payload.type === 'session/event') {
|
|
1988
|
+
if (ownership) this.#consumeInteractionOwnerships(sessionId, [payload.event]);
|
|
1989
|
+
dispatch(onSessionEvent, payload.event);
|
|
1990
|
+
return;
|
|
1991
|
+
}
|
|
1992
|
+
if (payload.type === 'question/requested' || payload.type === 'approval/requested') {
|
|
1993
|
+
const kind = payload.type === 'question/requested' ? 'question' : 'approval';
|
|
1994
|
+
const interactionId = kind === 'question' ? envelope.rpcId : payload.approvalId;
|
|
1995
|
+
const claimKey = `${kind}:${interactionId}`;
|
|
1996
|
+
if (ownership) {
|
|
1997
|
+
const claim = this.#interactionOwner(sessionId, claimKey, kind);
|
|
1998
|
+
if (claim?.ownership !== ownership) return;
|
|
1999
|
+
this.#interactionClaims.set(claimKey, claim);
|
|
2000
|
+
}
|
|
2001
|
+
const toolCall = kind === 'approval' && ownership && typeof payload.callId === 'string'
|
|
2002
|
+
? this.#interactionClaims.get(claimKey)?.ownership.toolCalls.get(payload.callId)
|
|
2003
|
+
: undefined;
|
|
2004
|
+
dispatch(onInteraction, Object.freeze({
|
|
2005
|
+
kind,
|
|
2006
|
+
interactionId,
|
|
2007
|
+
rpcId: envelope.rpcId,
|
|
2008
|
+
sessionId,
|
|
2009
|
+
payload,
|
|
2010
|
+
recovered: ownership
|
|
2011
|
+
? this.#interactionClaims.get(claimKey)?.recovered === true
|
|
2012
|
+
: false,
|
|
2013
|
+
...(toolCall ? { toolCall } : {}),
|
|
2014
|
+
reconnect: close,
|
|
2015
|
+
respond: (result, options = {}) => this.respondInteraction(
|
|
2016
|
+
envelope.rpcId,
|
|
2017
|
+
result,
|
|
2018
|
+
{ ...options, signal: options.signal ?? signal },
|
|
2019
|
+
),
|
|
2020
|
+
}));
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
if (payload.type === 'question/resolved' || payload.type === 'approval/resolved') {
|
|
2024
|
+
const kind = payload.type === 'question/resolved' ? 'question' : 'approval';
|
|
2025
|
+
const interactionId = kind === 'question'
|
|
2026
|
+
? payload.questionRpcId
|
|
2027
|
+
: payload.approvalId;
|
|
2028
|
+
const claimKey = `${kind}:${interactionId}`;
|
|
2029
|
+
if (ownership) {
|
|
2030
|
+
const claim = this.#interactionClaims.get(claimKey);
|
|
2031
|
+
if (claim?.ownership !== ownership) return;
|
|
2032
|
+
this.#interactionClaims.delete(claimKey);
|
|
2033
|
+
}
|
|
2034
|
+
dispatch(onResolved, Object.freeze({
|
|
2035
|
+
kind,
|
|
2036
|
+
interactionId,
|
|
2037
|
+
sessionId,
|
|
2038
|
+
outcome: payload.outcome,
|
|
2039
|
+
payload,
|
|
2040
|
+
}));
|
|
2041
|
+
}
|
|
2042
|
+
};
|
|
2043
|
+
const handleEnvelope = (envelope) => {
|
|
2044
|
+
try {
|
|
2045
|
+
const payload = envelope?.payload;
|
|
2046
|
+
if (envelope?.type !== 'server-request'
|
|
2047
|
+
|| typeof envelope.rpcId !== 'string'
|
|
2048
|
+
|| !payload || typeof payload !== 'object'
|
|
2049
|
+
|| envelope.method !== payload.type) {
|
|
2050
|
+
throw new Error('invalid server-request envelope');
|
|
2051
|
+
}
|
|
2052
|
+
if (payload.sessionId !== sessionId) return;
|
|
2053
|
+
if (!ownershipReady) bufferedEnvelopes.push(envelope);
|
|
2054
|
+
else processEnvelope(envelope);
|
|
2055
|
+
} catch (error) {
|
|
2056
|
+
console.warn('[dsh-im] ignored a malformed Harness interaction frame:', this.#logPrefix, error.message);
|
|
2057
|
+
}
|
|
2058
|
+
};
|
|
2059
|
+
try {
|
|
2060
|
+
await this.#watchMux({ signal, onOpen: handleOpen, onEnvelope: handleEnvelope });
|
|
2061
|
+
} finally {
|
|
2062
|
+
settled = true;
|
|
2063
|
+
if (ownership?.reconnect === close) ownership.reconnect = null;
|
|
2064
|
+
if (!signal.aborted) await callbackTail;
|
|
2065
|
+
}
|
|
2066
|
+
if (!signal.aborted && callbackFailure) throw callbackFailure;
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
/**
|
|
2070
|
+
* Watch the global Harness event mux (all sessions) until `signal`
|
|
2071
|
+
* aborts, reconnecting on drop. Both transports deliver the same envelopes;
|
|
2072
|
+
* only session/event payloads are forwarded. onReconnect fires after every
|
|
2073
|
+
* (re)connection so callers can compensate for events missed while offline.
|
|
2074
|
+
*/
|
|
2075
|
+
async watchHarnessEvents({ signal, onSessionEvent, onReconnect } = {}) {
|
|
2076
|
+
if (typeof onSessionEvent !== 'function') {
|
|
2077
|
+
throw new TypeError('watchHarnessEvents requires onSessionEvent');
|
|
2078
|
+
}
|
|
2079
|
+
if (!signal || typeof signal.addEventListener !== 'function') {
|
|
2080
|
+
throw new TypeError('watchHarnessEvents requires an AbortSignal');
|
|
2081
|
+
}
|
|
2082
|
+
if (onReconnect !== undefined && typeof onReconnect !== 'function') {
|
|
2083
|
+
throw new TypeError('onReconnect must be a function');
|
|
2084
|
+
}
|
|
2085
|
+
while (!signal.aborted) {
|
|
2086
|
+
try {
|
|
2087
|
+
await this.#watchMux({
|
|
2088
|
+
signal,
|
|
2089
|
+
onOpen: () => {
|
|
2090
|
+
try {
|
|
2091
|
+
onReconnect?.();
|
|
2092
|
+
} catch (error) {
|
|
2093
|
+
console.warn('[dsh-im] mux reconnect hook failed:', this.#logPrefix, error.message);
|
|
2094
|
+
}
|
|
2095
|
+
},
|
|
2096
|
+
onEnvelope: (envelope) => {
|
|
2097
|
+
try {
|
|
2098
|
+
const payload = envelope?.payload;
|
|
2099
|
+
if (envelope?.type !== 'server-request'
|
|
2100
|
+
|| !payload
|
|
2101
|
+
|| typeof payload !== 'object'
|
|
2102
|
+
|| envelope.method !== payload.type
|
|
2103
|
+
|| payload.type !== 'session/event'
|
|
2104
|
+
|| typeof payload.sessionId !== 'string'
|
|
2105
|
+
|| !payload.event
|
|
2106
|
+
|| typeof payload.event !== 'object') return;
|
|
2107
|
+
onSessionEvent({ sessionId: payload.sessionId, event: payload.event });
|
|
2108
|
+
} catch (error) {
|
|
2109
|
+
console.warn('[dsh-im] ignored a malformed global mux frame:', this.#logPrefix, error.message);
|
|
2110
|
+
}
|
|
2111
|
+
},
|
|
2112
|
+
});
|
|
2113
|
+
} catch (error) {
|
|
2114
|
+
if (signal.aborted) return;
|
|
2115
|
+
console.warn('[dsh-im] Harness event mux disconnected:', this.#logPrefix, error.message);
|
|
2116
|
+
}
|
|
2117
|
+
if (signal.aborted) return;
|
|
2118
|
+
try {
|
|
2119
|
+
await sleep(this.#interactionReconnectDelayMs, signal);
|
|
2120
|
+
} catch {
|
|
2121
|
+
if (signal.aborted) return;
|
|
2122
|
+
throw new Error('Harness event mux reconnect wait failed');
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
|
|
2127
|
+
#watchMux(options) {
|
|
2128
|
+
return watchHarnessMux({
|
|
2129
|
+
apiProxy: this.#apiProxy,
|
|
2130
|
+
baseUrl: this.#baseUrl,
|
|
2131
|
+
createWebSocket: this.#createWebSocket,
|
|
2132
|
+
rpcId: `${this.#rpcIdPrefix}-${randomUUID()}`,
|
|
2133
|
+
...options,
|
|
2134
|
+
onMalformed: (error) => {
|
|
2135
|
+
console.warn('[dsh-im] ignored a malformed Harness mux frame:', this.#logPrefix, error.message);
|
|
2136
|
+
},
|
|
2137
|
+
});
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
stopManagedProcess() {
|
|
2141
|
+
if (this.#managedProcess?.exitCode === null) this.#managedProcess.kill('SIGTERM');
|
|
2142
|
+
}
|
|
2143
|
+
}
|