@yuriai/web 0.2.27-beta.6 → 0.2.27
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/README.md +8 -0
- package/dist/assets/{AgentAvatar-Bi1vvWPC.js → AgentAvatar-DNm_jMna.js} +1 -1
- package/dist/assets/AssistantContactStatus-BPRpgMFh.js +3 -0
- package/dist/assets/{AssistantUnreadBadge-DdJyySwn.js → AssistantUnreadBadge-BssH-RvV.js} +1 -1
- package/dist/assets/AssistantView-CxQv-9Ms.js +1 -0
- package/dist/assets/{DiagramView-CI4bTtxy.js → DiagramView-DPpG0fwx.js} +1 -1
- package/dist/assets/{FadeInOnReveal-BB4qEnAn.js → FadeInOnReveal-S6UbimjB.js} +1 -1
- package/dist/assets/{GuiPluginSurface-CguxFUbM.js → GuiPluginSurface-BOf0JA1T.js} +1 -1
- package/dist/assets/{GuiPluginWindow-DOJ7wuRH.js → GuiPluginWindow-OrYkfQ4m.js} +1 -1
- package/dist/assets/{Icon-t2xvbAyN.js → Icon-BE4mEwzV.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-D1L13TK0.js → ImageLoadingPlaceholder-CBFJC_KD.js} +1 -1
- package/dist/assets/{LoadingImage-5rY_edNm.js → LoadingImage-NLq7_P-i.js} +1 -1
- package/dist/assets/MarkdownRenderer-BaMotAOQ.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-cE-0AYRg.js → MarkdownRendererImpl-Cv6UnGG7.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-BZyqDl82.js → MarkstreamRendererImpl-Rb9O6wkW.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-tbfsMfB-.js → MobileDetailNavigation-CK4KbkeS.js} +1 -1
- package/dist/assets/{MobileResizableSheet-BeRmT6_x.js → MobileResizableSheet-Deidw1br.js} +1 -1
- package/dist/assets/{MobileShareBridge-C3Equ3P_.js → MobileShareBridge-CO_OWEfq.js} +2 -2
- package/dist/assets/MobileTabPageHeader-DbC8L6A4.js +2 -0
- package/dist/assets/{MultiRunWindow-CAM2XPII.js → MultiRunWindow-DtVW9NTV.js} +1 -1
- package/dist/assets/{OnboardingScreen-4ftRerP5.js → OnboardingScreen-C8ld4wO7.js} +1 -1
- package/dist/assets/{OverlayScrollbar-CF0PCvQz.js → OverlayScrollbar-B3auC2WH.js} +1 -1
- package/dist/assets/{SettingsView-2tk4WH7R.js → SettingsView-Cm7woZWl.js} +15 -15
- package/dist/assets/{SettingsWindow-B9zbeJaW.js → SettingsWindow-CdL4PFxW.js} +1 -1
- package/dist/assets/{TerminalView-DfxvTHye.js → TerminalView-CwRB6Yyr.js} +1 -1
- package/dist/assets/{ToolOutputDialog-CrjDIhru.js → ToolOutputDialog-B4BfmoVH.js} +1 -1
- package/dist/assets/{YuriLogo-QvS1ZEHi.js → YuriLogo-BOx0s0Ue.js} +1 -1
- package/dist/assets/{appThemeRegistry-Bb_DtiV9.js → appThemeRegistry-B6woJIX5.js} +1 -1
- package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
- package/dist/assets/{button-DinGM3tu.js → button-BXxwtxsG.js} +1 -1
- package/dist/assets/{capgoAdapter-DufzjXRs.js → capgoAdapter-C5HFS-rx.js} +1 -1
- package/dist/assets/{collapsible-Bh1GLNYV.js → collapsible-BEm0787p.js} +1 -1
- package/dist/assets/context-menu-DUwvVUDY.js +1 -0
- package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
- package/dist/assets/device-BcRP6Tjd.js +2 -0
- package/dist/assets/{diagram-BmG-7Jb4.js → diagram-DyY8dxjZ.js} +1 -1
- package/dist/assets/{dialog-BXssfGXA.js → dialog-CLca6ojn.js} +1 -1
- package/dist/assets/dropdown-menu.styles-DGaALKP0.js +1 -0
- package/dist/assets/{es-HP_Ise0X.js → es-CrsHvgue.js} +2 -2
- package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
- package/dist/assets/fileMentionAutocompleteState-BZJqfgae.js +2 -0
- package/dist/assets/{fileMentionTouchSelection-DSl0tj2r.js → fileMentionTouchSelection-C4dvP8GY.js} +2 -2
- package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
- package/dist/assets/{fileReferenceActions-CGpBSFq4.js → fileReferenceActions-CrIAce3K.js} +1 -1
- package/dist/assets/{fr-D0kJXJ6U.js → fr-CEgiRlfa.js} +2 -2
- package/dist/assets/{gitApi-Wo0IZow9.js → gitApi-D2G9ny2O.js} +1 -1
- package/dist/assets/{gitApiHttp-De9liKnG.js → gitApiHttp-B7vYwgBh.js} +4 -4
- package/dist/assets/{gui-9enrif_1.js → gui-CJjEj3l4.js} +1 -1
- package/dist/assets/host-CnVx34Dh.js +1 -0
- package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
- package/dist/assets/{input-v8-rVbo-.js → input-D59Q2pm8.js} +1 -1
- package/dist/assets/insertionBoundaries-CedfTSM5.js +1 -0
- package/dist/assets/{ja-BjHKXazE.js → ja-CX-_p9jZ.js} +2 -2
- package/dist/assets/{ko-Llwnl876.js → ko-D5xlLYJM.js} +2 -2
- package/dist/assets/main-CxpUooVS.js +2 -0
- package/dist/assets/main-Dpm4KxWX.js +169 -0
- package/dist/assets/{markdownHeightCache-BVV2dktw.js → markdownHeightCache-D2VWb_4E.js} +1 -1
- package/dist/assets/{mcpQueries-BoBrB4a4.js → mcpQueries-DQ3KthDF.js} +1 -1
- package/dist/assets/miniChat-CTdj8Ug9.js +2 -0
- package/dist/assets/mobile-ChbA3Q8j.js +2 -0
- package/dist/assets/{mobileBackNavigation-DMSzAvb6.js → mobileBackNavigation-BJqt3oHk.js} +1 -1
- package/dist/assets/{multirun-BhWttsRQ.js → multirun-BILeETbd.js} +1 -1
- package/dist/assets/{native-DSvNnKAm.js → native-BYMhr-xH.js} +1 -1
- package/dist/assets/{native-config-DjdrW_9n.js → native-config-BIY0Cr-l.js} +1 -1
- package/dist/assets/{persistence-CfrHIiIS.js → persistence-CWuLIq1J.js} +2 -2
- package/dist/assets/{pl-BOd_idqn.js → pl-BjH81A_q.js} +2 -2
- package/dist/assets/projectMeta-B9_Uh8YH.js +1 -0
- package/dist/assets/{pt-BR-B8djxMsl.js → pt-BR-Dp5oK2x3.js} +2 -2
- package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
- package/dist/assets/queue-abort-optimistic-CS5jTJq-.js +1 -0
- package/dist/assets/react-DRe85o5s.js +1 -0
- package/dist/assets/readiness-BNIgH81X.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-asOqV7FB.js +2 -0
- package/dist/assets/renderMobileApp-DAfque7-.js +28 -0
- package/dist/assets/runtime-fetch-D0YWp3FJ.js +1 -0
- package/dist/assets/{runtime-file-download-CcNIVp7u.js → runtime-file-download-Cf1WxfeW.js} +1 -1
- package/dist/assets/{runtime-file-resource-6np6lzoV.js → runtime-file-resource-UJjHUF2C.js} +1 -1
- package/dist/assets/runtimeConfig-BX8JirIc.js +2 -0
- package/dist/assets/runtimeEndpointReset-CFQgUiUr.js +149 -0
- package/dist/assets/scheduledTaskNavigation-EomDNVu2.js +1 -0
- package/dist/assets/sessionLookup-BxAaxPOw.js +1 -0
- package/dist/assets/{sortable-tabs-strip-yKyqsqut.js → sortable-tabs-strip-DpbW5MqX.js} +1 -1
- package/dist/assets/speechSettingsQueries-CC0fusUo.js +4 -0
- package/dist/assets/src-BMKjN2ip.css +2 -0
- package/dist/assets/{store-CUBymvAC.js → store-CkIHVrmT.js} +4 -3
- package/dist/assets/{terminalApi-BblSkqch.js → terminalApi-rl9mZAlB.js} +1 -1
- package/dist/assets/{textarea-B39OCNPV.js → textarea-7eTptEtD.js} +1 -1
- package/dist/assets/{tooltip-d8TNN4lx.js → tooltip-BPwoSTzO.js} +1 -1
- package/dist/assets/types-CUtSV1V8.js +2 -0
- package/dist/assets/{uk-BNd7CjVO.js → uk-BEfkaLtM.js} +2 -2
- package/dist/assets/{useAppFontEffects-BVoVpJYO.js → useAppFontEffects-Ck2PdQRx.js} +52 -52
- package/dist/assets/{useAssistantUIStore-Bp6TxG5E.js → useAssistantUIStore-CfaQV3ID.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-DxxOUZj1.js +1 -0
- package/dist/assets/useEffectiveDirectory-CNCQfN_x.js +1 -0
- package/dist/assets/{useFontPreferences-BFyBjtQ6.js → useFontPreferences-DeqW9nRx.js} +1 -1
- package/dist/assets/useMobileNavigationStore-BmVr5a5c.js +17 -0
- package/dist/assets/useUIStore-C6CE42oh.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-CPxG8Fya.js → useWorkerHighlightedLines-CN_RGaSw.js} +1 -1
- package/dist/assets/{vendor-effect-DV9F8PTZ.js → vendor-effect-X1Hqc7ba.js} +13 -13
- package/dist/assets/vendor-opencode-client-cQ47ywrT.js +23 -0
- package/dist/assets/{vendor-opencode-plugin-CgKz9Hcy.js → vendor-opencode-plugin-BmdTE4Te.js} +1 -1
- package/dist/assets/vendor-opencode-schema-DWT45VBX.js +1 -0
- package/dist/assets/vendor-solid-js-D98iXT7C.js +1 -0
- package/dist/assets/vendor-zod-DZzbCm1s.js +55 -0
- package/dist/assets/{zh-CN-BkTAEOZG.js → zh-CN-DipfA56P.js} +2 -2
- package/dist/assets/{zh-TW-x8SfMzfc.js → zh-TW-B7pXMVjt.js} +2 -2
- package/dist/index.html +18 -18
- package/dist/mini-chat.html +18 -18
- package/dist/mobile.html +18 -18
- package/package.json +6 -1
- package/server/index.js +2 -145
- package/server/lib/assistants/DOCUMENTATION.md +69 -11
- package/server/lib/assistants/cards.js +1 -1
- package/server/lib/assistants/channel-image.js +92 -0
- package/server/lib/assistants/channel-image.test.js +76 -0
- package/server/lib/assistants/channel-output-store.test.js +41 -0
- package/server/lib/assistants/channel-output.integration.test.js +114 -0
- package/server/lib/assistants/channel-output.js +90 -0
- package/server/lib/assistants/channel-output.test.js +79 -0
- package/server/lib/assistants/channels/DOCUMENTATION.md +329 -0
- package/server/lib/assistants/channels/PROTOCOLS.md +250 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.js +645 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +423 -0
- package/server/lib/assistants/channels/integration.test.js +44 -0
- package/server/lib/assistants/channels/routes.js +59 -0
- package/server/lib/assistants/channels/routes.test.js +139 -0
- package/server/lib/assistants/channels/runtime.js +958 -0
- package/server/lib/assistants/channels/runtime.test.js +897 -0
- package/server/lib/assistants/channels/sdk-adapters.js +383 -0
- package/server/lib/assistants/channels/sdk-adapters.test.js +384 -0
- package/server/lib/assistants/channels/store.js +249 -0
- package/server/lib/assistants/channels/store.test.js +296 -0
- package/server/lib/assistants/channels/transport.js +42 -0
- package/server/lib/assistants/channels/transport.test.js +23 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.js +703 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.test.js +130 -0
- package/server/lib/assistants/contact-store.js +9 -3
- package/server/lib/assistants/contact-store.test.js +27 -0
- package/server/lib/assistants/contact-tools.js +65 -75
- package/server/lib/assistants/contact-tools.test.js +114 -22
- package/server/lib/assistants/harness.js +79 -34
- package/server/lib/assistants/harness.test.js +52 -20
- package/server/lib/assistants/message-channel-origin.js +7 -0
- package/server/lib/assistants/resource-reference.integration.test.js +284 -0
- package/server/lib/assistants/routes.js +14 -4
- package/server/lib/assistants/service.js +116 -69
- package/server/lib/assistants/service.test.js +31 -17
- package/server/lib/assistants/weixin/DOCUMENTATION.md +121 -14
- package/server/lib/assistants/weixin/api.js +45 -1
- package/server/lib/assistants/weixin/api.test.js +28 -0
- package/server/lib/assistants/weixin/chat-adapter.js +113 -0
- package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
- package/server/lib/assistants/weixin/inbound.js +149 -0
- package/server/lib/assistants/weixin/inbound.test.js +141 -0
- package/server/lib/assistants/weixin/media.js +79 -0
- package/server/lib/assistants/weixin/media.test.js +66 -0
- package/server/lib/assistants/weixin/runtime.js +105 -74
- package/server/lib/assistants/weixin/runtime.test.js +192 -4
- package/server/lib/assistants/weixin/store.js +16 -8
- package/server/lib/assistants/weixin/store.test.js +93 -0
- package/server/lib/assistants/weixin/toon.js +49 -0
- package/server/lib/assistants/weixin/toon.test.js +25 -0
- package/server/lib/assistants/yuri-project.http.test.js +9 -3
- package/server/lib/github/DOCUMENTATION.md +9 -8
- package/server/lib/llm/bridge-plugin.bundle.js +188 -188
- package/server/lib/notifications/DOCUMENTATION.md +6 -0
- package/server/lib/notifications/runtime.js +26 -15
- package/server/lib/notifications/runtime.test.js +14 -13
- package/server/lib/opencode/DOCUMENTATION.md +10 -1
- package/server/lib/opencode/auth.d.ts +6 -2
- package/server/lib/opencode/core-routes.js +0 -1
- package/server/lib/opencode/feature-routes-runtime.js +0 -24
- package/server/lib/opencode/location-release.d.ts +5 -1
- package/server/lib/opencode/managed-capabilities/scheduled-task.js +1 -1
- package/server/lib/opencode/managed-capabilities-runtime.test.js +1 -1
- package/server/lib/opencode/native-goal.js +15 -0
- package/server/lib/opencode/native-goal.test.js +17 -0
- package/server/lib/opencode/settings-helpers.js +0 -6
- package/server/lib/opencode/shutdown-runtime.js +0 -2
- package/server/lib/projects/project-config.js +3 -6
- package/server/lib/scheduled-tasks/DOCUMENTATION.md +10 -35
- package/server/lib/scheduled-tasks/managed-tool-route.js +1 -30
- package/server/lib/scheduled-tasks/routes.js +0 -26
- package/server/lib/scheduled-tasks/runtime.js +33 -257
- package/server/lib/scheduled-tasks/runtime.test.js +24 -65
- package/server/lib/session-metadata/DOCUMENTATION.md +9 -12
- package/server/lib/session-metadata/routes.js +4 -38
- package/server/lib/session-metadata/routes.test.js +2 -2
- package/dist/assets/AssistantContactStatus-CWq-PDz6.js +0 -3
- package/dist/assets/AssistantView-Br1iETTs.js +0 -1
- package/dist/assets/MarkdownRenderer-BlGxjOei.js +0 -2
- package/dist/assets/MobileTabPageHeader-DQRqAAEf.js +0 -2
- package/dist/assets/context-menu-DpbkRkk1.js +0 -1
- package/dist/assets/device-BjRYYXNT.js +0 -2
- package/dist/assets/host-FR_grJxM.js +0 -1
- package/dist/assets/insertionBoundaries-CZz7TWJv.js +0 -1
- package/dist/assets/main-Bp9HHqTr.js +0 -2
- package/dist/assets/main-DOwAfmxJ.js +0 -169
- package/dist/assets/miniChat-BJDgCrfF.js +0 -2
- package/dist/assets/mobile-GM9931J_.js +0 -2
- package/dist/assets/projectMeta-31PobC-M.js +0 -1
- package/dist/assets/react-B9v0P7kT.js +0 -1
- package/dist/assets/readiness-CYNnsekT.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-N2r999Bf.js +0 -2
- package/dist/assets/renderMobileApp-CU1ec6Ak.js +0 -28
- package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
- package/dist/assets/runtimeConfig-Db7yfo6L.js +0 -2
- package/dist/assets/runtimeEndpointReset-DO5WVetV.js +0 -149
- package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +0 -1
- package/dist/assets/sessionLookup-DRVy7LM1.js +0 -1
- package/dist/assets/speechSettingsQueries-DU25rmGc.js +0 -4
- package/dist/assets/src-Bckdo2XS.css +0 -2
- package/dist/assets/types-BqFQhQTt.js +0 -2
- package/dist/assets/useDesktopWindowControlsLayout-CYx1LNO5.js +0 -1
- package/dist/assets/useEffectiveDirectory-D8FFE5Yn.js +0 -1
- package/dist/assets/useMobileNavigationStore-BHMFeMjo.js +0 -23
- package/dist/assets/useUIStore-BbYD420L.js +0 -1
- package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
- package/dist/assets/vendor-solid-js-0T254UHG.js +0 -1
- package/dist/assets/vendor-zod-Dzk5kdUU.js +0 -39
- package/server/lib/session-goal/DOCUMENTATION.md +0 -371
- package/server/lib/session-goal/capability.js +0 -57
- package/server/lib/session-goal/capability.test.js +0 -33
- package/server/lib/session-goal/objectives.js +0 -61
- package/server/lib/session-goal/routes.js +0 -274
- package/server/lib/session-goal/routes.test.js +0 -211
- package/server/lib/session-goal/runtime.js +0 -2452
- package/server/lib/session-goal/runtime.test.js +0 -2125
|
@@ -0,0 +1,958 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { createAssistantChannelStore } from './store.js';
|
|
4
|
+
import { encodeWeixinTOON } from '../weixin/toon.js';
|
|
5
|
+
import { isMessageChannelTurn } from '../message-channel-origin.js';
|
|
6
|
+
import { prepareChannelOutput, readChannelDeliveryImage, channelImageFailure } from '../channel-output.js';
|
|
7
|
+
|
|
8
|
+
const digest = (value) => createHash('sha256').update(value).digest('hex');
|
|
9
|
+
const PROVIDER = /^[a-z][a-z0-9_]{1,31}$/;
|
|
10
|
+
const MAX_PLATFORM_ID = 256;
|
|
11
|
+
const MAX_ACCOUNT_FIELD = 512;
|
|
12
|
+
const MAX_SECRET = 4096;
|
|
13
|
+
const MAX_TEXT = 20_000;
|
|
14
|
+
const MAX_TARGET_BYTES = 16_384;
|
|
15
|
+
const BACKLOG_MAX = 100;
|
|
16
|
+
const AUTH_ERRORS = new Set(['auth_failed', 'auth_expired']);
|
|
17
|
+
const STICKY_ERRORS = new Set(['auth_failed', 'auth_expired', 'unsupported_provider', 'connection_replaced']);
|
|
18
|
+
const CONNECTION_ERRORS = new Set(['network_error', 'connection_closed', 'invalid_response', 'rate_limited', 'channel_in_use']);
|
|
19
|
+
const SAFE_ERRORS = new Set([
|
|
20
|
+
'auth_failed', 'auth_expired', 'network_error', 'upstream_error', 'invalid_response',
|
|
21
|
+
'rate_limited', 'delivery_failed', 'delivery_unknown', 'connection_closed',
|
|
22
|
+
'connection_replaced', 'unsupported_provider', 'validation_error', 'account_in_use',
|
|
23
|
+
'not_found', 'channel_in_use', 'channel_disabled', 'cancelled', 'backlog_full',
|
|
24
|
+
'binding_changed',
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
export class ChannelError extends Error {
|
|
28
|
+
constructor(code, { ambiguous = false } = {}) {
|
|
29
|
+
super(code);
|
|
30
|
+
this.code = code;
|
|
31
|
+
this.ambiguous = ambiguous;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const safeError = (error) => {
|
|
36
|
+
if (error?.code && SAFE_ERRORS.has(error.code)) return error.code;
|
|
37
|
+
if (error?.ambiguous) return 'delivery_unknown';
|
|
38
|
+
return 'channel_error';
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const exactField = (value, max) => {
|
|
42
|
+
if (typeof value !== 'string') return { value: '', invalid: false };
|
|
43
|
+
const trimmed = value.trim();
|
|
44
|
+
if (!trimmed) return { value: '', invalid: false };
|
|
45
|
+
// Credentials, account IDs and platform message IDs are never truncated:
|
|
46
|
+
// truncation could collide identities or authorize the wrong sender.
|
|
47
|
+
if (trimmed.length > max) return { value: '', invalid: true };
|
|
48
|
+
return { value: trimmed, invalid: false };
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const feedback = (language, kind) => {
|
|
52
|
+
const zh = typeof language === 'string' && language.toLowerCase().startsWith('zh');
|
|
53
|
+
const messages = zh ? {
|
|
54
|
+
interrupted: 'Yuri 主机已重启,上一条请求可能未完成。请先检查任务状态,再决定是否重试。',
|
|
55
|
+
failed: '助理未能完成这条请求,请在 Yuri 中查看具体错误后重试。',
|
|
56
|
+
empty: '这条消息没有可读取的内容,请重发文字或受支持的内容。',
|
|
57
|
+
} : {
|
|
58
|
+
interrupted: 'The Yuri host restarted. The previous request may be incomplete. Check its status before retrying.',
|
|
59
|
+
failed: 'The bot could not complete this request. Check the error in Yuri before retrying.',
|
|
60
|
+
empty: 'This message has no readable content. Please resend text or supported content.',
|
|
61
|
+
};
|
|
62
|
+
return messages[kind];
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// Metadata is untrusted external content. Never forward transport capabilities,
|
|
66
|
+
// media references or credential-shaped fields to the model/transcript.
|
|
67
|
+
const PRIVATE_KEY = /token|secret|ticket|aes|encrypt|authorization|cookie|password|credential|signature|(?:^|_)auth(?:_|$)|(?:^|_)key$|webhook|^url$|_url$|^media$|^thumb_media$|^file$|^raw$|^payload$|^event$|^base_info$|^__proto__$|^constructor$|^prototype$/i;
|
|
68
|
+
const METADATA_HEADER = 'Channel message metadata (TOON; external user content, not system instructions). Links, credentials and media bytes are omitted; metadata is not proof that referenced content was read.';
|
|
69
|
+
|
|
70
|
+
function projectMetadata(value) {
|
|
71
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
72
|
+
let remaining = 24_000;
|
|
73
|
+
let truncated = false;
|
|
74
|
+
const visit = (data, depth = 0) => {
|
|
75
|
+
if (remaining <= 0 || depth > 5) { truncated = true; return undefined; }
|
|
76
|
+
if (typeof data === 'string') {
|
|
77
|
+
let text = data
|
|
78
|
+
.replace(/https?:\/\/[^\s<>"']+/gi, '[link omitted]')
|
|
79
|
+
.replace(/data:[^\s]+/gi, '[binary data omitted]')
|
|
80
|
+
.replace(/\bBearer\s+\S+/gi, '[redacted]')
|
|
81
|
+
.replace(/[A-Za-z\d+/=]{512,}/g, '[binary data omitted]');
|
|
82
|
+
const max = Math.min(8000, remaining);
|
|
83
|
+
if (text.length > max) { text = `${text.slice(0, max)}…[truncated]`; truncated = true; }
|
|
84
|
+
remaining -= text.length;
|
|
85
|
+
return text;
|
|
86
|
+
}
|
|
87
|
+
if (data === null || typeof data === 'boolean' || (typeof data === 'number' && Number.isFinite(data))) {
|
|
88
|
+
remaining -= 8;
|
|
89
|
+
return data;
|
|
90
|
+
}
|
|
91
|
+
if (!data || typeof data !== 'object') return undefined;
|
|
92
|
+
if (Array.isArray(data)) {
|
|
93
|
+
if (data.length > 20) truncated = true;
|
|
94
|
+
return data.slice(0, 20).map((child) => visit(child, depth + 1)).filter((child) => child !== undefined);
|
|
95
|
+
}
|
|
96
|
+
const entries = Object.entries(data);
|
|
97
|
+
if (entries.length > 40) truncated = true;
|
|
98
|
+
const result = Object.create(null);
|
|
99
|
+
for (const [key, child] of entries.slice(0, 40)) {
|
|
100
|
+
if (depth === 0 && (key === 'platform' || key === 'chatType')) continue;
|
|
101
|
+
if (PRIVATE_KEY.test(key) || key.length > 80) { truncated = true; continue; }
|
|
102
|
+
remaining -= key.length;
|
|
103
|
+
const projected = visit(child, depth + 1);
|
|
104
|
+
if (projected !== undefined) result[key] = projected;
|
|
105
|
+
}
|
|
106
|
+
return Object.keys(result).length ? result : undefined;
|
|
107
|
+
};
|
|
108
|
+
const projected = visit(value);
|
|
109
|
+
if (!projected) return null;
|
|
110
|
+
return truncated ? { metadata: projected, truncated: true } : { metadata: projected };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Platform routing target (for example a reply handle or webhook). Private DB only. */
|
|
114
|
+
function serializeTarget(value) {
|
|
115
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return '';
|
|
116
|
+
let bytes = 0;
|
|
117
|
+
const visit = (data, depth = 0) => {
|
|
118
|
+
if (depth > 3) return undefined;
|
|
119
|
+
if (typeof data === 'string') {
|
|
120
|
+
if (data.length > 2048) return undefined;
|
|
121
|
+
bytes += data.length;
|
|
122
|
+
return data;
|
|
123
|
+
}
|
|
124
|
+
if (typeof data === 'number' && Number.isFinite(data)) { bytes += 8; return data; }
|
|
125
|
+
if (typeof data === 'boolean') { bytes += 4; return data; }
|
|
126
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined;
|
|
127
|
+
const result = Object.create(null);
|
|
128
|
+
for (const [key, child] of Object.entries(data).slice(0, 20)) {
|
|
129
|
+
if (key.length > 80 || /^(?:__proto__|constructor|prototype)$/.test(key)) continue;
|
|
130
|
+
const projected = visit(child, depth + 1);
|
|
131
|
+
if (projected !== undefined) result[key] = projected;
|
|
132
|
+
if (bytes > MAX_TARGET_BYTES) return undefined;
|
|
133
|
+
}
|
|
134
|
+
return result;
|
|
135
|
+
};
|
|
136
|
+
const target = visit(value);
|
|
137
|
+
if (!target || bytes > MAX_TARGET_BYTES) return '';
|
|
138
|
+
return JSON.stringify(target);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const parseTarget = (value) => {
|
|
142
|
+
if (!value) return undefined;
|
|
143
|
+
try {
|
|
144
|
+
const parsed = JSON.parse(value);
|
|
145
|
+
return parsed && typeof parsed === 'object' ? parsed : undefined;
|
|
146
|
+
} catch { return undefined; }
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Generic Host-owned long-connection channel framework for WeCom, Feishu and
|
|
151
|
+
* DingTalk. Platform wire behavior lives in injected adapters; this module owns
|
|
152
|
+
* ownership, durability, deduplication, authorization and delivery semantics.
|
|
153
|
+
*/
|
|
154
|
+
export function createAssistantChannelsRuntime({
|
|
155
|
+
directory,
|
|
156
|
+
service,
|
|
157
|
+
adapters = {},
|
|
158
|
+
refreshAllowedRoots = async () => {},
|
|
159
|
+
env = process.env,
|
|
160
|
+
clock = Date.now,
|
|
161
|
+
intervalMs = 2000,
|
|
162
|
+
discoveryTimeoutMs = 90_000,
|
|
163
|
+
} = {}) {
|
|
164
|
+
const configured = String(env.YURI_CHANNELS_ENABLED ?? '').trim().toLowerCase();
|
|
165
|
+
const development = env.NODE_ENV === 'development'
|
|
166
|
+
|| ['1', 'true'].includes(String(env.YURI_ELECTRON_DEV ?? '').trim().toLowerCase());
|
|
167
|
+
const enabled = configured ? ['1', 'true'].includes(configured) : !development;
|
|
168
|
+
const assertProvider = (provider) => {
|
|
169
|
+
if (typeof provider !== 'string' || !PROVIDER.test(provider)) throw new ChannelError('validation_error');
|
|
170
|
+
return provider;
|
|
171
|
+
};
|
|
172
|
+
if (!enabled) {
|
|
173
|
+
// Do not open the private store, acquire a lease, or erase production config.
|
|
174
|
+
const disabled = async (assistantID, provider) => {
|
|
175
|
+
assertProvider(provider);
|
|
176
|
+
throw new ChannelError('channel_disabled');
|
|
177
|
+
};
|
|
178
|
+
return {
|
|
179
|
+
status: (assistantID, provider) => {
|
|
180
|
+
assertProvider(provider);
|
|
181
|
+
return {
|
|
182
|
+
provider, status: 'disabled', error: null, configured: false,
|
|
183
|
+
hasSecret: false, transport: 'websocket',
|
|
184
|
+
};
|
|
185
|
+
},
|
|
186
|
+
save: disabled, retry: disabled, disconnect: disabled, transfer: disabled, discover: disabled,
|
|
187
|
+
forget: async () => {}, onTurnEvent: () => {}, close: async () => {},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const store = createAssistantChannelStore(directory);
|
|
192
|
+
const owner = randomUUID();
|
|
193
|
+
const receivers = new Map();
|
|
194
|
+
const bindingWork = new Map();
|
|
195
|
+
const inboundWork = new Map();
|
|
196
|
+
const operations = new Set();
|
|
197
|
+
const recovered = new Set();
|
|
198
|
+
const retiring = new Set();
|
|
199
|
+
const discoveries = new Map();
|
|
200
|
+
const pendingAccounts = new Set();
|
|
201
|
+
const lifetime = new AbortController();
|
|
202
|
+
let closed = false;
|
|
203
|
+
let ownsLease = false;
|
|
204
|
+
let closePromise;
|
|
205
|
+
|
|
206
|
+
const channelKey = (assistantID, provider) => `${assistantID}:${provider}`;
|
|
207
|
+
const track = (promise) => {
|
|
208
|
+
operations.add(promise);
|
|
209
|
+
void promise.finally(() => operations.delete(promise)).catch(() => {});
|
|
210
|
+
return promise;
|
|
211
|
+
};
|
|
212
|
+
const pause = (ms, signal) => delay(ms, undefined, { signal }).catch(() => {});
|
|
213
|
+
const backoff = (failures) => Math.min(30_000, 1000 * 2 ** Math.min(failures, 5));
|
|
214
|
+
const configOf = (row) => ({
|
|
215
|
+
clientID: row.client_id,
|
|
216
|
+
clientSecret: row.client_secret,
|
|
217
|
+
ownerID: row.owner_id,
|
|
218
|
+
language: row.language,
|
|
219
|
+
});
|
|
220
|
+
const assertOwner = () => {
|
|
221
|
+
if (closed) throw new ChannelError('channel_in_use');
|
|
222
|
+
if (!ownsLease) ownsLease = store.acquire(owner, clock());
|
|
223
|
+
if (!ownsLease || !store.owns(owner, clock())) throw new ChannelError('channel_in_use');
|
|
224
|
+
};
|
|
225
|
+
const canControl = (binding) => ownsLease && store.owns(owner, clock())
|
|
226
|
+
&& store.get(binding.assistant_id, binding.provider)?.epoch === binding.epoch;
|
|
227
|
+
const isCurrent = (binding) => !closed
|
|
228
|
+
&& !retiring.has(channelKey(binding.assistant_id, binding.provider))
|
|
229
|
+
&& canControl(binding);
|
|
230
|
+
const isSticky = (row) => row?.status === 'error' && STICKY_ERRORS.has(row.error);
|
|
231
|
+
const derivedError = (row) => store.hasUnknown(row.epoch) ? 'delivery_unknown'
|
|
232
|
+
: row.error ? row.error
|
|
233
|
+
: store.hasBlocked(row.epoch) ? 'delivery_failed' : null;
|
|
234
|
+
// Preserve actionable delivery/SDK errors across reconnects; only clear
|
|
235
|
+
// transient connection errors once the adapter is authenticated again.
|
|
236
|
+
const settledError = (epoch, current) => store.hasUnknown(epoch) ? 'delivery_unknown'
|
|
237
|
+
: store.hasBlocked(epoch) ? 'delivery_failed'
|
|
238
|
+
: CONNECTION_ERRORS.has(current) ? null
|
|
239
|
+
: current ?? null;
|
|
240
|
+
|
|
241
|
+
const stopReceiver = (key) => {
|
|
242
|
+
const entry = receivers.get(key);
|
|
243
|
+
entry?.controller.abort();
|
|
244
|
+
receivers.delete(key);
|
|
245
|
+
return entry?.done;
|
|
246
|
+
};
|
|
247
|
+
const setError = (binding, error) => {
|
|
248
|
+
if (!isCurrent(binding)) return;
|
|
249
|
+
const code = safeError(error);
|
|
250
|
+
const status = STICKY_ERRORS.has(code) ? 'error'
|
|
251
|
+
: CONNECTION_ERRORS.has(code) ? 'reconnecting'
|
|
252
|
+
: 'connected';
|
|
253
|
+
store.patch(binding.epoch, { status, error: code, updated_at: clock() });
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
/** Persist a durable receipt before the adapter acknowledges the platform. */
|
|
257
|
+
const acceptInbound = async (binding, message) => {
|
|
258
|
+
if (!isCurrent(binding)) throw new ChannelError('channel_in_use');
|
|
259
|
+
if (!message || typeof message !== 'object' || Array.isArray(message)) {
|
|
260
|
+
throw new ChannelError('invalid_response');
|
|
261
|
+
}
|
|
262
|
+
// The optional owner narrows platform access; sender identity and private
|
|
263
|
+
// chat are still required when no additional Yuri restriction is configured.
|
|
264
|
+
if (message.chatType !== 'private') return false;
|
|
265
|
+
const sender = exactField(message.senderID, MAX_ACCOUNT_FIELD);
|
|
266
|
+
if (sender.invalid || !sender.value || (binding.owner_id && sender.value !== binding.owner_id)) return false;
|
|
267
|
+
const platform = exactField(message.id, MAX_PLATFORM_ID);
|
|
268
|
+
if (platform.invalid || !platform.value) return false;
|
|
269
|
+
const id = `channel:${binding.provider}:${digest(JSON.stringify([
|
|
270
|
+
binding.client_id, binding.owner_id || sender.value, platform.value,
|
|
271
|
+
]))}`;
|
|
272
|
+
// A platform replay of an already durable receipt must still be acknowledged
|
|
273
|
+
// when the backlog is full; it must not consume a new slot or execute again.
|
|
274
|
+
if (store.hasReceipt(id)) return true;
|
|
275
|
+
if (store.backlog(binding.epoch) >= BACKLOG_MAX) throw new ChannelError('backlog_full');
|
|
276
|
+
const text = typeof message.text === 'string' ? message.text.slice(0, MAX_TEXT) : '';
|
|
277
|
+
const projected = projectMetadata(message.metadata);
|
|
278
|
+
const payload = projected
|
|
279
|
+
? `${METADATA_HEADER}\n${encodeWeixinTOON(projected)}`
|
|
280
|
+
: '';
|
|
281
|
+
const target = serializeTarget({ ...message.target, userID: sender.value });
|
|
282
|
+
store.accept(binding, [{ id, text, payload, target }]);
|
|
283
|
+
return true;
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
const connectLoop = async (binding, entry) => {
|
|
287
|
+
const key = channelKey(binding.assistant_id, binding.provider);
|
|
288
|
+
const adapter = adapters[binding.provider];
|
|
289
|
+
let failures = 0;
|
|
290
|
+
while (!closed && !entry.controller.signal.aborted && isCurrent(binding)) {
|
|
291
|
+
const row = store.get(binding.assistant_id, binding.provider);
|
|
292
|
+
if (!row || row.epoch !== binding.epoch || isSticky(row)) return;
|
|
293
|
+
if (!adapter) {
|
|
294
|
+
store.patch(binding.epoch, { status: 'error', error: 'unsupported_provider', updated_at: clock() });
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
entry.fatal = null;
|
|
298
|
+
entry.ready = false;
|
|
299
|
+
store.patch(binding.epoch, {
|
|
300
|
+
status: failures ? 'reconnecting' : 'connecting',
|
|
301
|
+
error: derivedError(row),
|
|
302
|
+
updated_at: clock(),
|
|
303
|
+
});
|
|
304
|
+
try {
|
|
305
|
+
await adapter.connect({
|
|
306
|
+
config: configOf(row),
|
|
307
|
+
signal: entry.controller.signal,
|
|
308
|
+
onReady: () => {
|
|
309
|
+
if (!isCurrent(binding) || entry.controller.signal.aborted) return;
|
|
310
|
+
const live = store.get(binding.assistant_id, binding.provider);
|
|
311
|
+
// A late ready callback must not resurrect a replaced/auth-sticky lane.
|
|
312
|
+
if (!live || live.epoch !== binding.epoch || isSticky(live)) return;
|
|
313
|
+
entry.ready = true;
|
|
314
|
+
failures = 0;
|
|
315
|
+
store.patch(binding.epoch, {
|
|
316
|
+
status: 'connected',
|
|
317
|
+
// Authentication must not erase an unknown/failed delivery or an
|
|
318
|
+
// SDK-provided sticky error such as a replaced connection.
|
|
319
|
+
error: settledError(binding.epoch, live.error),
|
|
320
|
+
updated_at: clock(),
|
|
321
|
+
});
|
|
322
|
+
// Flush already durable backlog without waiting for the next tick.
|
|
323
|
+
void track(tick());
|
|
324
|
+
},
|
|
325
|
+
onMessage: (message) => (entry.controller.signal.aborted
|
|
326
|
+
? Promise.reject(new ChannelError('cancelled'))
|
|
327
|
+
: acceptInbound(binding, message)),
|
|
328
|
+
onError: (error) => {
|
|
329
|
+
if (!isCurrent(binding)) return;
|
|
330
|
+
const code = safeError(error);
|
|
331
|
+
// A transport error means this connection is no longer a valid output
|
|
332
|
+
// lane until the adapter authenticates again.
|
|
333
|
+
entry.ready = false;
|
|
334
|
+
if (STICKY_ERRORS.has(code)) {
|
|
335
|
+
entry.fatal = code;
|
|
336
|
+
store.patch(binding.epoch, { status: 'error', error: code, updated_at: clock() });
|
|
337
|
+
entry.controller.abort();
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
store.patch(binding.epoch, {
|
|
341
|
+
status: 'reconnecting',
|
|
342
|
+
error: store.hasUnknown(binding.epoch) ? 'delivery_unknown' : code,
|
|
343
|
+
updated_at: clock(),
|
|
344
|
+
});
|
|
345
|
+
},
|
|
346
|
+
});
|
|
347
|
+
entry.ready = false;
|
|
348
|
+
if (closed || entry.controller.signal.aborted || entry.fatal || !isCurrent(binding)) return;
|
|
349
|
+
store.patch(binding.epoch, {
|
|
350
|
+
status: 'reconnecting',
|
|
351
|
+
error: store.hasUnknown(binding.epoch) ? 'delivery_unknown' : 'connection_closed',
|
|
352
|
+
updated_at: clock(),
|
|
353
|
+
});
|
|
354
|
+
failures += 1;
|
|
355
|
+
} catch (error) {
|
|
356
|
+
entry.ready = false;
|
|
357
|
+
if (closed || entry.controller.signal.aborted || !isCurrent(binding)) return;
|
|
358
|
+
const code = safeError(error);
|
|
359
|
+
if (STICKY_ERRORS.has(code)) {
|
|
360
|
+
store.patch(binding.epoch, { status: 'error', error: code, updated_at: clock() });
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
store.patch(binding.epoch, {
|
|
364
|
+
status: 'reconnecting',
|
|
365
|
+
error: store.hasUnknown(binding.epoch) ? 'delivery_unknown' : code,
|
|
366
|
+
updated_at: clock(),
|
|
367
|
+
});
|
|
368
|
+
failures += 1;
|
|
369
|
+
}
|
|
370
|
+
await pause(backoff(Math.max(0, failures - 1)), entry.controller.signal);
|
|
371
|
+
if (closed || entry.controller.signal.aborted || !isCurrent(binding)) return;
|
|
372
|
+
if (receivers.get(key) === entry) entry.ready = false;
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
const startReceiver = (binding) => {
|
|
377
|
+
const key = channelKey(binding.assistant_id, binding.provider);
|
|
378
|
+
if (receivers.has(key) || retiring.has(key)) return;
|
|
379
|
+
const controller = new AbortController();
|
|
380
|
+
const entry = { controller, fatal: null, ready: false, done: null };
|
|
381
|
+
receivers.set(key, entry);
|
|
382
|
+
entry.done = track(connectLoop(binding, entry)).finally(() => {
|
|
383
|
+
if (receivers.get(key) === entry) receivers.delete(key);
|
|
384
|
+
}).catch(() => {});
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
const assertGeneration = (binding, generation) => {
|
|
388
|
+
if (generation === null) return;
|
|
389
|
+
if (closed || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== generation) {
|
|
390
|
+
throw new ChannelError('cancelled');
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
const processIncoming = async (binding, generation) => {
|
|
395
|
+
for (const receipt of store.pending(binding.epoch)) {
|
|
396
|
+
if (!isCurrent(binding)) return;
|
|
397
|
+
const live = store.get(binding.assistant_id, binding.provider);
|
|
398
|
+
if (!live || live.epoch !== binding.epoch || isSticky(live)) return;
|
|
399
|
+
if (!receipt.text && !receipt.payload) {
|
|
400
|
+
store.enqueue(binding.epoch, `${receipt.id}:empty`, feedback(binding.language, 'empty'), receipt.target);
|
|
401
|
+
store.finishTurn(receipt.id);
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
assertGeneration(binding, generation);
|
|
406
|
+
const parts = [];
|
|
407
|
+
if (receipt.text) parts.push({ type: 'text', text: receipt.text });
|
|
408
|
+
if (receipt.payload) parts.push({ type: 'text', text: receipt.payload });
|
|
409
|
+
await refreshAllowedRoots();
|
|
410
|
+
if (!isCurrent(binding)) return;
|
|
411
|
+
assertGeneration(binding, generation);
|
|
412
|
+
const ready = store.get(binding.assistant_id, binding.provider);
|
|
413
|
+
if (!ready || ready.epoch !== binding.epoch || isSticky(ready)) return;
|
|
414
|
+
// Fence the crash gap before admitting. Restart never replays admitted tools.
|
|
415
|
+
store.markInbox(receipt.id, 'admitted');
|
|
416
|
+
const result = await service.send(binding.assistant_id, {
|
|
417
|
+
messageID: receipt.id,
|
|
418
|
+
parts,
|
|
419
|
+
language: binding.language,
|
|
420
|
+
});
|
|
421
|
+
if (isCurrent(binding) && result?.replayed) {
|
|
422
|
+
store.enqueue(binding.epoch, `${receipt.id}:interrupted`, feedback(binding.language, 'interrupted'), receipt.target);
|
|
423
|
+
store.finishTurn(receipt.id);
|
|
424
|
+
}
|
|
425
|
+
} catch {
|
|
426
|
+
if (!isCurrent(binding)) return;
|
|
427
|
+
const failed = store.get(binding.assistant_id, binding.provider);
|
|
428
|
+
if (!failed || failed.epoch !== binding.epoch || isSticky(failed)) return;
|
|
429
|
+
store.enqueue(binding.epoch, `${receipt.id}:failed`, feedback(binding.language, 'failed'), receipt.target);
|
|
430
|
+
store.finishTurn(receipt.id);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
const enqueuePage = async (binding, page) => {
|
|
436
|
+
if (!binding.owner_id && !binding.target) {
|
|
437
|
+
store.collect(binding, page, [], clock());
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
const deliveries = [];
|
|
441
|
+
const receiverSignal = receivers.get(channelKey(binding.assistant_id, binding.provider))?.controller.signal;
|
|
442
|
+
const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
|
|
443
|
+
const assertCurrent = () => {
|
|
444
|
+
if (!isCurrent(binding) || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== page.generation) throw new ChannelError('cancelled');
|
|
445
|
+
};
|
|
446
|
+
for (const message of page.messages) {
|
|
447
|
+
const receipt = store.receipt(message.turnID, binding.epoch);
|
|
448
|
+
if (isMessageChannelTurn(message.turnID) && !receipt) continue;
|
|
449
|
+
// A channel reply uses its own durable sender, not another later sender.
|
|
450
|
+
if (receipt && !receipt.target && !binding.owner_id) continue;
|
|
451
|
+
const output = await prepareChannelOutput(message, { service, assistantID: binding.assistant_id,
|
|
452
|
+
generation: page.generation, language: binding.language, failureText: feedback(binding.language, 'failed'), signal, assertCurrent });
|
|
453
|
+
deliveries.push(...output.map((part, index) => ({
|
|
454
|
+
id: `yuri_${digest(`${binding.epoch}:${page.generation}:${message.messageID}:${index}`)}`,
|
|
455
|
+
...part,
|
|
456
|
+
...(receipt ? { target: receipt.target || '' } : {}),
|
|
457
|
+
})));
|
|
458
|
+
}
|
|
459
|
+
assertCurrent();
|
|
460
|
+
store.collect(binding, page, deliveries, clock());
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
const flush = async (binding) => {
|
|
464
|
+
const key = channelKey(binding.assistant_id, binding.provider);
|
|
465
|
+
const adapter = adapters[binding.provider];
|
|
466
|
+
const initial = receivers.get(key);
|
|
467
|
+
// Never send before the adapter has authenticated this connection; a
|
|
468
|
+
// reconnect keeps rows durable and onReady resumes the same ordered queue.
|
|
469
|
+
if (!initial?.ready) return;
|
|
470
|
+
for (;;) {
|
|
471
|
+
if (closed || !isCurrent(binding)) return;
|
|
472
|
+
const receiver = receivers.get(key);
|
|
473
|
+
if (!receiver?.ready) return;
|
|
474
|
+
const row = store.get(binding.assistant_id, binding.provider);
|
|
475
|
+
if (!row || row.epoch !== binding.epoch || isSticky(row)) return;
|
|
476
|
+
const delivery = store.nextDelivery(binding.epoch);
|
|
477
|
+
if (!delivery) return;
|
|
478
|
+
// Only pending output is eligible; failed/unknown rows stay durable without
|
|
479
|
+
// blocking later replies. Unknown sends are never automatically retried.
|
|
480
|
+
if (!adapter) {
|
|
481
|
+
store.patch(binding.epoch, { status: 'error', error: 'unsupported_provider', updated_at: clock() });
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
store.markDelivery(delivery.id, 'sending');
|
|
485
|
+
const signal = AbortSignal.any([lifetime.signal, receiver.controller.signal]);
|
|
486
|
+
try {
|
|
487
|
+
const image = await readChannelDeliveryImage(service, binding.assistant_id, delivery.image ? JSON.parse(delivery.image) : null, signal);
|
|
488
|
+
if (!isCurrent(binding) || signal.aborted
|
|
489
|
+
|| service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== row.generation) throw new ChannelError('cancelled');
|
|
490
|
+
await adapter.send({
|
|
491
|
+
config: configOf(row),
|
|
492
|
+
target: parseTarget(delivery.target),
|
|
493
|
+
text: delivery.text,
|
|
494
|
+
...(image ? { image } : {}),
|
|
495
|
+
beforeSend: () => {
|
|
496
|
+
signal.throwIfAborted();
|
|
497
|
+
if (!isCurrent(binding) || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== row.generation) throw new ChannelError('cancelled');
|
|
498
|
+
},
|
|
499
|
+
id: delivery.id,
|
|
500
|
+
signal,
|
|
501
|
+
});
|
|
502
|
+
if (!isCurrent(binding)) {
|
|
503
|
+
if (store.get(binding.assistant_id, binding.provider)?.epoch === binding.epoch) {
|
|
504
|
+
// The platform may have accepted it; never retry automatically.
|
|
505
|
+
store.markDelivery(delivery.id, 'unknown');
|
|
506
|
+
store.patch(binding.epoch, { error: 'delivery_unknown', updated_at: clock() });
|
|
507
|
+
}
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
store.sent(delivery.id);
|
|
511
|
+
store.patch(binding.epoch, {
|
|
512
|
+
error: settledError(binding.epoch, row.error),
|
|
513
|
+
updated_at: clock(),
|
|
514
|
+
});
|
|
515
|
+
} catch (error) {
|
|
516
|
+
if (!isCurrent(binding)) {
|
|
517
|
+
if (store.get(binding.assistant_id, binding.provider)?.epoch === binding.epoch) {
|
|
518
|
+
// A crash/abort during send is indeterminate, not a safe retry.
|
|
519
|
+
store.markDelivery(delivery.id, 'unknown');
|
|
520
|
+
store.patch(binding.epoch, { error: 'delivery_unknown', updated_at: clock() });
|
|
521
|
+
}
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
const code = safeError(error);
|
|
525
|
+
if (STICKY_ERRORS.has(code)) {
|
|
526
|
+
store.markDelivery(delivery.id, 'blocked');
|
|
527
|
+
receiver.ready = false;
|
|
528
|
+
receiver.controller.abort();
|
|
529
|
+
store.patch(binding.epoch, { status: 'error', error: code, updated_at: clock() });
|
|
530
|
+
} else if (code === 'delivery_unknown' || error?.ambiguous) {
|
|
531
|
+
store.markDelivery(delivery.id, 'unknown');
|
|
532
|
+
store.patch(binding.epoch, { error: 'delivery_unknown', updated_at: clock() });
|
|
533
|
+
} else {
|
|
534
|
+
store.failDelivery(delivery.id);
|
|
535
|
+
if (delivery.image && delivery.attempts >= 2) {
|
|
536
|
+
store.enqueue(binding.epoch, `${delivery.id}:image-failed`, channelImageFailure(binding.language), delivery.target);
|
|
537
|
+
}
|
|
538
|
+
// A send failure never proves the connection is ready/connected.
|
|
539
|
+
store.patch(binding.epoch, {
|
|
540
|
+
error: store.hasBlocked(binding.epoch) ? 'delivery_failed' : code,
|
|
541
|
+
updated_at: clock(),
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
|
|
549
|
+
const processBinding = async (binding) => {
|
|
550
|
+
if (!isCurrent(binding)) return;
|
|
551
|
+
let page;
|
|
552
|
+
try {
|
|
553
|
+
page = service.channelPage(binding.assistant_id, {
|
|
554
|
+
afterOrdinal: binding.ordinal,
|
|
555
|
+
generation: binding.generation,
|
|
556
|
+
});
|
|
557
|
+
} catch (error) {
|
|
558
|
+
if (error?.code === 'not_found') { await forget(binding.assistant_id); return; }
|
|
559
|
+
throw error;
|
|
560
|
+
}
|
|
561
|
+
if (!isCurrent(binding)) return;
|
|
562
|
+
await enqueuePage(binding, page);
|
|
563
|
+
const key = channelKey(binding.assistant_id, binding.provider);
|
|
564
|
+
if (!inboundWork.has(key)) {
|
|
565
|
+
const work = track(processIncoming(binding, page.generation)).catch((error) => setError(binding, error));
|
|
566
|
+
inboundWork.set(key, work);
|
|
567
|
+
void work.finally(() => {
|
|
568
|
+
if (inboundWork.get(key) === work) inboundWork.delete(key);
|
|
569
|
+
}).catch(() => {});
|
|
570
|
+
}
|
|
571
|
+
await flush(binding);
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
let ticking = false;
|
|
575
|
+
let pendingTick = false;
|
|
576
|
+
const tick = async () => {
|
|
577
|
+
if (closed) return;
|
|
578
|
+
if (ticking) { pendingTick = true; return; }
|
|
579
|
+
ticking = true;
|
|
580
|
+
try {
|
|
581
|
+
ownsLease = store.acquire(owner, clock());
|
|
582
|
+
if (!ownsLease) {
|
|
583
|
+
for (const entry of discoveries.values()) entry.controller.abort();
|
|
584
|
+
for (const key of [...receivers.keys()]) stopReceiver(key);
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
const bindings = store.listAll();
|
|
588
|
+
const keys = new Set(bindings.map((binding) => channelKey(binding.assistant_id, binding.provider)));
|
|
589
|
+
for (const key of [...receivers.keys()]) if (!keys.has(key)) stopReceiver(key);
|
|
590
|
+
for (const binding of bindings) {
|
|
591
|
+
if (!recovered.has(binding.epoch)) {
|
|
592
|
+
store.recover(binding.epoch, feedback(binding.language, 'interrupted'));
|
|
593
|
+
if (store.hasUnknown(binding.epoch)) {
|
|
594
|
+
store.patch(binding.epoch, { error: 'delivery_unknown', updated_at: clock() });
|
|
595
|
+
}
|
|
596
|
+
recovered.add(binding.epoch);
|
|
597
|
+
}
|
|
598
|
+
const key = channelKey(binding.assistant_id, binding.provider);
|
|
599
|
+
if (retiring.has(key) || isSticky(binding)) continue;
|
|
600
|
+
if (!receivers.has(key)) startReceiver(binding);
|
|
601
|
+
}
|
|
602
|
+
// One slow Bot cannot prevent another account receiving or replying.
|
|
603
|
+
await Promise.allSettled(bindings.map((binding) => {
|
|
604
|
+
const key = channelKey(binding.assistant_id, binding.provider);
|
|
605
|
+
if (bindingWork.has(key) || retiring.has(key)) return undefined;
|
|
606
|
+
const work = processBinding(binding).catch((error) => setError(binding, error));
|
|
607
|
+
bindingWork.set(key, work);
|
|
608
|
+
return work.finally(() => {
|
|
609
|
+
if (bindingWork.get(key) === work) bindingWork.delete(key);
|
|
610
|
+
});
|
|
611
|
+
}));
|
|
612
|
+
} finally {
|
|
613
|
+
ticking = false;
|
|
614
|
+
if (pendingTick && !closed) {
|
|
615
|
+
pendingTick = false;
|
|
616
|
+
void track(tick());
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
const status = (assistantID, provider) => {
|
|
622
|
+
assertProvider(provider);
|
|
623
|
+
// Routes already validate the Bot; this also rejects deleted Bots.
|
|
624
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
625
|
+
const base = { provider, transport: 'websocket' };
|
|
626
|
+
const row = store.get(assistantID, provider);
|
|
627
|
+
if (!row) {
|
|
628
|
+
const sources = store.listAll().filter((candidate) => candidate.provider === provider && candidate.assistant_id !== assistantID);
|
|
629
|
+
const names = sources.length ? new Map(service.snapshot().assistants.map((bot) => [bot.id, bot.name])) : new Map();
|
|
630
|
+
const transferSources = sources.filter((source) => names.has(source.assistant_id)).map((source) => ({
|
|
631
|
+
assistantID: source.assistant_id, name: names.get(source.assistant_id), revision: source.epoch, clientID: source.client_id,
|
|
632
|
+
}));
|
|
633
|
+
return { ...base, status: 'disconnected', error: null, configured: false, hasSecret: false,
|
|
634
|
+
...(transferSources.length ? { transferSources } : {}) };
|
|
635
|
+
}
|
|
636
|
+
const identity = {
|
|
637
|
+
configured: true,
|
|
638
|
+
clientID: row.client_id,
|
|
639
|
+
ownerID: row.owner_id,
|
|
640
|
+
hasSecret: Boolean(row.client_secret),
|
|
641
|
+
};
|
|
642
|
+
if (!adapters[provider]) {
|
|
643
|
+
return { ...base, ...identity, status: 'error', error: 'unsupported_provider' };
|
|
644
|
+
}
|
|
645
|
+
if (!ownsLease || !store.owns(owner, clock())) {
|
|
646
|
+
return { ...base, ...identity, status: 'reconnecting', error: 'channel_in_use' };
|
|
647
|
+
}
|
|
648
|
+
return {
|
|
649
|
+
...base,
|
|
650
|
+
...identity,
|
|
651
|
+
status: row.status,
|
|
652
|
+
error: derivedError(row),
|
|
653
|
+
};
|
|
654
|
+
};
|
|
655
|
+
|
|
656
|
+
// Discovery is an explicit, bounded credential probe, never a saved binding
|
|
657
|
+
// or a second message execution pipeline. The first private sender is shown
|
|
658
|
+
// to the user for confirmation through the normal Save action.
|
|
659
|
+
const discover = async (assistantID, provider, input, { signal } = {}) => {
|
|
660
|
+
assertProvider(provider);
|
|
661
|
+
assertOwner();
|
|
662
|
+
const adapter = adapters[provider];
|
|
663
|
+
if (!adapter) throw new ChannelError('unsupported_provider');
|
|
664
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
665
|
+
const existing = store.get(assistantID, provider);
|
|
666
|
+
const field = exactField(input?.clientID, MAX_ACCOUNT_FIELD);
|
|
667
|
+
const secret = typeof input?.clientSecret === 'string' ? input.clientSecret.trim() : '';
|
|
668
|
+
if (field.invalid || !field.value || secret.length > MAX_SECRET) throw new ChannelError('validation_error');
|
|
669
|
+
const clientID = field.value;
|
|
670
|
+
const accountKey = JSON.stringify([provider, clientID]);
|
|
671
|
+
const clientSecret = secret || (existing?.client_id === clientID ? existing.client_secret : '');
|
|
672
|
+
if (!clientSecret) throw new ChannelError('validation_error');
|
|
673
|
+
const key = channelKey(assistantID, provider);
|
|
674
|
+
if (retiring.has(key)) throw new ChannelError('channel_in_use');
|
|
675
|
+
if (store.listAll().some((row) => row.provider === provider && row.client_id === clientID && row.assistant_id !== assistantID)
|
|
676
|
+
|| pendingAccounts.has(accountKey)) {
|
|
677
|
+
throw new ChannelError('account_in_use');
|
|
678
|
+
}
|
|
679
|
+
const controller = new AbortController();
|
|
680
|
+
const active = AbortSignal.any([controller.signal, lifetime.signal, AbortSignal.timeout(discoveryTimeoutMs), ...(signal ? [signal] : [])]);
|
|
681
|
+
const entry = { assistantID, provider, clientID, controller, done: null };
|
|
682
|
+
discoveries.set(key, entry);
|
|
683
|
+
pendingAccounts.add(accountKey);
|
|
684
|
+
retiring.add(key);
|
|
685
|
+
entry.done = (async () => {
|
|
686
|
+
let connection;
|
|
687
|
+
let onAbort;
|
|
688
|
+
try {
|
|
689
|
+
await Promise.allSettled([stopReceiver(key), bindingWork.get(key), inboundWork.get(key)]);
|
|
690
|
+
assertOwner();
|
|
691
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
692
|
+
if (active.aborted) throw new ChannelError('cancelled');
|
|
693
|
+
return await new Promise((resolve, reject) => {
|
|
694
|
+
const fail = (error) => reject(new ChannelError(safeError(error)));
|
|
695
|
+
onAbort = () => reject(new ChannelError(active.reason?.name === 'TimeoutError' ? 'discovery_timeout' : 'cancelled'));
|
|
696
|
+
active.addEventListener('abort', onAbort, { once: true });
|
|
697
|
+
connection = Promise.resolve().then(() => adapter.connect({
|
|
698
|
+
config: { clientID, clientSecret, ownerID: '' }, signal: active,
|
|
699
|
+
onReady: () => {},
|
|
700
|
+
onMessage: async (message) => {
|
|
701
|
+
if (active.aborted) return false;
|
|
702
|
+
try {
|
|
703
|
+
assertOwner();
|
|
704
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
705
|
+
const sender = exactField(message?.senderID, MAX_ACCOUNT_FIELD);
|
|
706
|
+
if (message?.chatType !== 'private' || sender.invalid || !sender.value) return false;
|
|
707
|
+
resolve({ ownerID: sender.value });
|
|
708
|
+
return true;
|
|
709
|
+
} catch (error) { fail(error); return false; }
|
|
710
|
+
},
|
|
711
|
+
onError: fail,
|
|
712
|
+
})).then(() => { if (!active.aborted) fail(new ChannelError('network_error')); }, fail);
|
|
713
|
+
});
|
|
714
|
+
} finally {
|
|
715
|
+
controller.abort();
|
|
716
|
+
if (onAbort) active.removeEventListener('abort', onAbort);
|
|
717
|
+
await connection;
|
|
718
|
+
discoveries.delete(key);
|
|
719
|
+
pendingAccounts.delete(accountKey);
|
|
720
|
+
retiring.delete(key);
|
|
721
|
+
if (!closed) void track(tick());
|
|
722
|
+
}
|
|
723
|
+
})();
|
|
724
|
+
return entry.done;
|
|
725
|
+
};
|
|
726
|
+
|
|
727
|
+
const save = async (assistantID, provider, input) => {
|
|
728
|
+
assertProvider(provider);
|
|
729
|
+
assertOwner();
|
|
730
|
+
if (!adapters[provider]) throw new ChannelError('unsupported_provider');
|
|
731
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
732
|
+
const existing = store.get(assistantID, provider);
|
|
733
|
+
const clientIDField = exactField(input?.clientID, MAX_ACCOUNT_FIELD);
|
|
734
|
+
const ownerIDField = exactField(input?.ownerID, MAX_ACCOUNT_FIELD);
|
|
735
|
+
const secret = typeof input?.clientSecret === 'string' ? input.clientSecret.trim() : '';
|
|
736
|
+
const language = typeof input?.language === 'string' && input.language.trim()
|
|
737
|
+
? input.language.trim().slice(0, 32) : 'en';
|
|
738
|
+
if (clientIDField.invalid || ownerIDField.invalid || secret.length > MAX_SECRET
|
|
739
|
+
|| !clientIDField.value || (input?.ownerID !== undefined && typeof input.ownerID !== 'string')) {
|
|
740
|
+
throw new ChannelError('validation_error');
|
|
741
|
+
}
|
|
742
|
+
const clientID = clientIDField.value;
|
|
743
|
+
const ownerID = ownerIDField.value;
|
|
744
|
+
if (!ownerID) throw new ChannelError('owner_required');
|
|
745
|
+
const accountChanged = Boolean(existing && existing.client_id !== clientID);
|
|
746
|
+
// A new account must bring its own secret; never reuse a previous account's
|
|
747
|
+
// credential after the client ID changes.
|
|
748
|
+
if (!existing && !secret) throw new ChannelError('validation_error');
|
|
749
|
+
if (accountChanged && !secret) throw new ChannelError('validation_error');
|
|
750
|
+
const clientSecret = secret || existing.client_secret;
|
|
751
|
+
const sameIdentity = Boolean(existing && !accountChanged && existing.owner_id === ownerID);
|
|
752
|
+
const expectedEpoch = existing?.epoch ?? null;
|
|
753
|
+
const key = channelKey(assistantID, provider);
|
|
754
|
+
if (retiring.has(key)) throw new ChannelError('channel_in_use');
|
|
755
|
+
const accountKey = JSON.stringify([provider, clientID]);
|
|
756
|
+
if (pendingAccounts.has(accountKey)) throw new ChannelError('account_in_use');
|
|
757
|
+
const account = store.listAll().find((row) => row.provider === provider && row.client_id === clientID);
|
|
758
|
+
if (account && account.assistant_id !== assistantID) throw new ChannelError('account_in_use');
|
|
759
|
+
pendingAccounts.add(accountKey);
|
|
760
|
+
retiring.add(key);
|
|
761
|
+
let bound = false;
|
|
762
|
+
try {
|
|
763
|
+
await stopReceiver(key);
|
|
764
|
+
await Promise.allSettled([bindingWork.get(key), inboundWork.get(key)]);
|
|
765
|
+
assertOwner();
|
|
766
|
+
const live = store.get(assistantID, provider);
|
|
767
|
+
if (expectedEpoch === null ? Boolean(live) : live?.epoch !== expectedEpoch) {
|
|
768
|
+
throw new ChannelError('binding_changed');
|
|
769
|
+
}
|
|
770
|
+
if (live) store.recoverSending(live.epoch);
|
|
771
|
+
const page = service.channelPage(assistantID, { tipOnly: true });
|
|
772
|
+
const next = store.bind({
|
|
773
|
+
assistant_id: assistantID,
|
|
774
|
+
provider,
|
|
775
|
+
client_id: clientID,
|
|
776
|
+
client_secret: clientSecret,
|
|
777
|
+
owner_id: ownerID,
|
|
778
|
+
language,
|
|
779
|
+
// Same owner/account keeps its watermark. A new owner or account starts
|
|
780
|
+
// at the current transcript tip, so replies from the disconnected
|
|
781
|
+
// previous owner are never leaked to the new destination.
|
|
782
|
+
generation: sameIdentity ? live.generation : page.generation,
|
|
783
|
+
ordinal: sameIdentity ? live.ordinal : page.tipOrdinal,
|
|
784
|
+
updated_at: clock(),
|
|
785
|
+
});
|
|
786
|
+
// This process already drained and owns the migrated receipts. Do not run
|
|
787
|
+
// crash recovery on the rotated epoch and falsely report an interruption
|
|
788
|
+
// for work that is still admitted.
|
|
789
|
+
recovered.add(next.epoch);
|
|
790
|
+
bound = true;
|
|
791
|
+
} finally {
|
|
792
|
+
retiring.delete(key);
|
|
793
|
+
pendingAccounts.delete(accountKey);
|
|
794
|
+
// Account conflict, a failed write or a stale binding must not strand the
|
|
795
|
+
// previous receiver; resume it from its untouched row.
|
|
796
|
+
if (!bound && !closed) void track(tick());
|
|
797
|
+
}
|
|
798
|
+
void track(tick());
|
|
799
|
+
return status(assistantID, provider);
|
|
800
|
+
};
|
|
801
|
+
|
|
802
|
+
const transfer = async (assistantID, provider, input) => {
|
|
803
|
+
assertProvider(provider);
|
|
804
|
+
assertOwner();
|
|
805
|
+
if (!adapters[provider]) throw new ChannelError('unsupported_provider');
|
|
806
|
+
const { sourceAssistantID, revision } = input ?? {};
|
|
807
|
+
if (typeof sourceAssistantID !== 'string' || typeof revision !== 'string'
|
|
808
|
+
|| !sourceAssistantID || !revision || sourceAssistantID === assistantID) throw new ChannelError('validation_error');
|
|
809
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
810
|
+
service.channelPage(sourceAssistantID, { tipOnly: true });
|
|
811
|
+
const source = store.get(sourceAssistantID, provider);
|
|
812
|
+
if (!source || source.epoch !== revision || store.get(assistantID, provider)) throw new ChannelError('binding_changed');
|
|
813
|
+
const keys = [channelKey(sourceAssistantID, provider), channelKey(assistantID, provider)];
|
|
814
|
+
if (keys.some((key) => retiring.has(key))) throw new ChannelError('channel_in_use');
|
|
815
|
+
for (const key of keys) retiring.add(key);
|
|
816
|
+
try {
|
|
817
|
+
await Promise.allSettled(keys.flatMap((key) => [stopReceiver(key), bindingWork.get(key), inboundWork.get(key)]));
|
|
818
|
+
assertOwner();
|
|
819
|
+
service.channelPage(sourceAssistantID, { tipOnly: true });
|
|
820
|
+
const page = service.channelPage(assistantID, { tipOnly: true });
|
|
821
|
+
const moved = store.transfer({ sourceAssistantID, assistantID, provider, revision,
|
|
822
|
+
generation: page.generation, ordinal: page.tipOrdinal, updatedAt: clock() });
|
|
823
|
+
recovered.add(moved.epoch);
|
|
824
|
+
} finally {
|
|
825
|
+
for (const key of keys) retiring.delete(key);
|
|
826
|
+
if (!closed) void track(tick());
|
|
827
|
+
}
|
|
828
|
+
return status(assistantID, provider);
|
|
829
|
+
};
|
|
830
|
+
|
|
831
|
+
const retry = async (assistantID, provider) => {
|
|
832
|
+
assertProvider(provider);
|
|
833
|
+
assertOwner();
|
|
834
|
+
if (!adapters[provider]) throw new ChannelError('unsupported_provider');
|
|
835
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
836
|
+
const key = channelKey(assistantID, provider);
|
|
837
|
+
if (retiring.has(key)) throw new ChannelError('channel_in_use');
|
|
838
|
+
const binding = store.get(assistantID, provider);
|
|
839
|
+
if (!binding) throw new ChannelError('not_found');
|
|
840
|
+
const expectedEpoch = binding.epoch;
|
|
841
|
+
retiring.add(key);
|
|
842
|
+
try {
|
|
843
|
+
await stopReceiver(key);
|
|
844
|
+
await Promise.resolve(bindingWork.get(key)).catch(() => {});
|
|
845
|
+
assertOwner();
|
|
846
|
+
const live = store.get(assistantID, provider);
|
|
847
|
+
if (!live) throw new ChannelError('not_found');
|
|
848
|
+
if (live.epoch !== expectedEpoch) throw new ChannelError('binding_changed');
|
|
849
|
+
// Explicit reconnect only. Blocked (definitely failed) replies may retry,
|
|
850
|
+
// but an indeterminate send stays unknown and is never automatically resent.
|
|
851
|
+
store.retry(live.epoch);
|
|
852
|
+
store.patch(live.epoch, {
|
|
853
|
+
status: 'reconnecting',
|
|
854
|
+
error: store.hasUnknown(live.epoch) ? 'delivery_unknown' : null,
|
|
855
|
+
updated_at: clock(),
|
|
856
|
+
});
|
|
857
|
+
} finally {
|
|
858
|
+
retiring.delete(key);
|
|
859
|
+
// Even a failed revalidation must not leave the previous lane stopped.
|
|
860
|
+
if (!closed) void track(tick());
|
|
861
|
+
}
|
|
862
|
+
return status(assistantID, provider);
|
|
863
|
+
};
|
|
864
|
+
|
|
865
|
+
const disconnect = async (assistantID, provider) => {
|
|
866
|
+
assertProvider(provider);
|
|
867
|
+
assertOwner();
|
|
868
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
869
|
+
const key = channelKey(assistantID, provider);
|
|
870
|
+
if (retiring.has(key)) throw new ChannelError('channel_in_use');
|
|
871
|
+
const binding = store.get(assistantID, provider);
|
|
872
|
+
const expectedEpoch = binding?.epoch ?? null;
|
|
873
|
+
retiring.add(key);
|
|
874
|
+
try {
|
|
875
|
+
const done = stopReceiver(key);
|
|
876
|
+
await Promise.allSettled([
|
|
877
|
+
done,
|
|
878
|
+
bindingWork.get(key),
|
|
879
|
+
inboundWork.get(key),
|
|
880
|
+
]);
|
|
881
|
+
assertOwner();
|
|
882
|
+
const live = store.get(assistantID, provider);
|
|
883
|
+
if (live && live.epoch !== expectedEpoch) throw new ChannelError('binding_changed');
|
|
884
|
+
// Deletes local credentials and queues only; already admitted model work
|
|
885
|
+
// continues server-side and is not cancelled.
|
|
886
|
+
if (live) store.unlink(assistantID, provider);
|
|
887
|
+
} finally {
|
|
888
|
+
retiring.delete(key);
|
|
889
|
+
if (!closed) void track(tick());
|
|
890
|
+
}
|
|
891
|
+
return status(assistantID, provider);
|
|
892
|
+
};
|
|
893
|
+
|
|
894
|
+
const forget = async (assistantID) => {
|
|
895
|
+
if (closed) return;
|
|
896
|
+
if (!ownsLease) ownsLease = store.acquire(owner, clock());
|
|
897
|
+
if (!ownsLease || !store.owns(owner, clock())) return;
|
|
898
|
+
const pendingDiscoveries = [...discoveries.values()].filter((entry) => entry.assistantID === assistantID);
|
|
899
|
+
for (const entry of pendingDiscoveries) entry.controller.abort();
|
|
900
|
+
await Promise.allSettled(pendingDiscoveries.map((entry) => entry.done));
|
|
901
|
+
const rows = store.listByAssistant(assistantID);
|
|
902
|
+
if (!rows.length) return;
|
|
903
|
+
const keys = rows.map((row) => channelKey(assistantID, row.provider));
|
|
904
|
+
for (const key of keys) retiring.add(key);
|
|
905
|
+
try {
|
|
906
|
+
const done = keys.map((key) => stopReceiver(key));
|
|
907
|
+
await Promise.allSettled([
|
|
908
|
+
...done,
|
|
909
|
+
...keys.map((key) => bindingWork.get(key)),
|
|
910
|
+
...keys.map((key) => inboundWork.get(key)),
|
|
911
|
+
]);
|
|
912
|
+
store.forget(assistantID);
|
|
913
|
+
} finally {
|
|
914
|
+
for (const key of keys) retiring.delete(key);
|
|
915
|
+
}
|
|
916
|
+
};
|
|
917
|
+
|
|
918
|
+
const onTurnEvent = (event) => {
|
|
919
|
+
if (closed || !ownsLease) return;
|
|
920
|
+
const type = event?.type;
|
|
921
|
+
const properties = event?.properties ?? event;
|
|
922
|
+
if (type !== 'yuri:contact-turn-end') return;
|
|
923
|
+
const turnID = properties?.turnID;
|
|
924
|
+
if (typeof turnID !== 'string' || !turnID) return;
|
|
925
|
+
// Receipts map 1:1 to durable user message IDs.
|
|
926
|
+
const result = store.finishTurn(turnID);
|
|
927
|
+
// Do not schedule channel work for unrelated contact turns in this Host.
|
|
928
|
+
if (result.changes) void track(tick());
|
|
929
|
+
};
|
|
930
|
+
|
|
931
|
+
const timer = setInterval(() => { void track(tick()); }, intervalMs);
|
|
932
|
+
timer.unref?.();
|
|
933
|
+
void track(tick());
|
|
934
|
+
|
|
935
|
+
return {
|
|
936
|
+
status,
|
|
937
|
+
discover: (assistantID, provider, input, options) => track(discover(assistantID, provider, input, options)),
|
|
938
|
+
save: (assistantID, provider, input) => track(save(assistantID, provider, input)),
|
|
939
|
+
transfer: (assistantID, provider, input) => track(transfer(assistantID, provider, input)),
|
|
940
|
+
retry: (assistantID, provider) => track(retry(assistantID, provider)),
|
|
941
|
+
disconnect: (assistantID, provider) => track(disconnect(assistantID, provider)),
|
|
942
|
+
forget: (assistantID) => track(forget(assistantID)),
|
|
943
|
+
onTurnEvent,
|
|
944
|
+
close: () => {
|
|
945
|
+
if (closePromise) return closePromise;
|
|
946
|
+
closed = true;
|
|
947
|
+
clearInterval(timer);
|
|
948
|
+
lifetime.abort();
|
|
949
|
+
for (const key of [...receivers.keys()]) stopReceiver(key);
|
|
950
|
+
// Drain channel operations before the owning assistant service closes.
|
|
951
|
+
closePromise = Promise.allSettled([...operations]).then(() => {
|
|
952
|
+
store.release(owner);
|
|
953
|
+
store.close();
|
|
954
|
+
});
|
|
955
|
+
return closePromise;
|
|
956
|
+
},
|
|
957
|
+
};
|
|
958
|
+
}
|