@yuriai/web 0.2.27-beta.3 → 0.2.27-beta.8
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 +17 -0
- package/dist/assets/{AgentAvatar-kIN4sZMz.js → AgentAvatar-BJ42lGZD.js} +1 -1
- package/dist/assets/AssistantContactStatus-dtkObamV.js +3 -0
- package/dist/assets/AssistantUnreadBadge-QwhBfXpC.js +1 -0
- package/dist/assets/AssistantView-D7ryIKL0.js +1 -0
- package/dist/assets/{DiagramView-DK0iXm9b.js → DiagramView-ERrGEBDp.js} +1 -1
- package/dist/assets/{FadeInOnReveal-BJA9Za3T.js → FadeInOnReveal-Bu2GvaM9.js} +1 -1
- package/dist/assets/GuiPluginSurface-MzQgEZNr.js +1 -0
- package/dist/assets/{GuiPluginWindow-l4FYY6S-.js → GuiPluginWindow-DZMmlQzx.js} +1 -1
- package/dist/assets/Icon-Dj4CCqCP.js +1 -0
- package/dist/assets/{ImageLoadingPlaceholder-DCWssLJG.js → ImageLoadingPlaceholder-BnFXgUuO.js} +1 -1
- package/dist/assets/{LoadingImage-C_Hryaqe.js → LoadingImage-PBnivDKv.js} +1 -1
- package/dist/assets/{MarkdownRenderer-Y6uQXIFH.js → MarkdownRenderer-BajF4gUU.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-qKp1tQrP.js → MarkdownRendererImpl-CfyXL4rg.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-B_JTod0h.js → MarkstreamRendererImpl-BGadklK1.js} +1 -1
- package/dist/assets/MobileDetailNavigation-DqajQdB4.js +1 -0
- package/dist/assets/{MobileResizableSheet-F1zSUD1S.js → MobileResizableSheet-BvdUgwA3.js} +1 -1
- package/dist/assets/{MobileShareBridge-F70fkIfS.js → MobileShareBridge-3oPoYnry.js} +2 -2
- package/dist/assets/MobileTabPageHeader-B6cRyIRH.js +2 -0
- package/dist/assets/{MultiRunWindow-D8m6R_4x.js → MultiRunWindow-yhs0Ih5_.js} +1 -1
- package/dist/assets/{OnboardingScreen-BAsPVV_W.js → OnboardingScreen-Bi1VWFQC.js} +1 -1
- package/dist/assets/{OverlayScrollbar-wiRM4AGj.js → OverlayScrollbar-BBDwGvGO.js} +1 -1
- package/dist/assets/{SettingsView-izzjIckv.js → SettingsView-BSf-SJUA.js} +15 -15
- package/dist/assets/{SettingsWindow-CSuHDq_c.js → SettingsWindow-BvSXVMTm.js} +1 -1
- package/dist/assets/TerminalView-DhL01N7e.js +8 -0
- package/dist/assets/{ToolOutputDialog-DJs9w1_J.js → ToolOutputDialog-C8lnH4Ky.js} +1 -1
- package/dist/assets/{YuriLogo-aBS6wlYU.js → YuriLogo-D8asj1CS.js} +1 -1
- package/dist/assets/{appThemeRegistry-BY5rY9-W.js → appThemeRegistry-C-maYSdv.js} +1 -1
- package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
- package/dist/assets/{button-Dt6Ygbc7.js → button-vXOdzd8x.js} +1 -1
- package/dist/assets/{capgoAdapter-MQ1qpf60.js → capgoAdapter-DJ_h2x5D.js} +1 -1
- package/dist/assets/{collapsible-Dm7OHk7m.js → collapsible-DwDQs3Wa.js} +1 -1
- package/dist/assets/context-menu-BabBujQ-.js +1 -0
- package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
- package/dist/assets/{diagram-DWZaG3_v.js → diagram-HwgrQxY5.js} +1 -1
- package/dist/assets/{dialog-CjQeHVOc.js → dialog-Dnf626tb.js} +1 -1
- package/dist/assets/dropdown-menu.styles-CBc_a-Nv.js +1 -0
- package/dist/assets/es-BQkO-Odr.js +15 -0
- package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
- package/dist/assets/{fileMentionTouchSelection-D7QtVxjI.js → fileMentionTouchSelection-CKPnEetl.js} +1 -1
- package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
- package/dist/assets/{fileReferenceActions-BAoEu4z8.js → fileReferenceActions-g7KZLi_G.js} +1 -1
- package/dist/assets/fr-C852roK5.js +13 -0
- package/dist/assets/gitApi-CVq5oKCd.js +370 -0
- package/dist/assets/gitApiHttp-BYOIbYIh.js +7 -0
- package/dist/assets/{gui-9enrif_1.js → gui-M_Rbwkyu.js} +1 -1
- package/dist/assets/host-BW3FEJdU.js +1 -0
- package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
- package/dist/assets/{input-Dq4usRDa.js → input-BtM712b1.js} +1 -1
- package/dist/assets/insertionBoundaries-Dx3WAY6i.js +1 -0
- package/dist/assets/ja-BqC39qK6.js +15 -0
- package/dist/assets/ko-BMaChAWh.js +15 -0
- package/dist/assets/main-9uP2z1qT.js +2 -0
- package/dist/assets/main-Mey7bCWf.js +169 -0
- package/dist/assets/{markdownHeightCache-C1u0bWDL.js → markdownHeightCache-Bf8iisO4.js} +1 -1
- package/dist/assets/{mcpQueries-D2IxTr4k.js → mcpQueries-DpXqegX5.js} +1 -1
- package/dist/assets/miniChat-DqZvVkme.js +2 -0
- package/dist/assets/mobile-DXAWjYcN.js +2 -0
- package/dist/assets/{mobileBackNavigation-vpCg1S7j.js → mobileBackNavigation-DZcI7aZg.js} +1 -1
- package/dist/assets/{multirun-DT-dFXud.js → multirun-hzspPepd.js} +1 -1
- package/dist/assets/{native-De1DIkLZ.js → native-H7K64Ulc.js} +1 -1
- package/dist/assets/{native-config-ncdoz9Wl.js → native-config-CddZtLQ1.js} +1 -1
- package/dist/assets/{persistence-JyLTFv27.js → persistence-BT8045Ue.js} +1 -1
- package/dist/assets/pl-Ubs8p28T.js +15 -0
- package/dist/assets/projectMeta-CEf0QPmD.js +1 -0
- package/dist/assets/pt-BR-8rAOjJrs.js +15 -0
- package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
- package/dist/assets/react-DRe85o5s.js +1 -0
- package/dist/assets/readiness-Dyr7314z.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-DoOq8Cuo.js +2 -0
- package/dist/assets/renderMobileApp-TTxtOb8b.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-B8VHHNxj.js +2 -0
- package/dist/assets/runtimeEndpointReset-BC6XWntz.js +149 -0
- package/dist/assets/scheduledTaskNavigation-Zm87Nydi.js +1 -0
- package/dist/assets/sessionLookup-De53jDwM.js +1 -0
- package/dist/assets/sortable-tabs-strip-D4pVoodN.js +1 -0
- package/dist/assets/speechSettingsQueries-RlCLMBtr.js +4 -0
- package/dist/assets/src-lE4uqaHS.css +2 -0
- package/dist/assets/store-ME7oHni1.js +15 -0
- package/dist/assets/{terminalApi-B5o8UqWA.js → terminalApi-BSaclMDJ.js} +1 -1
- package/dist/assets/{textarea-vtIQM2iP.js → textarea-B98rsLs7.js} +1 -1
- package/dist/assets/{tooltip-BpG2mxrT.js → tooltip-B9810jbK.js} +1 -1
- package/dist/assets/{types-CNTgeeM1.js → types-DFf9vd1b.js} +1 -1
- package/dist/assets/{uk-B_JwElWz.js → uk-LzwzUApL.js} +4 -4
- package/dist/assets/{useAppFontEffects-BguV1Hfa.js → useAppFontEffects-D2C1sBYM.js} +59 -57
- package/dist/assets/{useAssistantUIStore-C9FPlYQz.js → useAssistantUIStore-TUN_ycy5.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-BjKaHN0x.js +1 -0
- package/dist/assets/{useEffectiveDirectory-Ci6Z13kj.js → useEffectiveDirectory-TEvyiQSC.js} +1 -1
- package/dist/assets/{useFontPreferences-DMiP_Yy-.js → useFontPreferences-BlhlCJCX.js} +1 -1
- package/dist/assets/useMobileNavigationStore-DTvJV9s-.js +23 -0
- package/dist/assets/useUIStore-DRx6OgCp.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-HKhuYGSj.js → useWorkerHighlightedLines-D093jNsH.js} +1 -1
- package/dist/assets/{vendor-codemirror-search-ZqtrPLjU.js → vendor-codemirror-search-DiPwvA-6.js} +2 -2
- package/dist/assets/vendor-opencode-client-ZeOZ4Efz.js +23 -0
- package/dist/assets/{vendor-opencode-plugin-Bw7Q6Nv9.js → vendor-opencode-plugin-BBOP6WNx.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-DDj0dSVY.js → vendor-replit-codemirror-vim-DCdAdxvE.js} +3 -3
- package/dist/assets/{vendor-solid-js-0T254UHG.js → vendor-solid-js-9wmPZH9g.js} +1 -1
- package/dist/assets/zh-CN-D-FVCeks.js +15 -0
- package/dist/assets/zh-TW-B9iH_NXL.js +15 -0
- package/dist/index.html +17 -17
- package/dist/mini-chat.html +17 -17
- package/dist/mobile.html +17 -17
- package/package.json +8 -3
- package/server/lib/assistants/DOCUMENTATION.md +33 -1
- package/server/lib/assistants/channels/DOCUMENTATION.md +291 -0
- package/server/lib/assistants/channels/PROTOCOLS.md +228 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.js +633 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +415 -0
- package/server/lib/assistants/channels/integration.test.js +44 -0
- package/server/lib/assistants/channels/routes.js +47 -0
- package/server/lib/assistants/channels/routes.test.js +105 -0
- package/server/lib/assistants/channels/runtime.js +867 -0
- package/server/lib/assistants/channels/runtime.test.js +723 -0
- package/server/lib/assistants/channels/sdk-adapters.js +371 -0
- package/server/lib/assistants/channels/sdk-adapters.test.js +367 -0
- package/server/lib/assistants/channels/store.js +246 -0
- package/server/lib/assistants/channels/store.test.js +286 -0
- package/server/lib/assistants/channels/transport.js +41 -0
- package/server/lib/assistants/channels/transport.test.js +23 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.js +689 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.test.js +109 -0
- package/server/lib/assistants/contracts.js +1 -0
- package/server/lib/assistants/message-channel-origin.js +7 -0
- package/server/lib/assistants/routes.js +14 -1
- package/server/lib/assistants/service.js +23 -7
- package/server/lib/assistants/service.test.js +151 -0
- package/server/lib/assistants/weixin/DOCUMENTATION.md +147 -8
- package/server/lib/assistants/weixin/api.js +2 -0
- package/server/lib/assistants/weixin/chat-adapter.js +107 -0
- package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
- package/server/lib/assistants/weixin/inbound.js +147 -0
- package/server/lib/assistants/weixin/inbound.test.js +121 -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/routes.js +4 -3
- package/server/lib/assistants/weixin/routes.test.js +30 -0
- package/server/lib/assistants/weixin/runtime.js +157 -66
- package/server/lib/assistants/weixin/runtime.test.js +372 -6
- package/server/lib/assistants/weixin/store.js +20 -3
- package/server/lib/assistants/weixin/store.test.js +72 -0
- package/server/lib/assistants/weixin/toon.js +49 -0
- package/server/lib/assistants/weixin/toon.test.js +25 -0
- package/server/lib/github/DOCUMENTATION.md +9 -8
- package/server/lib/llm/bridge-plugin.bundle.js +188 -188
- package/server/lib/opencode/DOCUMENTATION.md +2 -1
- package/server/lib/opencode/npm-registry.js +7 -21
- package/server/lib/opencode/npm-registry.test.js +36 -5
- package/server/lib/opencode/plugin-icon.d.ts +2 -0
- package/server/lib/opencode/plugin-icon.js +43 -0
- package/server/lib/opencode/plugin-icon.test.js +41 -0
- package/server/lib/opencode/plugin-routes.js +3 -1
- package/server/lib/opencode/plugin-routes.test.js +13 -0
- package/dist/assets/AssistantView-C2KQZ6a4.js +0 -3
- package/dist/assets/GuiPluginSurface-Dz2CdSUA.js +0 -1
- package/dist/assets/Icon-BP1sfnHn.js +0 -1
- package/dist/assets/MobileDetailNavigation-B3rUx5Ve.js +0 -1
- package/dist/assets/MobileTabPageHeader-0esgB2TO.js +0 -2
- package/dist/assets/TerminalView-BtM5-BVx.js +0 -8
- package/dist/assets/dropdown-menu.styles-PdxueXzN.js +0 -1
- package/dist/assets/es-BjI1GHJ5.js +0 -15
- package/dist/assets/fr-Bs7ndHkb.js +0 -13
- package/dist/assets/gitApi-BxQmH8Wg.js +0 -10
- package/dist/assets/gitApiHttp-DHrRqnYh.js +0 -7
- package/dist/assets/host-D1EpSUMR.js +0 -1
- package/dist/assets/insertionBoundaries-CKQL85zy.js +0 -1
- package/dist/assets/ja-DkdV26EW.js +0 -15
- package/dist/assets/ko-B0qoC5da.js +0 -15
- package/dist/assets/main-CNwFqQQd.js +0 -2
- package/dist/assets/main-DPhcXanT.js +0 -169
- package/dist/assets/miniChat-CF2vb25D.js +0 -2
- package/dist/assets/mobile-C24qSj44.js +0 -2
- package/dist/assets/pl-D27Y_GBs.js +0 -15
- package/dist/assets/projectMeta-CG8NLahh.js +0 -1
- package/dist/assets/pt-BR-DbocEu4b.js +0 -15
- package/dist/assets/react-CURmDhtB.js +0 -1
- package/dist/assets/readiness-DSJs_3v4.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-ChZCxxH6.js +0 -2
- package/dist/assets/renderMobileApp-CRv3Il6P.js +0 -28
- package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
- package/dist/assets/runtimeConfig-CZrflo-r.js +0 -2
- package/dist/assets/runtimeEndpointReset-Cx3RE97b.js +0 -149
- package/dist/assets/scheduledTaskNavigation-rhgnZaaj.js +0 -1
- package/dist/assets/sessionChangeSummary-CVUA1AFw.js +0 -1
- package/dist/assets/sessionLookup-C3_vQwLe.js +0 -1
- package/dist/assets/sortable-tabs-strip-C1QmKFdb.js +0 -1
- package/dist/assets/speechSettingsQueries-BSQ-2JTv.js +0 -4
- package/dist/assets/src-NKCZI3Lg.css +0 -2
- package/dist/assets/store-DvN2L3vf.js +0 -15
- package/dist/assets/useDesktopWindowControlsLayout-CwgkVw9f.js +0 -1
- package/dist/assets/useMobileNavigationStore-TCj7ZnhV.js +0 -418
- package/dist/assets/useUIStore-DI7va1HH.js +0 -1
- package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
- package/dist/assets/zh-CN-DhFFdHQu.js +0 -15
- package/dist/assets/zh-TW-BvehppXO.js +0 -15
- /package/dist/assets/{sessionChangeSummary-8C8nv-EP.css → sessionLookup-8C8nv-EP.css} +0 -0
|
@@ -2,8 +2,25 @@ import express from 'express';
|
|
|
2
2
|
import request from 'supertest';
|
|
3
3
|
import { describe, expect, it, vi } from 'vitest';
|
|
4
4
|
import { registerWeixinRoutes } from './routes.js';
|
|
5
|
+
import { createWeixinRuntime } from './runtime.js';
|
|
5
6
|
|
|
6
7
|
describe('authenticated Bot WeChat routes', () => {
|
|
8
|
+
it('reports a disabled channel and blocks direct mutation requests, not only UI buttons', async () => {
|
|
9
|
+
const app = express();
|
|
10
|
+
app.use(express.json());
|
|
11
|
+
const runtime = createWeixinRuntime({ env: { NODE_ENV: 'development' } });
|
|
12
|
+
registerWeixinRoutes(app, runtime);
|
|
13
|
+
const root = '/api/yuri/assistants/bot/weixin';
|
|
14
|
+
const response = await request(app).get(root).expect(200);
|
|
15
|
+
expect(response.body).toEqual({ status: 'disabled', error: null });
|
|
16
|
+
for (const action of ['login', 'verify', 'retry', 'transfer']) {
|
|
17
|
+
const result = await request(app).post(`${root}/${action}`).send({}).expect(403);
|
|
18
|
+
expect(result.body).toEqual({ error: 'channel_disabled' });
|
|
19
|
+
}
|
|
20
|
+
await request(app).delete(root).expect(403);
|
|
21
|
+
await runtime.close();
|
|
22
|
+
});
|
|
23
|
+
|
|
7
24
|
it('keeps the existing authentication boundary, has explicit routes and no-store QR responses', async () => {
|
|
8
25
|
const app = express();
|
|
9
26
|
app.use(express.json());
|
|
@@ -14,6 +31,7 @@ describe('authenticated Bot WeChat routes', () => {
|
|
|
14
31
|
verify: vi.fn(() => ({ status: 'verify', error: null })),
|
|
15
32
|
retry: vi.fn(() => ({ status: 'connected', error: null })),
|
|
16
33
|
disconnect: vi.fn(() => ({ status: 'disconnected', error: null })),
|
|
34
|
+
transfer: vi.fn(async () => ({ status: 'connected', error: null })),
|
|
17
35
|
};
|
|
18
36
|
registerWeixinRoutes(app, runtime);
|
|
19
37
|
const root = '/api/yuri/assistants/bot/weixin';
|
|
@@ -27,6 +45,18 @@ describe('authenticated Bot WeChat routes', () => {
|
|
|
27
45
|
expect(runtime.verify).toHaveBeenCalledWith('bot', '123456');
|
|
28
46
|
await request(app).delete(root).auth('test-owner', { type: 'bearer' }).expect(200);
|
|
29
47
|
expect(runtime.disconnect).toHaveBeenCalledWith('bot');
|
|
48
|
+
await request(app).post(`${root}/transfer`).send({ sourceAssistantID: 'old', revision: 'r1' }).expect(401);
|
|
49
|
+
expect(runtime.transfer).not.toHaveBeenCalled();
|
|
50
|
+
await request(app).post(`${root}/transfer`).auth('test-owner', { type: 'bearer' })
|
|
51
|
+
.send({ sourceAssistantID: 'old', revision: 'r1', language: 'zh-CN' }).expect('Cache-Control', 'no-store').expect(200);
|
|
52
|
+
expect(runtime.transfer).toHaveBeenCalledWith('bot', { sourceAssistantID: 'old', revision: 'r1', language: 'zh-CN' });
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('reports stale move confirmations as conflicts without leaking binding credentials', async () => {
|
|
56
|
+
const app = express();
|
|
57
|
+
registerWeixinRoutes(app, { transfer: () => { throw Object.assign(new Error('private-token'), { code: 'binding_changed' }); } });
|
|
58
|
+
const result = await request(app).post('/api/yuri/assistants/bot/weixin/transfer').expect(409);
|
|
59
|
+
expect(result.body).toEqual({ error: 'binding_changed' });
|
|
30
60
|
});
|
|
31
61
|
|
|
32
62
|
it('redacts untrusted errors and reports binding conflicts as conflicts', async () => {
|
|
@@ -3,9 +3,11 @@ import { setTimeout as delay } from 'node:timers/promises';
|
|
|
3
3
|
import { createWeixinAPI, WeixinError, weixinOrigin } from './api.js';
|
|
4
4
|
import { createWeixinStore } from './store.js';
|
|
5
5
|
import { createWeixinTyping } from './typing.js';
|
|
6
|
+
import { prepareWeixinInput } from './inbound.js';
|
|
7
|
+
import { createWeixinChatAdapter } from './chat-adapter.js';
|
|
8
|
+
import { isMessageChannelTurn } from '../message-channel-origin.js';
|
|
6
9
|
|
|
7
10
|
const digest = (value) => createHash('sha256').update(value).digest('hex');
|
|
8
|
-
const messageID = (account, peer, id) => `weixin:${digest(JSON.stringify([account, peer, id]))}`;
|
|
9
11
|
const chunks = (text) => {
|
|
10
12
|
const chars = Array.from(text);
|
|
11
13
|
const result = [];
|
|
@@ -16,28 +18,41 @@ const feedback = (language, kind) => {
|
|
|
16
18
|
const messages = language.startsWith('zh') ? {
|
|
17
19
|
interrupted: 'Yuri 主机已重启,上一条请求可能未完成。请先检查任务状态,再决定是否重试。',
|
|
18
20
|
failed: '助理未能完成这条请求,请在 Yuri 中查看具体错误后重试。',
|
|
19
|
-
|
|
21
|
+
empty: '这条微信消息没有可读取的内容,请重发文字、图片或文章链接。',
|
|
20
22
|
} : {
|
|
21
23
|
interrupted: 'The Yuri host restarted. The previous request may be incomplete. Check its status before retrying.',
|
|
22
24
|
failed: 'The bot could not complete this request. Check the error in Yuri before retrying.',
|
|
23
|
-
|
|
25
|
+
empty: 'This WeChat message has no readable content. Please resend text, an image, or an article link.',
|
|
24
26
|
};
|
|
25
27
|
return messages[kind];
|
|
26
28
|
};
|
|
27
29
|
const safeError = (error) => error instanceof WeixinError ? error.code
|
|
28
30
|
: ['account_in_use', 'not_found', 'no_provider'].includes(error?.code) ? error.code : 'channel_error';
|
|
29
31
|
|
|
30
|
-
export function createWeixinRuntime({ directory, service, refreshAllowedRoots = async () => {}, api = createWeixinAPI(), clock = Date.now, intervalMs = 2000 } = {}) {
|
|
32
|
+
export function createWeixinRuntime({ directory, service, refreshAllowedRoots = async () => {}, api = createWeixinAPI(), clock = Date.now, intervalMs = 2000, env = process.env } = {}) {
|
|
33
|
+
const configured = String(env.YURI_WEIXIN_ENABLED ?? '').trim().toLowerCase();
|
|
34
|
+
const development = env.NODE_ENV === 'development' || ['1', 'true'].includes(String(env.YURI_ELECTRON_DEV ?? '').trim().toLowerCase());
|
|
35
|
+
const enabled = configured ? ['1', 'true'].includes(configured) : !development;
|
|
36
|
+
if (!enabled) {
|
|
37
|
+
// Do not open the shared store, acquire a lease, or remove production bindings.
|
|
38
|
+
const disabled = () => { throw new WeixinError('channel_disabled'); };
|
|
39
|
+
return {
|
|
40
|
+
status: () => ({ status: 'disabled', error: null }),
|
|
41
|
+
startLogin: disabled, verify: disabled, retry: disabled, disconnect: disabled, transfer: disabled,
|
|
42
|
+
forget: async () => {}, onTurnEvent: () => {}, close: async () => {},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
31
45
|
const store = createWeixinStore(directory);
|
|
32
46
|
const owner = randomUUID();
|
|
33
47
|
const logins = new Map();
|
|
34
48
|
const receivers = new Map();
|
|
49
|
+
const bindingWork = new Map();
|
|
50
|
+
const inboundWork = new Map();
|
|
35
51
|
const operations = new Set();
|
|
36
52
|
const recovered = new Set();
|
|
37
53
|
const retiring = new Set();
|
|
38
54
|
const lifetime = new AbortController();
|
|
39
55
|
let closed = false;
|
|
40
|
-
let ticking = false;
|
|
41
56
|
let ownsLease = false;
|
|
42
57
|
let closePromise;
|
|
43
58
|
const track = (promise) => {
|
|
@@ -54,8 +69,10 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
54
69
|
const typing = createWeixinTyping({ api, clock, getBinding: store.get, isCurrent, canCancel: canControl });
|
|
55
70
|
const pause = (ms, signal) => delay(ms, undefined, { signal }).catch(() => {});
|
|
56
71
|
const stopReceiver = (assistantID) => {
|
|
57
|
-
receivers.get(assistantID)
|
|
72
|
+
const entry = receivers.get(assistantID);
|
|
73
|
+
entry?.controller.abort();
|
|
58
74
|
receivers.delete(assistantID);
|
|
75
|
+
return entry?.done;
|
|
59
76
|
};
|
|
60
77
|
const setError = (binding, error) => {
|
|
61
78
|
if (!isCurrent(binding)) return;
|
|
@@ -70,29 +87,32 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
70
87
|
|
|
71
88
|
const receive = async (initial, signal) => {
|
|
72
89
|
let failures = 0;
|
|
90
|
+
let messages = [];
|
|
91
|
+
const adapter = createWeixinChatAdapter({ api, clock, getBinding: () => isCurrent(initial) ? store.get(initial.assistant_id) : null });
|
|
92
|
+
await adapter.initialize({ processMessage: async (_adapter, _threadID, message) => { messages.push(adapter.receipt(message)); } });
|
|
73
93
|
while (!signal.aborted && isCurrent(initial)) {
|
|
74
94
|
const binding = store.get(initial.assistant_id);
|
|
75
95
|
if (!binding || binding.status === 'expired') return;
|
|
76
96
|
if (store.backlog(binding.epoch) >= 100) { await pause(2000, signal); continue; }
|
|
77
97
|
try {
|
|
78
|
-
const response = await
|
|
98
|
+
const response = await adapter.poll(signal);
|
|
79
99
|
if (signal.aborted || !isCurrent(binding)) return;
|
|
80
100
|
if (store.get(binding.assistant_id)?.status === 'expired') return;
|
|
81
101
|
const incoming = response.msgs ?? [];
|
|
82
102
|
const cursor = response.get_updates_buf ?? binding.cursor;
|
|
83
103
|
if (!Array.isArray(incoming) || incoming.length > 500 || typeof cursor !== 'string'
|
|
84
104
|
|| cursor.length > 512_000) throw new WeixinError('invalid_response');
|
|
85
|
-
|
|
105
|
+
messages = [];
|
|
86
106
|
for (const msg of incoming) {
|
|
87
107
|
if (!msg || typeof msg !== 'object') continue;
|
|
88
108
|
// The QR-confirmed owner is the only principal allowed to execute tools.
|
|
89
109
|
if (msg.message_type !== 1 || msg.from_user_id !== binding.peer_id || msg.group_id) continue;
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
messages.push({ id: messageID(binding.account_id, binding.peer_id, msg.message_id), text: text.length <= 20_000 ? text : '', context });
|
|
110
|
+
const platformID = typeof msg.message_id === 'string' && msg.message_id ? msg.message_id
|
|
111
|
+
: Array.isArray(msg.item_list) ? msg.item_list.find((item) => typeof item?.msg_id === 'string' && item.msg_id)?.msg_id : '';
|
|
112
|
+
if (!platformID || platformID.length > 256) continue;
|
|
113
|
+
await adapter.dispatch(msg);
|
|
95
114
|
}
|
|
115
|
+
if (signal.aborted || !isCurrent(binding)) return;
|
|
96
116
|
// Persist receipt and context before acknowledging the platform cursor.
|
|
97
117
|
store.accept(binding, cursor || binding.cursor, messages);
|
|
98
118
|
if (messages.some((message) => message.context)) store.unblock(binding.epoch);
|
|
@@ -112,39 +132,28 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
112
132
|
}
|
|
113
133
|
};
|
|
114
134
|
|
|
115
|
-
const
|
|
116
|
-
if (!isCurrent(binding)) return;
|
|
117
|
-
let page;
|
|
118
|
-
try { page = service.channelPage(binding.assistant_id, { afterOrdinal: binding.ordinal, generation: binding.generation }); }
|
|
119
|
-
catch (error) {
|
|
120
|
-
if (error?.code === 'not_found') { await forget(binding.assistant_id); return; }
|
|
121
|
-
throw error;
|
|
122
|
-
}
|
|
123
|
-
if (binding.status === 'expired') return;
|
|
124
|
-
const deliveries = page.messages.flatMap((message) => {
|
|
125
|
-
const text = message.status === 'error' ? feedback(binding.language, 'failed')
|
|
126
|
-
: message.text?.trim() && !message.text.trim().startsWith('oc.settle.') ? message.text.trim()
|
|
127
|
-
: message.cards.map((card) => card.title || card.name || '').filter(Boolean).join('\n');
|
|
128
|
-
return chunks(text).map((chunk, index) => ({
|
|
129
|
-
id: `yuri_${digest(`${binding.epoch}:${page.generation}:${message.messageID}:${index}`)}`, text: chunk,
|
|
130
|
-
}));
|
|
131
|
-
});
|
|
132
|
-
store.collect(binding, page, deliveries);
|
|
133
|
-
|
|
135
|
+
const processIncoming = async (binding, generation) => {
|
|
134
136
|
for (const receipt of store.pending(binding.epoch)) {
|
|
135
137
|
if (!isCurrent(binding)) return;
|
|
136
|
-
if (!receipt.text) {
|
|
137
|
-
store.enqueue(binding.epoch, `${receipt.id}:
|
|
138
|
+
if (!receipt.text && !receipt.payload) {
|
|
139
|
+
store.enqueue(binding.epoch, `${receipt.id}:empty`, feedback(binding.language, 'empty'));
|
|
138
140
|
store.finishTurn(receipt.id);
|
|
139
141
|
continue;
|
|
140
142
|
}
|
|
141
|
-
// Fence the crash gap. Never replay admitted tool side effects on restart.
|
|
142
|
-
store.markInbox(receipt.id, 'admitted');
|
|
143
143
|
try {
|
|
144
|
+
const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
|
|
145
|
+
const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
|
|
146
|
+
const assertCurrent = () => {
|
|
147
|
+
if (!isCurrent(binding) || signal.aborted || store.get(binding.assistant_id)?.status === 'expired'
|
|
148
|
+
|| service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== generation) throw new WeixinError('cancelled');
|
|
149
|
+
};
|
|
150
|
+
const parts = await prepareWeixinInput(receipt, { api, service, assistantID: binding.assistant_id, signal, assertCurrent });
|
|
144
151
|
await refreshAllowedRoots();
|
|
145
|
-
|
|
152
|
+
assertCurrent();
|
|
153
|
+
// Fence the crash gap. Never replay admitted tool side effects on restart.
|
|
154
|
+
store.markInbox(receipt.id, 'admitted');
|
|
146
155
|
const result = await service.send(binding.assistant_id, {
|
|
147
|
-
messageID: receipt.id, parts
|
|
156
|
+
messageID: receipt.id, parts, language: binding.language,
|
|
148
157
|
});
|
|
149
158
|
if (isCurrent(binding) && result.replayed) {
|
|
150
159
|
store.enqueue(binding.epoch, `${receipt.id}:interrupted`, feedback(binding.language, 'interrupted'));
|
|
@@ -156,6 +165,34 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
156
165
|
store.finishTurn(receipt.id);
|
|
157
166
|
}
|
|
158
167
|
}
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const processBinding = async (binding) => {
|
|
171
|
+
if (!isCurrent(binding)) return;
|
|
172
|
+
let page;
|
|
173
|
+
try { page = service.channelPage(binding.assistant_id, { afterOrdinal: binding.ordinal, generation: binding.generation }); }
|
|
174
|
+
catch (error) {
|
|
175
|
+
if (error?.code === 'not_found') { await forget(binding.assistant_id); return; }
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
if (binding.status === 'expired') return;
|
|
179
|
+
const deliveries = page.messages.flatMap((message) => {
|
|
180
|
+
if (isMessageChannelTurn(message.turnID) && !store.hasReceipt(message.turnID, binding.epoch)) return [];
|
|
181
|
+
const text = message.status === 'error' ? feedback(binding.language, 'failed')
|
|
182
|
+
: message.text?.trim() && !message.text.trim().startsWith('oc.settle.') ? message.text.trim()
|
|
183
|
+
: message.cards.map((card) => card.title || card.name || '').filter(Boolean).join('\n');
|
|
184
|
+
return chunks(text).map((chunk, index) => ({
|
|
185
|
+
id: `yuri_${digest(`${binding.epoch}:${page.generation}:${message.messageID}:${index}`)}`, text: chunk,
|
|
186
|
+
}));
|
|
187
|
+
});
|
|
188
|
+
store.collect(binding, page, deliveries);
|
|
189
|
+
if (!inboundWork.has(binding.assistant_id)) {
|
|
190
|
+
const work = track(processIncoming(binding, page.generation)).catch((error) => setError(binding, error));
|
|
191
|
+
inboundWork.set(binding.assistant_id, work);
|
|
192
|
+
void work.finally(() => {
|
|
193
|
+
if (inboundWork.get(binding.assistant_id) === work) inboundWork.delete(binding.assistant_id);
|
|
194
|
+
}).catch(() => {});
|
|
195
|
+
}
|
|
159
196
|
const current = store.get(binding.assistant_id);
|
|
160
197
|
if (!isCurrent(binding) || current.status === 'expired' || !current.context_token) return;
|
|
161
198
|
const delivery = store.nextDelivery(binding.epoch);
|
|
@@ -163,12 +200,24 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
163
200
|
store.markDelivery(delivery.id, 'sending');
|
|
164
201
|
try {
|
|
165
202
|
const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
|
|
166
|
-
|
|
167
|
-
|
|
203
|
+
const adapter = createWeixinChatAdapter({ api, clock, getBinding: () => isCurrent(binding) ? store.get(binding.assistant_id) : null });
|
|
204
|
+
const threadID = await adapter.openDM(current.peer_id);
|
|
205
|
+
await adapter.postMessage(threadID, delivery.text, { id: delivery.id,
|
|
206
|
+
signal: receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal });
|
|
207
|
+
if (!isCurrent(binding) && !(retiring.has(binding.assistant_id) && canControl(binding))) return;
|
|
168
208
|
store.sent(delivery.id);
|
|
169
209
|
store.patch(binding.epoch, { error: null, updated_at: clock() });
|
|
170
210
|
} catch (error) {
|
|
171
|
-
if (!isCurrent(binding))
|
|
211
|
+
if (!isCurrent(binding)) {
|
|
212
|
+
if (retiring.has(binding.assistant_id) && canControl(binding)) {
|
|
213
|
+
// A failed move may resume this binding. Never strand an aborted send
|
|
214
|
+
// in 'sending', or automatically replay a request already on the wire.
|
|
215
|
+
store.markDelivery(delivery.id, 'unknown');
|
|
216
|
+
store.patch(binding.epoch, error?.code === 'auth_expired'
|
|
217
|
+
? { status: 'expired', error: 'auth_expired' } : { error: 'delivery_unknown' });
|
|
218
|
+
}
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
172
221
|
// Network ambiguity is user-retryable, not an automatic duplicate reply.
|
|
173
222
|
store.markDelivery(delivery.id, error?.ambiguous ? 'unknown' : 'blocked');
|
|
174
223
|
setError(binding, error?.ambiguous ? new WeixinError('delivery_unknown') : error);
|
|
@@ -185,38 +234,47 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
185
234
|
void track(typing.clear());
|
|
186
235
|
return;
|
|
187
236
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
store.recover(binding.epoch, feedback(binding.language, 'interrupted'));
|
|
197
|
-
if (store.hasUnknown(binding.epoch)) store.patch(binding.epoch, { error: 'delivery_unknown' });
|
|
198
|
-
recovered.add(binding.epoch);
|
|
199
|
-
}
|
|
200
|
-
if (binding.status !== 'expired' && !retiring.has(binding.assistant_id) && !receivers.has(binding.assistant_id)) {
|
|
201
|
-
const controller = new AbortController();
|
|
202
|
-
const entry = { controller };
|
|
203
|
-
receivers.set(binding.assistant_id, entry);
|
|
204
|
-
track(receive(binding, controller.signal)).finally(() => {
|
|
205
|
-
if (receivers.get(binding.assistant_id) === entry) receivers.delete(binding.assistant_id);
|
|
206
|
-
}).catch(() => {});
|
|
207
|
-
}
|
|
237
|
+
const bindings = store.list();
|
|
238
|
+
const ids = new Set(bindings.map((binding) => binding.assistant_id));
|
|
239
|
+
for (const id of receivers.keys()) if (!ids.has(id)) stopReceiver(id);
|
|
240
|
+
for (const binding of bindings) {
|
|
241
|
+
if (!recovered.has(binding.epoch)) {
|
|
242
|
+
store.recover(binding.epoch, feedback(binding.language, 'interrupted'));
|
|
243
|
+
if (store.hasUnknown(binding.epoch)) store.patch(binding.epoch, { error: 'delivery_unknown' });
|
|
244
|
+
recovered.add(binding.epoch);
|
|
208
245
|
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
246
|
+
if (binding.status !== 'expired' && !retiring.has(binding.assistant_id) && !receivers.has(binding.assistant_id)) {
|
|
247
|
+
const controller = new AbortController();
|
|
248
|
+
const entry = { controller };
|
|
249
|
+
receivers.set(binding.assistant_id, entry);
|
|
250
|
+
entry.done = track(receive(binding, controller.signal)).finally(() => {
|
|
251
|
+
if (receivers.get(binding.assistant_id) === entry) receivers.delete(binding.assistant_id);
|
|
252
|
+
}).catch(() => {});
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
// One slow Bot cannot prevent another account receiving or replying.
|
|
256
|
+
await Promise.allSettled(bindings.map((binding) => {
|
|
257
|
+
if (bindingWork.has(binding.assistant_id) || retiring.has(binding.assistant_id)) return;
|
|
258
|
+
const work = processBinding(binding).catch((error) => setError(binding, error));
|
|
259
|
+
bindingWork.set(binding.assistant_id, work);
|
|
260
|
+
return work.finally(() => {
|
|
261
|
+
if (bindingWork.get(binding.assistant_id) === work) bindingWork.delete(binding.assistant_id);
|
|
262
|
+
});
|
|
263
|
+
}));
|
|
212
264
|
};
|
|
213
265
|
|
|
214
266
|
const status = (assistantID) => {
|
|
215
267
|
service.channelPage(assistantID, { tipOnly: true });
|
|
216
268
|
const login = logins.get(assistantID);
|
|
217
|
-
if (login) return { status: login.status, qrCode: login.qrCode, expiresAt: login.expiresAt, error: login.error ?? null };
|
|
218
269
|
const binding = store.get(assistantID);
|
|
219
|
-
|
|
270
|
+
const sources = !binding ? store.list().filter((row) => row.assistant_id !== assistantID && row.status !== 'expired') : [];
|
|
271
|
+
const names = sources.length ? new Map(service.snapshot().assistants.map((row) => [row.id, row.name])) : new Map();
|
|
272
|
+
const transferSources = sources.filter((row) => names.has(row.assistant_id)).map((row) => ({
|
|
273
|
+
assistantID: row.assistant_id, name: names.get(row.assistant_id), revision: row.epoch,
|
|
274
|
+
}));
|
|
275
|
+
const available = transferSources.length ? { transferSources } : {};
|
|
276
|
+
if (login) return { status: login.status, qrCode: login.qrCode, expiresAt: login.expiresAt, error: login.error ?? null, ...available };
|
|
277
|
+
if (!binding) return { status: 'disconnected', error: null, ...available };
|
|
220
278
|
return {
|
|
221
279
|
status: ownsLease ? binding.status : 'reconnecting',
|
|
222
280
|
error: ownsLease ? (store.hasUnknown(binding.epoch) ? 'delivery_unknown' : binding.error) : 'channel_in_use',
|
|
@@ -301,6 +359,7 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
301
359
|
}
|
|
302
360
|
};
|
|
303
361
|
const forget = async (assistantID) => {
|
|
362
|
+
if (retiring.has(assistantID)) throw new WeixinError('channel_in_use');
|
|
304
363
|
retiring.add(assistantID);
|
|
305
364
|
logins.get(assistantID)?.controller.abort();
|
|
306
365
|
logins.delete(assistantID);
|
|
@@ -316,11 +375,42 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
316
375
|
await forget(assistantID);
|
|
317
376
|
return status(assistantID);
|
|
318
377
|
};
|
|
378
|
+
const transfer = async (assistantID, input) => {
|
|
379
|
+
assertOwner();
|
|
380
|
+
const { sourceAssistantID, revision, language = 'en' } = input ?? {};
|
|
381
|
+
if (typeof sourceAssistantID !== 'string' || typeof revision !== 'string' || sourceAssistantID === assistantID) {
|
|
382
|
+
throw new WeixinError('validation_error');
|
|
383
|
+
}
|
|
384
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
385
|
+
service.channelPage(sourceAssistantID, { tipOnly: true });
|
|
386
|
+
if (retiring.has(assistantID) || retiring.has(sourceAssistantID)) throw new WeixinError('channel_in_use');
|
|
387
|
+
const source = store.get(sourceAssistantID);
|
|
388
|
+
if (!source || source.epoch !== revision || source.status === 'expired' || store.get(assistantID)) throw new WeixinError('binding_changed');
|
|
389
|
+
retiring.add(sourceAssistantID);
|
|
390
|
+
retiring.add(assistantID);
|
|
391
|
+
logins.get(assistantID)?.controller.abort();
|
|
392
|
+
logins.delete(assistantID);
|
|
393
|
+
try {
|
|
394
|
+
await Promise.allSettled([stopReceiver(sourceAssistantID), bindingWork.get(sourceAssistantID), inboundWork.get(sourceAssistantID), typing.forget(sourceAssistantID)]);
|
|
395
|
+
assertOwner();
|
|
396
|
+
// Revalidate after draining: deletion or a stale confirmation must not move credentials.
|
|
397
|
+
service.channelPage(sourceAssistantID, { tipOnly: true });
|
|
398
|
+
const page = service.channelPage(assistantID, { tipOnly: true });
|
|
399
|
+
store.transfer({ sourceAssistantID, expectedEpoch: revision, assistantID,
|
|
400
|
+
generation: page.generation, ordinal: page.tipOrdinal, language: String(language).slice(0, 32), updatedAt: clock() });
|
|
401
|
+
} finally {
|
|
402
|
+
retiring.delete(sourceAssistantID);
|
|
403
|
+
retiring.delete(assistantID);
|
|
404
|
+
if (!closed) void track(tick());
|
|
405
|
+
}
|
|
406
|
+
return status(assistantID);
|
|
407
|
+
};
|
|
319
408
|
const timer = setInterval(() => { void track(tick()); }, intervalMs);
|
|
320
409
|
timer.unref?.();
|
|
321
410
|
void track(tick());
|
|
322
411
|
return {
|
|
323
412
|
status, startLogin, disconnect, forget,
|
|
413
|
+
transfer: (assistantID, input) => track(transfer(assistantID, input)),
|
|
324
414
|
verify: (assistantID, code) => {
|
|
325
415
|
assertOwner();
|
|
326
416
|
const login = logins.get(assistantID);
|
|
@@ -330,6 +420,7 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
330
420
|
},
|
|
331
421
|
retry: (assistantID) => {
|
|
332
422
|
assertOwner();
|
|
423
|
+
if (retiring.has(assistantID)) throw new WeixinError('channel_in_use');
|
|
333
424
|
const binding = store.get(assistantID);
|
|
334
425
|
if (!binding) throw new WeixinError('not_found');
|
|
335
426
|
if (binding.status === 'expired') throw new WeixinError('auth_expired');
|