@yuriai/web 0.2.27-beta.2 → 0.2.27-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AgentAvatar-BW4Zg8bo.js → AgentAvatar-kIN4sZMz.js} +1 -1
- package/dist/assets/{AssistantView-Cl0ZeXwr.js → AssistantView-C2KQZ6a4.js} +3 -3
- package/dist/assets/{DiagramView-D6wdXRzu.js → DiagramView-DK0iXm9b.js} +1 -1
- package/dist/assets/{FadeInOnReveal-gOsILpSk.js → FadeInOnReveal-BJA9Za3T.js} +1 -1
- package/dist/assets/{GuiPluginSurface-DOZAQKX0.js → GuiPluginSurface-Dz2CdSUA.js} +1 -1
- package/dist/assets/{GuiPluginWindow-tGvc4_0g.js → GuiPluginWindow-l4FYY6S-.js} +1 -1
- package/dist/assets/{Icon-DvUDsV1z.js → Icon-BP1sfnHn.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-9xYbKqtf.js → ImageLoadingPlaceholder-DCWssLJG.js} +1 -1
- package/dist/assets/{LoadingImage-CiOcKPfb.js → LoadingImage-C_Hryaqe.js} +1 -1
- package/dist/assets/{MarkdownRenderer-DZkP4UNr.js → MarkdownRenderer-Y6uQXIFH.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-BXzPUEEo.js → MarkdownRendererImpl-qKp1tQrP.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-B-NWd069.js → MarkstreamRendererImpl-B_JTod0h.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-5U28hfYf.js → MobileDetailNavigation-B3rUx5Ve.js} +1 -1
- package/dist/assets/{MobileResizableSheet-ZL-zPa3W.js → MobileResizableSheet-F1zSUD1S.js} +1 -1
- package/dist/assets/{MobileShareBridge-JSH_Y8Ps.js → MobileShareBridge-F70fkIfS.js} +1 -1
- package/dist/assets/{MobileTabPageHeader-Bj9MIS38.js → MobileTabPageHeader-0esgB2TO.js} +1 -1
- package/dist/assets/{MultiRunWindow-ZPz62Aqg.js → MultiRunWindow-D8m6R_4x.js} +1 -1
- package/dist/assets/{OnboardingScreen-BQNoy9o1.js → OnboardingScreen-BAsPVV_W.js} +1 -1
- package/dist/assets/{OverlayScrollbar-BwCFalSw.js → OverlayScrollbar-wiRM4AGj.js} +1 -1
- package/dist/assets/{SettingsView-B17qt8dh.js → SettingsView-izzjIckv.js} +15 -15
- package/dist/assets/{SettingsWindow-CIFNHb-F.js → SettingsWindow-CSuHDq_c.js} +1 -1
- package/dist/assets/{TerminalView-BZZ8LW4d.js → TerminalView-BtM5-BVx.js} +1 -1
- package/dist/assets/{ToolOutputDialog-BKuVpgEu.js → ToolOutputDialog-DJs9w1_J.js} +1 -1
- package/dist/assets/{YuriLogo-C1Ty-RTB.js → YuriLogo-aBS6wlYU.js} +1 -1
- package/dist/assets/{appThemeRegistry-DqGuzMaH.js → appThemeRegistry-BY5rY9-W.js} +1 -1
- package/dist/assets/{button-DuHjvKJJ.js → button-Dt6Ygbc7.js} +1 -1
- package/dist/assets/{capgoAdapter-B-tddboe.js → capgoAdapter-MQ1qpf60.js} +1 -1
- package/dist/assets/{collapsible-B8eL5nLo.js → collapsible-Dm7OHk7m.js} +1 -1
- package/dist/assets/{diagram-ChoQDKzy.js → diagram-DWZaG3_v.js} +1 -1
- package/dist/assets/{dialog-CVhqZux0.js → dialog-CjQeHVOc.js} +1 -1
- package/dist/assets/{dropdown-menu.styles-DGvlOX_5.js → dropdown-menu.styles-PdxueXzN.js} +1 -1
- package/dist/assets/{es-B8sAsuo5.js → es-BjI1GHJ5.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-Dd-iSIe2.js → fileMentionTouchSelection-D7QtVxjI.js} +1 -1
- package/dist/assets/{fr-BPpW8T-l.js → fr-Bs7ndHkb.js} +1 -1
- package/dist/assets/{gitApi-D43bAQh1.js → gitApi-BxQmH8Wg.js} +1 -1
- package/dist/assets/{input-E_oYiXZT.js → input-Dq4usRDa.js} +1 -1
- package/dist/assets/{insertionBoundaries-BQjiZAmZ.js → insertionBoundaries-CKQL85zy.js} +1 -1
- package/dist/assets/{ja-DEoFDi7P.js → ja-DkdV26EW.js} +1 -1
- package/dist/assets/{ko-B45xHN6I.js → ko-B0qoC5da.js} +1 -1
- package/dist/assets/{main-C6MDfyZy.js → main-CNwFqQQd.js} +2 -2
- package/dist/assets/{main-u5iQScJs.js → main-DPhcXanT.js} +4 -4
- package/dist/assets/{markdownHeightCache-heNXHdzb.js → markdownHeightCache-C1u0bWDL.js} +1 -1
- package/dist/assets/{mcpQueries-BqKVe4Su.js → mcpQueries-D2IxTr4k.js} +1 -1
- package/dist/assets/{miniChat-Dhfn71Re.js → miniChat-CF2vb25D.js} +2 -2
- package/dist/assets/{mobile-DSVdPfcG.js → mobile-C24qSj44.js} +2 -2
- package/dist/assets/{mobileBackNavigation-DHxFQ7SY.js → mobileBackNavigation-vpCg1S7j.js} +1 -1
- package/dist/assets/{multirun-CPOzaEQj.js → multirun-DT-dFXud.js} +1 -1
- package/dist/assets/{native-config-oauL2ekt.js → native-config-ncdoz9Wl.js} +1 -1
- package/dist/assets/{pl-Bm3Je_AX.js → pl-D27Y_GBs.js} +1 -1
- package/dist/assets/{projectMeta-YDMdD3AP.js → projectMeta-CG8NLahh.js} +1 -1
- package/dist/assets/{pt-BR-BiQwFHhL.js → pt-BR-DbocEu4b.js} +1 -1
- package/dist/assets/{readiness-BveVUOIb.js → readiness-DSJs_3v4.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-NC8iRPyy.js → renderElectronMiniChatApp-ChZCxxH6.js} +2 -2
- package/dist/assets/{renderMobileApp-D5ai1i6y.js → renderMobileApp-CRv3Il6P.js} +4 -4
- package/dist/assets/{runtimeConfig-BpcgdIV9.js → runtimeConfig-CZrflo-r.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-ByKa_0nu.js → runtimeEndpointReset-Cx3RE97b.js} +3 -3
- package/dist/assets/{scheduledTaskNavigation-CZfAnPD-.js → scheduledTaskNavigation-rhgnZaaj.js} +1 -1
- package/dist/assets/{sessionChangeSummary-D6NlE_5k.js → sessionChangeSummary-CVUA1AFw.js} +1 -1
- package/dist/assets/{sessionLookup-C70EoX-V.js → sessionLookup-C3_vQwLe.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-aKussO2c.js → sortable-tabs-strip-C1QmKFdb.js} +1 -1
- package/dist/assets/{speechSettingsQueries-B6qf-mCh.js → speechSettingsQueries-BSQ-2JTv.js} +1 -1
- package/dist/assets/{store-BeD2keas.js → store-DvN2L3vf.js} +2 -2
- package/dist/assets/{textarea-DmKaqHSb.js → textarea-vtIQM2iP.js} +1 -1
- package/dist/assets/{tooltip-DUKu4nC6.js → tooltip-BpG2mxrT.js} +1 -1
- package/dist/assets/{types-DRTMRW4R.js → types-CNTgeeM1.js} +1 -1
- package/dist/assets/{uk-CYZXWdd7.js → uk-B_JwElWz.js} +1 -1
- package/dist/assets/{useAppFontEffects-BiQf6tgZ.js → useAppFontEffects-BguV1Hfa.js} +5 -5
- package/dist/assets/{useDesktopWindowControlsLayout-DJxNmCWb.js → useDesktopWindowControlsLayout-CwgkVw9f.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-B8q00InF.js → useEffectiveDirectory-Ci6Z13kj.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-Bn4SaalY.js → useMobileNavigationStore-TCj7ZnhV.js} +6 -6
- package/dist/assets/{useWorkerHighlightedLines-B6lWNk01.js → useWorkerHighlightedLines-HKhuYGSj.js} +1 -1
- package/dist/assets/{zh-CN-CMLBHipA.js → zh-CN-DhFFdHQu.js} +1 -1
- package/dist/assets/{zh-TW-CJlmnnhK.js → zh-TW-BvehppXO.js} +1 -1
- package/dist/index.html +5 -5
- package/dist/mini-chat.html +5 -5
- package/dist/mobile.html +5 -5
- package/package.json +1 -1
- package/server/lib/assistants/DOCUMENTATION.md +10 -0
- package/server/lib/assistants/contact-store.js +16 -0
- package/server/lib/assistants/contact-store.test.js +19 -0
- package/server/lib/assistants/routes.js +25 -3
- package/server/lib/assistants/service.js +7 -1
- package/server/lib/assistants/weixin/DOCUMENTATION.md +142 -0
- package/server/lib/assistants/weixin/api.js +113 -0
- package/server/lib/assistants/weixin/api.test.js +80 -0
- package/server/lib/assistants/weixin/routes.js +23 -0
- package/server/lib/assistants/weixin/routes.test.js +41 -0
- package/server/lib/assistants/weixin/runtime.js +357 -0
- package/server/lib/assistants/weixin/runtime.test.js +286 -0
- package/server/lib/assistants/weixin/store.js +103 -0
- package/server/lib/assistants/weixin/typing.js +88 -0
- package/server/lib/assistants/weixin/typing.test.js +185 -0
- package/server/lib/opencode/shutdown-runtime.js +1 -1
- package/server/lib/opencode/shutdown-runtime.test.js +12 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
import request from 'supertest';
|
|
3
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
4
|
+
import { registerWeixinRoutes } from './routes.js';
|
|
5
|
+
|
|
6
|
+
describe('authenticated Bot WeChat routes', () => {
|
|
7
|
+
it('keeps the existing authentication boundary, has explicit routes and no-store QR responses', async () => {
|
|
8
|
+
const app = express();
|
|
9
|
+
app.use(express.json());
|
|
10
|
+
app.use('/api/yuri', (req, res, next) => req.headers.authorization === 'Bearer test-owner' ? next() : res.sendStatus(401));
|
|
11
|
+
const runtime = {
|
|
12
|
+
status: vi.fn(() => ({ status: 'disconnected', error: null })),
|
|
13
|
+
startLogin: vi.fn(async () => ({ status: 'waiting', qrCode: 'https://example.com/scan', error: null })),
|
|
14
|
+
verify: vi.fn(() => ({ status: 'verify', error: null })),
|
|
15
|
+
retry: vi.fn(() => ({ status: 'connected', error: null })),
|
|
16
|
+
disconnect: vi.fn(() => ({ status: 'disconnected', error: null })),
|
|
17
|
+
};
|
|
18
|
+
registerWeixinRoutes(app, runtime);
|
|
19
|
+
const root = '/api/yuri/assistants/bot/weixin';
|
|
20
|
+
await request(app).post(`${root}/login`).send({}).expect(401);
|
|
21
|
+
expect(runtime.startLogin).not.toHaveBeenCalled();
|
|
22
|
+
const response = await request(app).post(`${root}/login`).auth('test-owner', { type: 'bearer' }).send({ language: 'zh-CN' }).expect(200);
|
|
23
|
+
expect(response.headers['cache-control']).toBe('no-store');
|
|
24
|
+
expect(response.body).toMatchObject({ status: 'waiting' });
|
|
25
|
+
expect(runtime.startLogin).toHaveBeenCalledWith('bot', 'zh-CN');
|
|
26
|
+
await request(app).post(`${root}/verify`).auth('test-owner', { type: 'bearer' }).send({ code: '123456' }).expect(200);
|
|
27
|
+
expect(runtime.verify).toHaveBeenCalledWith('bot', '123456');
|
|
28
|
+
await request(app).delete(root).auth('test-owner', { type: 'bearer' }).expect(200);
|
|
29
|
+
expect(runtime.disconnect).toHaveBeenCalledWith('bot');
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('redacts untrusted errors and reports binding conflicts as conflicts', async () => {
|
|
33
|
+
const app = express();
|
|
34
|
+
registerWeixinRoutes(app, { status: () => { throw new Error('credential=private-token'); },
|
|
35
|
+
startLogin: () => { throw Object.assign(new Error('private upstream response'), { code: 'account_in_use' }); } });
|
|
36
|
+
const response = await request(app).get('/api/yuri/assistants/bot/weixin').expect(400);
|
|
37
|
+
expect(response.body).toEqual({ error: 'channel_error' });
|
|
38
|
+
const conflict = await request(app).post('/api/yuri/assistants/bot/weixin/login').expect(409);
|
|
39
|
+
expect(conflict.body).toEqual({ error: 'account_in_use' });
|
|
40
|
+
});
|
|
41
|
+
});
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { createWeixinAPI, WeixinError, weixinOrigin } from './api.js';
|
|
4
|
+
import { createWeixinStore } from './store.js';
|
|
5
|
+
import { createWeixinTyping } from './typing.js';
|
|
6
|
+
|
|
7
|
+
const digest = (value) => createHash('sha256').update(value).digest('hex');
|
|
8
|
+
const messageID = (account, peer, id) => `weixin:${digest(JSON.stringify([account, peer, id]))}`;
|
|
9
|
+
const chunks = (text) => {
|
|
10
|
+
const chars = Array.from(text);
|
|
11
|
+
const result = [];
|
|
12
|
+
for (let index = 0; index < chars.length; index += 3500) result.push(chars.slice(index, index + 3500).join(''));
|
|
13
|
+
return result;
|
|
14
|
+
};
|
|
15
|
+
const feedback = (language, kind) => {
|
|
16
|
+
const messages = language.startsWith('zh') ? {
|
|
17
|
+
interrupted: 'Yuri 主机已重启,上一条请求可能未完成。请先检查任务状态,再决定是否重试。',
|
|
18
|
+
failed: '助理未能完成这条请求,请在 Yuri 中查看具体错误后重试。',
|
|
19
|
+
textOnly: '当前微信通道仅支持文字,请发送文字消息。',
|
|
20
|
+
} : {
|
|
21
|
+
interrupted: 'The Yuri host restarted. The previous request may be incomplete. Check its status before retrying.',
|
|
22
|
+
failed: 'The bot could not complete this request. Check the error in Yuri before retrying.',
|
|
23
|
+
textOnly: 'This WeChat connection currently accepts text messages only. Please send a text message.',
|
|
24
|
+
};
|
|
25
|
+
return messages[kind];
|
|
26
|
+
};
|
|
27
|
+
const safeError = (error) => error instanceof WeixinError ? error.code
|
|
28
|
+
: ['account_in_use', 'not_found', 'no_provider'].includes(error?.code) ? error.code : 'channel_error';
|
|
29
|
+
|
|
30
|
+
export function createWeixinRuntime({ directory, service, refreshAllowedRoots = async () => {}, api = createWeixinAPI(), clock = Date.now, intervalMs = 2000 } = {}) {
|
|
31
|
+
const store = createWeixinStore(directory);
|
|
32
|
+
const owner = randomUUID();
|
|
33
|
+
const logins = new Map();
|
|
34
|
+
const receivers = new Map();
|
|
35
|
+
const operations = new Set();
|
|
36
|
+
const recovered = new Set();
|
|
37
|
+
const retiring = new Set();
|
|
38
|
+
const lifetime = new AbortController();
|
|
39
|
+
let closed = false;
|
|
40
|
+
let ticking = false;
|
|
41
|
+
let ownsLease = false;
|
|
42
|
+
let closePromise;
|
|
43
|
+
const track = (promise) => {
|
|
44
|
+
operations.add(promise);
|
|
45
|
+
void promise.finally(() => operations.delete(promise)).catch(() => {});
|
|
46
|
+
return promise;
|
|
47
|
+
};
|
|
48
|
+
const assertOwner = () => {
|
|
49
|
+
if (closed || !ownsLease || !store.owns(owner, clock())) throw new WeixinError('channel_in_use');
|
|
50
|
+
};
|
|
51
|
+
const canControl = (binding) => ownsLease && store.owns(owner, clock())
|
|
52
|
+
&& store.get(binding.assistant_id)?.epoch === binding.epoch;
|
|
53
|
+
const isCurrent = (binding) => !closed && !retiring.has(binding.assistant_id) && canControl(binding);
|
|
54
|
+
const typing = createWeixinTyping({ api, clock, getBinding: store.get, isCurrent, canCancel: canControl });
|
|
55
|
+
const pause = (ms, signal) => delay(ms, undefined, { signal }).catch(() => {});
|
|
56
|
+
const stopReceiver = (assistantID) => {
|
|
57
|
+
receivers.get(assistantID)?.controller.abort();
|
|
58
|
+
receivers.delete(assistantID);
|
|
59
|
+
};
|
|
60
|
+
const setError = (binding, error) => {
|
|
61
|
+
if (!isCurrent(binding)) return;
|
|
62
|
+
if (store.get(binding.assistant_id)?.status === 'expired') return;
|
|
63
|
+
const code = safeError(error);
|
|
64
|
+
store.patch(binding.epoch, {
|
|
65
|
+
status: code === 'auth_expired' ? 'expired' : code === 'network_error' ? 'reconnecting' : 'connected',
|
|
66
|
+
error: code, updated_at: clock(),
|
|
67
|
+
});
|
|
68
|
+
if (code === 'auth_expired') void track(typing.forget(binding.assistant_id));
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const receive = async (initial, signal) => {
|
|
72
|
+
let failures = 0;
|
|
73
|
+
while (!signal.aborted && isCurrent(initial)) {
|
|
74
|
+
const binding = store.get(initial.assistant_id);
|
|
75
|
+
if (!binding || binding.status === 'expired') return;
|
|
76
|
+
if (store.backlog(binding.epoch) >= 100) { await pause(2000, signal); continue; }
|
|
77
|
+
try {
|
|
78
|
+
const response = await api.getUpdates(binding, signal);
|
|
79
|
+
if (signal.aborted || !isCurrent(binding)) return;
|
|
80
|
+
if (store.get(binding.assistant_id)?.status === 'expired') return;
|
|
81
|
+
const incoming = response.msgs ?? [];
|
|
82
|
+
const cursor = response.get_updates_buf ?? binding.cursor;
|
|
83
|
+
if (!Array.isArray(incoming) || incoming.length > 500 || typeof cursor !== 'string'
|
|
84
|
+
|| cursor.length > 512_000) throw new WeixinError('invalid_response');
|
|
85
|
+
const messages = [];
|
|
86
|
+
for (const msg of incoming) {
|
|
87
|
+
if (!msg || typeof msg !== 'object') continue;
|
|
88
|
+
// The QR-confirmed owner is the only principal allowed to execute tools.
|
|
89
|
+
if (msg.message_type !== 1 || msg.from_user_id !== binding.peer_id || msg.group_id) continue;
|
|
90
|
+
if (typeof msg.message_id !== 'string' || !msg.message_id || msg.message_id.length > 256) continue;
|
|
91
|
+
const text = Array.isArray(msg.item_list) ? msg.item_list.filter((item) => item?.type === 1)
|
|
92
|
+
.map((item) => typeof item.text_item?.text === 'string' ? item.text_item.text : '').join('\n').trim() : '';
|
|
93
|
+
const context = typeof msg.context_token === 'string' && msg.context_token.length <= 65_536 ? msg.context_token : '';
|
|
94
|
+
messages.push({ id: messageID(binding.account_id, binding.peer_id, msg.message_id), text: text.length <= 20_000 ? text : '', context });
|
|
95
|
+
}
|
|
96
|
+
// Persist receipt and context before acknowledging the platform cursor.
|
|
97
|
+
store.accept(binding, cursor || binding.cursor, messages);
|
|
98
|
+
if (messages.some((message) => message.context)) store.unblock(binding.epoch);
|
|
99
|
+
const lastError = store.get(binding.assistant_id)?.error;
|
|
100
|
+
store.patch(binding.epoch, {
|
|
101
|
+
status: 'connected', error: store.hasUnknown(binding.epoch) ? 'delivery_unknown'
|
|
102
|
+
: lastError === 'network_error' ? null : lastError, updated_at: clock(),
|
|
103
|
+
});
|
|
104
|
+
failures = 0;
|
|
105
|
+
if (!incoming.length) await pause(250, signal);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (signal.aborted || !isCurrent(binding)) return;
|
|
108
|
+
setError(binding, error);
|
|
109
|
+
if (safeError(error) === 'auth_expired') return;
|
|
110
|
+
await pause(Math.min(30_000, 1000 * 2 ** Math.min(failures++, 5)), signal);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const processBinding = async (binding) => {
|
|
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
|
+
|
|
134
|
+
for (const receipt of store.pending(binding.epoch)) {
|
|
135
|
+
if (!isCurrent(binding)) return;
|
|
136
|
+
if (!receipt.text) {
|
|
137
|
+
store.enqueue(binding.epoch, `${receipt.id}:text-only`, feedback(binding.language, 'textOnly'));
|
|
138
|
+
store.finishTurn(receipt.id);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
// Fence the crash gap. Never replay admitted tool side effects on restart.
|
|
142
|
+
store.markInbox(receipt.id, 'admitted');
|
|
143
|
+
try {
|
|
144
|
+
await refreshAllowedRoots();
|
|
145
|
+
if (!isCurrent(binding)) return;
|
|
146
|
+
const result = await service.send(binding.assistant_id, {
|
|
147
|
+
messageID: receipt.id, parts: [{ type: 'text', text: receipt.text }], language: binding.language,
|
|
148
|
+
});
|
|
149
|
+
if (isCurrent(binding) && result.replayed) {
|
|
150
|
+
store.enqueue(binding.epoch, `${receipt.id}:interrupted`, feedback(binding.language, 'interrupted'));
|
|
151
|
+
store.finishTurn(receipt.id);
|
|
152
|
+
}
|
|
153
|
+
} catch {
|
|
154
|
+
if (!isCurrent(binding)) return;
|
|
155
|
+
store.enqueue(binding.epoch, `${receipt.id}:failed`, feedback(binding.language, 'failed'));
|
|
156
|
+
store.finishTurn(receipt.id);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const current = store.get(binding.assistant_id);
|
|
160
|
+
if (!isCurrent(binding) || current.status === 'expired' || !current.context_token) return;
|
|
161
|
+
const delivery = store.nextDelivery(binding.epoch);
|
|
162
|
+
if (!delivery || delivery.state !== 'pending') return;
|
|
163
|
+
store.markDelivery(delivery.id, 'sending');
|
|
164
|
+
try {
|
|
165
|
+
const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
|
|
166
|
+
await api.sendText(current, delivery, receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal);
|
|
167
|
+
if (!isCurrent(binding)) return;
|
|
168
|
+
store.sent(delivery.id);
|
|
169
|
+
store.patch(binding.epoch, { error: null, updated_at: clock() });
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (!isCurrent(binding)) return;
|
|
172
|
+
// Network ambiguity is user-retryable, not an automatic duplicate reply.
|
|
173
|
+
store.markDelivery(delivery.id, error?.ambiguous ? 'unknown' : 'blocked');
|
|
174
|
+
setError(binding, error?.ambiguous ? new WeixinError('delivery_unknown') : error);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const tick = async () => {
|
|
179
|
+
if (closed) return;
|
|
180
|
+
ownsLease = store.acquire(owner, clock());
|
|
181
|
+
if (!ownsLease) {
|
|
182
|
+
for (const id of receivers.keys()) stopReceiver(id);
|
|
183
|
+
for (const login of logins.values()) login.controller.abort();
|
|
184
|
+
logins.clear();
|
|
185
|
+
void track(typing.clear());
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (ticking) return;
|
|
189
|
+
ticking = true;
|
|
190
|
+
try {
|
|
191
|
+
const bindings = store.list();
|
|
192
|
+
const ids = new Set(bindings.map((binding) => binding.assistant_id));
|
|
193
|
+
for (const id of receivers.keys()) if (!ids.has(id)) stopReceiver(id);
|
|
194
|
+
for (const binding of bindings) {
|
|
195
|
+
if (!recovered.has(binding.epoch)) {
|
|
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
|
+
}
|
|
208
|
+
}
|
|
209
|
+
// One slow Bot cannot prevent another account receiving or replying.
|
|
210
|
+
await Promise.allSettled(bindings.map((binding) => processBinding(binding).catch((error) => setError(binding, error))));
|
|
211
|
+
} finally { ticking = false; }
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const status = (assistantID) => {
|
|
215
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
216
|
+
const login = logins.get(assistantID);
|
|
217
|
+
if (login) return { status: login.status, qrCode: login.qrCode, expiresAt: login.expiresAt, error: login.error ?? null };
|
|
218
|
+
const binding = store.get(assistantID);
|
|
219
|
+
if (!binding) return { status: 'disconnected', error: null };
|
|
220
|
+
return {
|
|
221
|
+
status: ownsLease ? binding.status : 'reconnecting',
|
|
222
|
+
error: ownsLease ? (store.hasUnknown(binding.epoch) ? 'delivery_unknown' : binding.error) : 'channel_in_use',
|
|
223
|
+
};
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
const pollLogin = async (assistantID, login) => {
|
|
227
|
+
let origin = weixinOrigin();
|
|
228
|
+
let redirects = 0;
|
|
229
|
+
while (!login.controller.signal.aborted && clock() < login.expiresAt && logins.get(assistantID) === login) {
|
|
230
|
+
try {
|
|
231
|
+
const verifyCode = login.verifyCode;
|
|
232
|
+
const response = await api.getQRStatus(origin, login.qrcode, verifyCode, login.controller.signal);
|
|
233
|
+
if (login.verifyCode === verifyCode) login.verifyCode = '';
|
|
234
|
+
assertOwner();
|
|
235
|
+
if (logins.get(assistantID) !== login || login.controller.signal.aborted) return;
|
|
236
|
+
if (response.status === 'confirmed') {
|
|
237
|
+
const { bot_token: token, ilink_bot_id: account, ilink_user_id: peer } = response;
|
|
238
|
+
if (![token, account, peer].every((value) => typeof value === 'string' && value.length > 0 && value.length <= 8192)) {
|
|
239
|
+
throw new WeixinError('invalid_response');
|
|
240
|
+
}
|
|
241
|
+
const page = service.channelPage(assistantID, { tipOnly: true });
|
|
242
|
+
store.bind({ assistant_id: assistantID, account_id: account, peer_id: peer, token,
|
|
243
|
+
base_url: weixinOrigin(response.baseurl || origin), language: login.language,
|
|
244
|
+
generation: page.generation, ordinal: page.tipOrdinal, updated_at: clock() });
|
|
245
|
+
logins.delete(assistantID);
|
|
246
|
+
void track(tick());
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (response.status === 'scaned_but_redirect' && response.redirect_host && redirects++ < 3) {
|
|
250
|
+
origin = weixinOrigin(response.redirect_host);
|
|
251
|
+
} else if (response.status === 'need_verifycode') {
|
|
252
|
+
login.status = 'verify';
|
|
253
|
+
} else if (response.status === 'scaned') {
|
|
254
|
+
login.status = 'scanned';
|
|
255
|
+
} else if (['expired', 'verify_code_blocked', 'binded_redirect'].includes(response.status)) {
|
|
256
|
+
login.status = 'expired';
|
|
257
|
+
login.error = response.status === 'binded_redirect' ? 'already_bound' : null;
|
|
258
|
+
login.qrCode = null;
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
login.error = null;
|
|
262
|
+
} catch (error) {
|
|
263
|
+
if (login.controller.signal.aborted || closed) return;
|
|
264
|
+
login.error = safeError(error);
|
|
265
|
+
if (['account_in_use', 'not_found', 'invalid_response', 'channel_in_use'].includes(login.error)) {
|
|
266
|
+
login.status = 'error'; login.qrCode = null; return;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
await pause(1000, login.controller.signal);
|
|
270
|
+
}
|
|
271
|
+
if (logins.get(assistantID) === login) { login.status = 'expired'; login.qrCode = null; }
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
const startLogin = async (assistantID, language = 'en') => {
|
|
275
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
276
|
+
assertOwner();
|
|
277
|
+
if (retiring.has(assistantID)) throw new WeixinError('channel_in_use');
|
|
278
|
+
const previous = logins.get(assistantID);
|
|
279
|
+
if (previous && ['waiting', 'scanned', 'verify'].includes(previous.status) && previous.expiresAt > clock()) return status(assistantID);
|
|
280
|
+
if (store.get(assistantID) && store.get(assistantID).status !== 'expired') throw new WeixinError('already_bound');
|
|
281
|
+
previous?.controller.abort();
|
|
282
|
+
stopReceiver(assistantID);
|
|
283
|
+
const login = { controller: new AbortController(), status: 'waiting', qrCode: null,
|
|
284
|
+
qrcode: '', verifyCode: '', language: String(language).slice(0, 32), expiresAt: clock() + 480_000 };
|
|
285
|
+
logins.set(assistantID, login);
|
|
286
|
+
try {
|
|
287
|
+
const data = await api.getQRCode(login.controller.signal, store.list().map((binding) => binding.token));
|
|
288
|
+
assertOwner();
|
|
289
|
+
if (logins.get(assistantID) !== login) throw new WeixinError('cancelled');
|
|
290
|
+
if (typeof data.qrcode !== 'string' || !data.qrcode || data.qrcode.length > 8192
|
|
291
|
+
|| typeof data.qrcode_img_content !== 'string' || !data.qrcode_img_content || data.qrcode_img_content.length > 8192) {
|
|
292
|
+
throw new WeixinError('invalid_response');
|
|
293
|
+
}
|
|
294
|
+
login.qrcode = data.qrcode;
|
|
295
|
+
login.qrCode = data.qrcode_img_content;
|
|
296
|
+
void track(pollLogin(assistantID, login));
|
|
297
|
+
return status(assistantID);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (logins.get(assistantID) === login) { login.status = 'error'; login.error = safeError(error); login.qrCode = null; }
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
const forget = async (assistantID) => {
|
|
304
|
+
retiring.add(assistantID);
|
|
305
|
+
logins.get(assistantID)?.controller.abort();
|
|
306
|
+
logins.delete(assistantID);
|
|
307
|
+
stopReceiver(assistantID);
|
|
308
|
+
try {
|
|
309
|
+
await typing.forget(assistantID);
|
|
310
|
+
store.unlink(assistantID);
|
|
311
|
+
} finally { retiring.delete(assistantID); }
|
|
312
|
+
};
|
|
313
|
+
const disconnect = async (assistantID) => {
|
|
314
|
+
service.channelPage(assistantID, { tipOnly: true });
|
|
315
|
+
assertOwner();
|
|
316
|
+
await forget(assistantID);
|
|
317
|
+
return status(assistantID);
|
|
318
|
+
};
|
|
319
|
+
const timer = setInterval(() => { void track(tick()); }, intervalMs);
|
|
320
|
+
timer.unref?.();
|
|
321
|
+
void track(tick());
|
|
322
|
+
return {
|
|
323
|
+
status, startLogin, disconnect, forget,
|
|
324
|
+
verify: (assistantID, code) => {
|
|
325
|
+
assertOwner();
|
|
326
|
+
const login = logins.get(assistantID);
|
|
327
|
+
if (!login || login.status !== 'verify' || typeof code !== 'string' || !/^\d{4,12}$/.test(code)) throw new WeixinError('validation_error');
|
|
328
|
+
login.verifyCode = code;
|
|
329
|
+
return status(assistantID);
|
|
330
|
+
},
|
|
331
|
+
retry: (assistantID) => {
|
|
332
|
+
assertOwner();
|
|
333
|
+
const binding = store.get(assistantID);
|
|
334
|
+
if (!binding) throw new WeixinError('not_found');
|
|
335
|
+
if (binding.status === 'expired') throw new WeixinError('auth_expired');
|
|
336
|
+
store.retry(binding.epoch);
|
|
337
|
+
store.patch(binding.epoch, { error: null });
|
|
338
|
+
void track(tick());
|
|
339
|
+
return status(assistantID);
|
|
340
|
+
},
|
|
341
|
+
onTurnEvent: (event) => {
|
|
342
|
+
if (closed || !ownsLease) return;
|
|
343
|
+
if (event.type === 'yuri:contact-turn-end') store.finishTurn(event.properties?.turnID ?? event.turnID);
|
|
344
|
+
typing.onTurnEvent(event);
|
|
345
|
+
},
|
|
346
|
+
close: () => {
|
|
347
|
+
if (closePromise) return closePromise;
|
|
348
|
+
closed = true;
|
|
349
|
+
clearInterval(timer);
|
|
350
|
+
lifetime.abort();
|
|
351
|
+
for (const login of logins.values()) login.controller.abort();
|
|
352
|
+
for (const id of receivers.keys()) stopReceiver(id);
|
|
353
|
+
closePromise = Promise.allSettled([...operations, typing.close()]).then(() => { store.release(owner); store.close(); });
|
|
354
|
+
return closePromise;
|
|
355
|
+
},
|
|
356
|
+
};
|
|
357
|
+
}
|