@xmanrui/dsh-im 5.9.1 → 5.10.0
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/PROACTIVE_DELIVERY.en.md +33 -9
- package/PROACTIVE_DELIVERY.md +33 -9
- package/README.en.md +3 -2
- package/README.md +4 -3
- package/lib/client.js +550 -125
- package/lib/index.js +323 -323
- package/package.json +1 -1
- package/plugin-src/client/delivery-settings.js +2 -0
- package/plugin-src/client/delivery-sync-settings.js +269 -0
- package/plugin-src/client/global-settings.js +45 -7
- package/plugin-src/client/i18n-ru.js +27 -0
- package/plugin-src/client/i18n.js +27 -0
- package/plugin-src/client/index.js +17 -1
- package/plugin-src/client/model-setting.js +6 -3
- package/plugin-src/client/styles.js +16 -0
- package/plugin-src/host/channels/feishu/production.mjs +11 -27
- package/plugin-src/host/channels/shared/workspace-rpc.mjs +1 -0
- package/plugin-src/host/delivery-adapter.mjs +35 -20
- package/plugin-src/host/delivery-service.mjs +100 -1
- package/plugin-src/host/delivery-suggestions.mjs +28 -0
- package/plugin-src/host/delivery-sync-rpc.mjs +100 -0
- package/plugin-src/host/host-language-rpc.mjs +16 -2
- package/plugin-src/host/host-language.mjs +29 -0
- package/plugin-src/host/index.mjs +22 -0
- package/plugin-src/host/session-sync-coordinator.mjs +288 -121
- package/plugin-src/host/session-sync-targets.mjs +71 -0
- package/scripts/verify-package.mjs +14 -5
- package/src/channels/qq/qq-bridge.mjs +9 -0
- package/src/channels/qq/state-store.mjs +42 -0
- package/src/channels/shared/action-card.mjs +83 -7
- package/src/channels/shared/bot-workspace-store.mjs +100 -8
- package/src/channels/shared/delivery-sync-settings-store.mjs +86 -0
- package/src/channels/shared/delivery-sync-settings.mjs +122 -0
- package/src/channels/shared/harness-client.mjs +148 -90
- package/src/channels/shared/i18n-en/diagnostics.mjs +1 -0
- package/src/channels/shared/i18n-en/shared-b.mjs +6 -0
- package/src/channels/shared/i18n-ru/diagnostics.mjs +1 -0
- package/src/channels/shared/i18n-ru/shared-b.mjs +5 -0
- package/src/channels/shared/interface-language-store.mjs +49 -10
- package/src/channels/shared/interface-language.mjs +19 -1
- package/src/channels/shared/model-setting.mjs +6 -3
- package/src/channels/shared/workspace-session.mjs +13 -1
- package/src/channels/telegram/telegram-api.mjs +19 -1
|
@@ -26,6 +26,7 @@ export function publicWorkspaceError(error) {
|
|
|
26
26
|
'agent-preset-unavailable',
|
|
27
27
|
'model-selection-invalid',
|
|
28
28
|
'model-selection-unavailable',
|
|
29
|
+
'model-catalog-unavailable',
|
|
29
30
|
'model-reasoning-unavailable',
|
|
30
31
|
'context-enhancement-invalid',
|
|
31
32
|
'access-policy-invalid',
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import {
|
|
3
|
+
conversationKeyMatchesTarget,
|
|
4
|
+
deliverySuggestionFromConversationKey,
|
|
3
5
|
deliverySuggestionsFromSessions,
|
|
4
6
|
privateConversationKeyMatchesTarget,
|
|
5
7
|
privateDeliverySuggestionFromConversationKey,
|
|
6
|
-
|
|
8
|
+
resolveConversationKey,
|
|
7
9
|
} from './delivery-suggestions.mjs';
|
|
8
10
|
import { parseConversationKey } from '../../src/channels/shared/conversation/describe.mjs';
|
|
9
11
|
import { withSessionBindingLock } from '../../src/channels/shared/session-binding-lock.mjs';
|
|
@@ -196,8 +198,8 @@ function sessionSyncConfigs(workspaces, botId) {
|
|
|
196
198
|
return botId === undefined ? targets : targets.filter((target) => target.botId === botId);
|
|
197
199
|
}
|
|
198
200
|
|
|
199
|
-
/** Bindings own their
|
|
200
|
-
*
|
|
201
|
+
/** Bindings own their chat sync while active. Ordinary delivery settings remain
|
|
202
|
+
* saved and resume after unbinding, without duplicate mirrors. */
|
|
201
203
|
export function configuredSessionSyncTargets(workspaces, botId) {
|
|
202
204
|
const bindings = (workspaces.listDsBotBindings?.(botId) ?? []).map((binding) => ({
|
|
203
205
|
...binding,
|
|
@@ -214,7 +216,7 @@ export function configuredSessionSyncTargets(workspaces, botId) {
|
|
|
214
216
|
export function sessionSyncTarget(channel, workspaces, configured) {
|
|
215
217
|
if (!configured) return null;
|
|
216
218
|
if (!configured.dsBotId) return workspaces.deliveryTargetFor(configured.botId, configured.targetId);
|
|
217
|
-
const target =
|
|
219
|
+
const target = deliverySuggestionFromConversationKey(channel, configured.conversationKey);
|
|
218
220
|
return target ? { ...target, targetId: configured.targetId } : null;
|
|
219
221
|
}
|
|
220
222
|
|
|
@@ -305,11 +307,7 @@ function stateSessions(state) {
|
|
|
305
307
|
|
|
306
308
|
function sessionSyncView(channel, target, sessions, configured) {
|
|
307
309
|
if (configured) {
|
|
308
|
-
const valid =
|
|
309
|
-
channel,
|
|
310
|
-
configured.conversationKey,
|
|
311
|
-
target,
|
|
312
|
-
);
|
|
310
|
+
const valid = conversationKeyMatchesTarget(channel, configured.conversationKey, target);
|
|
313
311
|
if (!valid || !sessions) return { enabled: true, state: 'unavailable' };
|
|
314
312
|
return {
|
|
315
313
|
enabled: true,
|
|
@@ -320,7 +318,7 @@ function sessionSyncView(channel, target, sessions, configured) {
|
|
|
320
318
|
};
|
|
321
319
|
}
|
|
322
320
|
const conversationKey = sessions
|
|
323
|
-
?
|
|
321
|
+
? resolveConversationKey(channel, sessions, target)
|
|
324
322
|
: null;
|
|
325
323
|
return { enabled: false, state: conversationKey ? 'off' : 'unavailable' };
|
|
326
324
|
}
|
|
@@ -344,11 +342,20 @@ export function createDeliveryAdapter({
|
|
|
344
342
|
if (typeof stateFor !== 'function') {
|
|
345
343
|
throw new TypeError('delivery adapter requires a bot state getter');
|
|
346
344
|
}
|
|
347
|
-
const syncTarget = async (botId, targetId, sessionId, { allowParts = true } = {}) => {
|
|
345
|
+
const syncTarget = async (botId, targetId, sessionId, { allowParts = true, privateOnly = false } = {}) => {
|
|
348
346
|
const configured = configuredSessionSyncTargets(workspaces, botId).find((entry) => entry.targetId === targetId);
|
|
349
347
|
const target = sessionSyncTarget(channel, workspaces, configured);
|
|
350
|
-
|
|
351
|
-
|
|
348
|
+
// Mirrored text may follow any route the channel persists. A synced question
|
|
349
|
+
// or approval is different: it is answered by whoever reads the chat, so
|
|
350
|
+
// those two paths keep the private-only gate — a group, a thread or a forum
|
|
351
|
+
// topic never becomes a place where anyone can answer for the reader.
|
|
352
|
+
const keyMatches = privateOnly
|
|
353
|
+
? privateConversationKeyMatchesTarget(channel, configured?.conversationKey, target)
|
|
354
|
+
: conversationKeyMatchesTarget(channel, configured?.conversationKey, target);
|
|
355
|
+
if (!configured || !target || !keyMatches) {
|
|
356
|
+
throw sessionSyncUnavailable(privateOnly
|
|
357
|
+
? 'Session sync questions and approvals need one private chat'
|
|
358
|
+
: 'Session sync target is no longer enabled');
|
|
352
359
|
}
|
|
353
360
|
const sessions = stateSessions(await stateFor(botId));
|
|
354
361
|
const bot = configured.dsBotId ? await dsBot?.resolve(configured.dsBotId) : null;
|
|
@@ -360,14 +367,15 @@ export function createDeliveryAdapter({
|
|
|
360
367
|
}
|
|
361
368
|
return { target, conversationKey: configured.conversationKey, dsBotId: configured.dsBotId };
|
|
362
369
|
};
|
|
363
|
-
const describeSyncTarget = async (botId, targetId, sessionId) => {
|
|
364
|
-
const { conversationKey } = await syncTarget(botId, targetId, sessionId);
|
|
370
|
+
const describeSyncTarget = async (botId, targetId, sessionId, options = {}) => {
|
|
371
|
+
const { conversationKey } = await syncTarget(botId, targetId, sessionId, options);
|
|
365
372
|
return { conversationKey };
|
|
366
373
|
};
|
|
367
374
|
const presentSyncInteraction = async (method, botId, targetId, sessionId, interaction, options = {}) => {
|
|
368
375
|
// Text from an old part may finish delivery, but a new question answer must
|
|
369
|
-
// still belong to the Bot's current session
|
|
370
|
-
|
|
376
|
+
// still belong to the Bot's current session, and both interactions stay
|
|
377
|
+
// private-chat only.
|
|
378
|
+
const routeOptions = { allowParts: method !== 'presentSessionSyncQuestion', privateOnly: true };
|
|
371
379
|
const original = await syncTarget(botId, targetId, sessionId, routeOptions);
|
|
372
380
|
if (typeof coreController[method] !== 'function') return false;
|
|
373
381
|
const validate = async () => {
|
|
@@ -568,7 +576,7 @@ export function createDeliveryAdapter({
|
|
|
568
576
|
return sessionSyncView(channel, target, sessions, null);
|
|
569
577
|
}
|
|
570
578
|
const sessions = stateSessions(await stateFor(botId));
|
|
571
|
-
const conversationKey =
|
|
579
|
+
const conversationKey = resolveConversationKey(channel, sessions, target);
|
|
572
580
|
if (!conversationKey) throw sessionSyncUnavailable();
|
|
573
581
|
await workspaces.setDeliveryTargetSessionSync(botId, targetId, conversationKey);
|
|
574
582
|
return { enabled: true, state: 'active' };
|
|
@@ -580,6 +588,9 @@ export function createDeliveryAdapter({
|
|
|
580
588
|
const matches = [];
|
|
581
589
|
for (const configured of configuredSessionSyncTargets(workspaces)) {
|
|
582
590
|
const target = sessionSyncTarget(channel, workspaces, configured);
|
|
591
|
+
// Listed targets are the candidate range of synced questions and
|
|
592
|
+
// approvals only, so a non-private route never appears here even
|
|
593
|
+
// though mirrored text may be delivered to it.
|
|
583
594
|
if (!target || !privateConversationKeyMatchesTarget(
|
|
584
595
|
channel,
|
|
585
596
|
configured.conversationKey,
|
|
@@ -599,8 +610,12 @@ export function createDeliveryAdapter({
|
|
|
599
610
|
}
|
|
600
611
|
return matches;
|
|
601
612
|
},
|
|
602
|
-
|
|
603
|
-
|
|
613
|
+
// Both interaction paths resolve their target through the private-only gate,
|
|
614
|
+
// so a synced group or topic is never offered a question or an approval.
|
|
615
|
+
describeSessionSyncApprovalTarget: (botId, targetId, sessionId) =>
|
|
616
|
+
describeSyncTarget(botId, targetId, sessionId, { privateOnly: true }),
|
|
617
|
+
describeSessionSyncQuestionTarget: (botId, targetId, sessionId) =>
|
|
618
|
+
describeSyncTarget(botId, targetId, sessionId, { privateOnly: true }),
|
|
604
619
|
async presentSessionSyncApproval(botId, targetId, sessionId, interaction, options = {}) {
|
|
605
620
|
return presentSyncInteraction('presentSessionSyncApproval', botId, targetId, sessionId, interaction, options);
|
|
606
621
|
},
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { normalizeDeliveryTarget } from './delivery-adapter.mjs';
|
|
3
|
+
import { deliverySuggestionFromConversationKey } from './delivery-suggestions.mjs';
|
|
3
4
|
import { COMPETITIVE_APPROVAL_CHANNELS } from '../../src/channels/shared/harness-approval.mjs';
|
|
4
5
|
import { t } from '../../src/channels/shared/i18n.mjs';
|
|
6
|
+
import { parseConversationKey } from '../../src/channels/shared/conversation/describe.mjs';
|
|
5
7
|
|
|
6
8
|
const BOT_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
7
9
|
const TARGET_ID_PATTERN = /^[A-Za-z0-9._:@-]{1,128}$/;
|
|
@@ -145,9 +147,10 @@ function sessionSyncState(value, available) {
|
|
|
145
147
|
export class DeliveryService {
|
|
146
148
|
#adapters = new Map();
|
|
147
149
|
#unavailableSessionSyncChannels;
|
|
150
|
+
#logger;
|
|
148
151
|
dsBot;
|
|
149
152
|
|
|
150
|
-
constructor({ unavailableSessionSyncChannels = [], dsBot } = {}) {
|
|
153
|
+
constructor({ unavailableSessionSyncChannels = [], dsBot, logger = console } = {}) {
|
|
151
154
|
if (!Array.isArray(unavailableSessionSyncChannels)
|
|
152
155
|
|| unavailableSessionSyncChannels.some((channel) => (
|
|
153
156
|
typeof channel !== 'string' || !CHANNEL_PATTERN.test(channel)
|
|
@@ -155,6 +158,7 @@ export class DeliveryService {
|
|
|
155
158
|
throw new TypeError('unavailableSessionSyncChannels must contain valid channel ids');
|
|
156
159
|
}
|
|
157
160
|
this.#unavailableSessionSyncChannels = new Set(unavailableSessionSyncChannels);
|
|
161
|
+
this.#logger = logger ?? console;
|
|
158
162
|
this.dsBot = dsBot;
|
|
159
163
|
}
|
|
160
164
|
|
|
@@ -503,6 +507,7 @@ export class DeliveryService {
|
|
|
503
507
|
}
|
|
504
508
|
|
|
505
509
|
/**
|
|
510
|
+
|
|
506
511
|
* The same lookup, answered from memory only: no await, no network. A session
|
|
507
512
|
* whose channel has not loaded its state yet answers null — which is exactly the
|
|
508
513
|
* truth a synchronous prompt assembly can act on.
|
|
@@ -522,6 +527,100 @@ export class DeliveryService {
|
|
|
522
527
|
return null;
|
|
523
528
|
}
|
|
524
529
|
|
|
530
|
+
/**
|
|
531
|
+
* The Session no channel state owns may still be a DS Bot's current session:
|
|
532
|
+
* its chat was bound to the bot, the bot's `sessionId` rolled over without a
|
|
533
|
+
* new inbound message, and only the bot service knows the new session. Reverse
|
|
534
|
+
* the binding through `dsBot.status()` so delivery survives that rollover.
|
|
535
|
+
* An unavailable DS Bot, or a session no bot currently owns, answers `null`.
|
|
536
|
+
*/
|
|
537
|
+
async describeViaDsBot(sessionId) {
|
|
538
|
+
try {
|
|
539
|
+
const status = await this.dsBot?.status();
|
|
540
|
+
if (status?.state !== 'ready') return null;
|
|
541
|
+
const bot = status.bots.find((entry) => entry.sessionId === sessionId);
|
|
542
|
+
if (!bot) return null;
|
|
543
|
+
for (const { adapter } of this.#adapters.values()) {
|
|
544
|
+
const bindings = await adapter.listDsBotBindings?.() ?? [];
|
|
545
|
+
const binding = bindings.find((entry) => entry.dsBotId === bot.id);
|
|
546
|
+
if (!binding) continue;
|
|
547
|
+
const parsed = parseConversationKey(binding.conversationKey, { channel: adapter.channel });
|
|
548
|
+
return {
|
|
549
|
+
channel: adapter.channel,
|
|
550
|
+
botId: binding.botId,
|
|
551
|
+
botName: bot.name ?? null,
|
|
552
|
+
conversationKey: binding.conversationKey,
|
|
553
|
+
chatType: parsed?.chatType ?? null,
|
|
554
|
+
chatId: parsed?.chatId ?? null,
|
|
555
|
+
threadId: parsed?.threadId ?? null,
|
|
556
|
+
chatTitle: null,
|
|
557
|
+
senderId: null,
|
|
558
|
+
senderName: null,
|
|
559
|
+
senderUsername: null,
|
|
560
|
+
senderIsBot: null,
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
return null;
|
|
564
|
+
} catch {
|
|
565
|
+
return null;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Deliver one text to the chat this Session is currently bound to.
|
|
571
|
+
*
|
|
572
|
+
* The address is not configured anywhere beforehand: `describeConversation`
|
|
573
|
+
* reads the conversation the channel itself keeps for the Session, and its
|
|
574
|
+
* conversation key becomes the same draft route the manual delivery path
|
|
575
|
+
* accepts. A Session no channel owns simply has nowhere to go, which is a
|
|
576
|
+
* result rather than an error; a real send failure is thrown like `send()`.
|
|
577
|
+
*
|
|
578
|
+
* @param {string} sessionId harness session id
|
|
579
|
+
* @param {string} text message body
|
|
580
|
+
* @param {{format?: 'plain'|'markdown', signal?: AbortSignal}} [options]
|
|
581
|
+
* @returns {Promise<{sent: true} | {sent: false, reason: 'unbound'|'unroutable'}>}
|
|
582
|
+
*/
|
|
583
|
+
async deliverSessionText(sessionId, text, { format = 'plain', signal } = {}) {
|
|
584
|
+
if (typeof sessionId !== 'string' || !sessionId
|
|
585
|
+
|| typeof text !== 'string' || !text.trim()
|
|
586
|
+
|| (format !== 'plain' && format !== 'markdown')) {
|
|
587
|
+
throw deliveryError('bad-request', 'Invalid Session delivery');
|
|
588
|
+
}
|
|
589
|
+
cancellation(signal);
|
|
590
|
+
const described = await this.describeConversation(sessionId) ?? await this.describeViaDsBot(sessionId);
|
|
591
|
+
cancellation(signal);
|
|
592
|
+
if (!described) {
|
|
593
|
+
this.#warnUndelivered(sessionId, 'unbound', null);
|
|
594
|
+
return { sent: false, reason: 'unbound' };
|
|
595
|
+
}
|
|
596
|
+
const draft = deliverySuggestionFromConversationKey(described.channel, described.conversationKey);
|
|
597
|
+
if (!draft) {
|
|
598
|
+
// A key the channel persisted but no route covers stays unroutable. An
|
|
599
|
+
// older shape such as `direct:<chatId>:<threadId>` is deliberately not
|
|
600
|
+
// reinterpreted as a chat: guessing a recipient would drop the thread and
|
|
601
|
+
// message the wrong place, so the key is only reported here.
|
|
602
|
+
this.#warnUndelivered(sessionId, 'unroutable', described);
|
|
603
|
+
return { sent: false, reason: 'unroutable' };
|
|
604
|
+
}
|
|
605
|
+
// The draft goes through the ordinary send path, so the adapter validates
|
|
606
|
+
// and normalizes it exactly as it does a saved target.
|
|
607
|
+
return this.send(described.botId, { kind: draft.kind, route: draft.route }, text, { signal, format });
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Report one text that found nowhere to go. Only the identifiers that make the
|
|
612
|
+
* miss diagnosable are logged — Session, channel, conversation key — never the
|
|
613
|
+
* message body, and never a channel credential.
|
|
614
|
+
*/
|
|
615
|
+
#warnUndelivered(sessionId, reason, described) {
|
|
616
|
+
const where = described
|
|
617
|
+
? ` channel=${described.channel} conversationKey=${described.conversationKey}`
|
|
618
|
+
: '';
|
|
619
|
+
this.#logger?.warn?.(
|
|
620
|
+
`[dsh-im] Session text was not delivered [${reason}] session=${sessionId}${where}`,
|
|
621
|
+
);
|
|
622
|
+
}
|
|
623
|
+
|
|
525
624
|
async describeBot(botId) {
|
|
526
625
|
const id = botIdOf(botId);
|
|
527
626
|
const registration = await this.#checkedRegistrationFor(id);
|
|
@@ -60,6 +60,8 @@ function slackSuggestion(key) {
|
|
|
60
60
|
return { kind: 'thread', route: { channelId: match[1], threadTs: match[2] } };
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
// Telegram-only: numeric chat/topic keys can safely prefill Telegram target fields.
|
|
64
|
+
// Other channels must use their native route fields; never turn their keys into Telegram links.
|
|
63
65
|
function telegramSuggestion(key) {
|
|
64
66
|
const match = /^(direct|group):(-?\d+)(?::([1-9]\d*))?$/.exec(key);
|
|
65
67
|
if (!match) return null;
|
|
@@ -192,6 +194,32 @@ export function resolvePrivateConversationKey(channel, sessions, target) {
|
|
|
192
194
|
return matches[0] ?? null;
|
|
193
195
|
}
|
|
194
196
|
|
|
197
|
+
/**
|
|
198
|
+
* Check that one saved conversation key still identifies this target route.
|
|
199
|
+
*
|
|
200
|
+
* Unlike the private variant this accepts every route the channel can persist —
|
|
201
|
+
* a Telegram forum topic (`group:<chatId>:<threadId>`), a Slack thread, a
|
|
202
|
+
* Discord channel — because mirrored text is not limited to private chat.
|
|
203
|
+
* Questions and approvals keep the private gate: they are resolved through
|
|
204
|
+
* `privateConversationKeyMatchesTarget` instead of this function.
|
|
205
|
+
*/
|
|
206
|
+
export function conversationKeyMatchesTarget(channel, key, target) {
|
|
207
|
+
const suggestionIdentity = routeIdentity(deliverySuggestionFromConversationKey(channel, key));
|
|
208
|
+
return suggestionIdentity !== null && suggestionIdentity === routeIdentity(target);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Resolve exactly one current conversation of any route kind for a normalized delivery target. */
|
|
212
|
+
export function resolveConversationKey(channel, sessions, target) {
|
|
213
|
+
if (!CHANNELS.has(channel) || !isRecord(sessions)) return null;
|
|
214
|
+
const matches = [];
|
|
215
|
+
for (const [key, sessionId] of Object.entries(sessions)) {
|
|
216
|
+
if (typeof sessionId !== 'string' || !sessionId) continue;
|
|
217
|
+
if (conversationKeyMatchesTarget(channel, key, target)) matches.push(key);
|
|
218
|
+
if (matches.length > 1) return null;
|
|
219
|
+
}
|
|
220
|
+
return matches[0] ?? null;
|
|
221
|
+
}
|
|
222
|
+
|
|
195
223
|
/**
|
|
196
224
|
* Extract and de-duplicate stable delivery routes from a persisted sessions map.
|
|
197
225
|
* Session ids and every other state field are intentionally ignored.
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { registerManagementRpc } from '../management-rpc.mjs';
|
|
2
|
+
import { deliverySyncPatchKeys } from '../../src/channels/shared/delivery-sync-settings.mjs';
|
|
3
|
+
import { getDeliverySyncSettingsStore } from '../../src/channels/shared/delivery-sync-settings-store.mjs';
|
|
4
|
+
import { t } from '../../src/channels/shared/i18n.mjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Management channel for the delivery-sync settings. It is separate from the
|
|
8
|
+
* loopback-only `/dsh-im-settings` channel on purpose: this page must stay
|
|
9
|
+
* usable from an authenticated domain (the Host dashboard served beyond
|
|
10
|
+
* loopback), so it follows the profile's `rpcAuthority` like the sidebar
|
|
11
|
+
* settings do.
|
|
12
|
+
*/
|
|
13
|
+
export const DELIVERY_SYNC_RPC_CHANNEL = '/dsh-im-delivery-sync';
|
|
14
|
+
|
|
15
|
+
export const DELIVERY_SYNC_ENDPOINTS = Object.freeze({
|
|
16
|
+
get: 'settings.delivery-sync.get',
|
|
17
|
+
set: 'settings.delivery-sync.set',
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
const ENDPOINTS = new Set(Object.values(DELIVERY_SYNC_ENDPOINTS));
|
|
21
|
+
|
|
22
|
+
const BOOLEAN_FIELDS = new Set(['mirrorUserInput', 'deliverModelAnswers']);
|
|
23
|
+
const ICON_FIELDS = new Set(['inputIcon', 'modelIcon']);
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Validate one delivery-sync request. `get` takes an empty object; `set` takes
|
|
27
|
+
* one or more of the four known fields, each with the type it is stored as.
|
|
28
|
+
* An icon that is a string but unusable is accepted here and normalized to the
|
|
29
|
+
* empty prefix by the store, so a reader never loses a save over a pasted
|
|
30
|
+
* emoji sequence.
|
|
31
|
+
*/
|
|
32
|
+
export function validDeliverySyncPayload(endpoint, payload) {
|
|
33
|
+
if (!ENDPOINTS.has(endpoint)) return false;
|
|
34
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) return false;
|
|
35
|
+
const keys = deliverySyncPatchKeys(payload);
|
|
36
|
+
if (keys === null) return false;
|
|
37
|
+
if (endpoint === DELIVERY_SYNC_ENDPOINTS.get) return keys.length === 0;
|
|
38
|
+
if (keys.length === 0) return false;
|
|
39
|
+
return keys.every((key) => (BOOLEAN_FIELDS.has(key)
|
|
40
|
+
? typeof payload[key] === 'boolean'
|
|
41
|
+
: ICON_FIELDS.has(key) && typeof payload[key] === 'string'));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createDeliverySyncRpcHandler(store, { logger = console } = {}) {
|
|
45
|
+
if (!store || typeof store.get !== 'function' || typeof store.set !== 'function') {
|
|
46
|
+
throw new TypeError('createDeliverySyncRpcHandler requires a delivery sync settings store');
|
|
47
|
+
}
|
|
48
|
+
return async (endpoint, payload, signal) => {
|
|
49
|
+
if (!validDeliverySyncPayload(endpoint, payload)) {
|
|
50
|
+
return {
|
|
51
|
+
ok: false,
|
|
52
|
+
error: {
|
|
53
|
+
code: 'bad-request',
|
|
54
|
+
message: t('无效的会话同步设置:开关必须是布尔值,图标是不超过 32 个字符的文本。'),
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
if (signal?.aborted) {
|
|
59
|
+
return { ok: false, error: { code: 'cancelled', message: t('请求已取消。') } };
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
const value = endpoint === DELIVERY_SYNC_ENDPOINTS.get
|
|
63
|
+
? await store.get()
|
|
64
|
+
: await store.set(payload);
|
|
65
|
+
return { ok: true, value };
|
|
66
|
+
} catch (error) {
|
|
67
|
+
// The page only sees a stable code; the Host log keeps the cause, so a
|
|
68
|
+
// damaged document or a permission problem stays diagnosable.
|
|
69
|
+
logger?.warn?.(
|
|
70
|
+
`[dsh-im] delivery-sync settings ${endpoint} failed`
|
|
71
|
+
+ ` [${error?.code ?? error?.name ?? 'unknown-error'}]: ${error?.message ?? ''}`,
|
|
72
|
+
);
|
|
73
|
+
return {
|
|
74
|
+
ok: false,
|
|
75
|
+
error: {
|
|
76
|
+
code: 'delivery-sync-settings-unavailable',
|
|
77
|
+
message: t('无法读取或保存会话同步设置,请稍后重试。'),
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Install-time helper: the store the RPC and the coordinator share. */
|
|
85
|
+
export function deliverySyncStore(config) {
|
|
86
|
+
return getDeliverySyncSettingsStore(config);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Register the delivery-sync settings channel. The authority follows the
|
|
91
|
+
* profile option (`trusted-host` by default) because the settings page is
|
|
92
|
+
* commonly opened through the Host dashboard's own domain rather than
|
|
93
|
+
* 127.0.0.1; `loopback` stays available for operators who pinned it.
|
|
94
|
+
*/
|
|
95
|
+
export function installDeliverySyncRpc(ctx, { config = {}, store = null, logger = console } = {}) {
|
|
96
|
+
const handler = createDeliverySyncRpcHandler(store ?? deliverySyncStore(config), { logger });
|
|
97
|
+
return registerManagementRpc(ctx, DELIVERY_SYNC_RPC_CHANNEL, handler, {
|
|
98
|
+
authority: config.rpcAuthority,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { registerManagementRpc } from '../management-rpc.mjs';
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
normalizeInterfaceLanguageTag,
|
|
4
|
+
normalizeMessageLanguageChoice,
|
|
5
|
+
} from '../../src/channels/shared/interface-language.mjs';
|
|
3
6
|
|
|
4
7
|
export const HOST_LANGUAGE_RPC_CHANNEL = '/dsh-im-language';
|
|
5
8
|
export const HOST_LANGUAGE_ENDPOINTS = Object.freeze({
|
|
6
9
|
get: 'settings.language.get',
|
|
10
|
+
set: 'settings.language.set',
|
|
7
11
|
mirror: 'settings.language.mirror',
|
|
8
12
|
});
|
|
9
13
|
|
|
@@ -13,6 +17,12 @@ export function validHostLanguagePayload(endpoint, payload) {
|
|
|
13
17
|
if (!ENDPOINTS.has(endpoint)) return false;
|
|
14
18
|
if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) return false;
|
|
15
19
|
const keys = Object.keys(payload);
|
|
20
|
+
if (endpoint === HOST_LANGUAGE_ENDPOINTS.set) {
|
|
21
|
+
if (keys.length !== 1 || keys[0] !== 'language') return false;
|
|
22
|
+
// 'auto' clears the explicit choice; a tag must be one the shipped
|
|
23
|
+
// dictionaries can serve, so the page cannot pin a language nobody wrote.
|
|
24
|
+
return normalizeMessageLanguageChoice(payload.language) !== null;
|
|
25
|
+
}
|
|
16
26
|
if (endpoint === HOST_LANGUAGE_ENDPOINTS.mirror) {
|
|
17
27
|
if (keys.length !== 1 || keys[0] !== 'locale') return false;
|
|
18
28
|
// An explicit null clears the mirror; anything else must be a usable tag.
|
|
@@ -28,7 +38,7 @@ export function validHostLanguagePayload(endpoint, payload) {
|
|
|
28
38
|
*/
|
|
29
39
|
export function createHostLanguageRpcHandler({ controller, logger = null } = {}) {
|
|
30
40
|
if (!controller || typeof controller.snapshot !== 'function'
|
|
31
|
-
|| typeof controller.mirror !== 'function') {
|
|
41
|
+
|| typeof controller.mirror !== 'function' || typeof controller.select !== 'function') {
|
|
32
42
|
throw new TypeError('createHostLanguageRpcHandler requires a host language controller');
|
|
33
43
|
}
|
|
34
44
|
return async (endpoint, payload, signal) => {
|
|
@@ -42,6 +52,10 @@ export function createHostLanguageRpcHandler({ controller, logger = null } = {})
|
|
|
42
52
|
if (endpoint === HOST_LANGUAGE_ENDPOINTS.get) {
|
|
43
53
|
return { ok: true, value: controller.snapshot() };
|
|
44
54
|
}
|
|
55
|
+
if (endpoint === HOST_LANGUAGE_ENDPOINTS.set) {
|
|
56
|
+
const choice = normalizeMessageLanguageChoice(payload.language);
|
|
57
|
+
return { ok: true, value: await controller.select(choice === 'auto' ? null : choice) };
|
|
58
|
+
}
|
|
45
59
|
return { ok: true, value: await controller.mirror(payload.locale) };
|
|
46
60
|
} catch (error) {
|
|
47
61
|
// The failure is almost always a settings-directory write problem; keep
|
|
@@ -60,8 +60,11 @@ export function createHostLanguageController({
|
|
|
60
60
|
|
|
61
61
|
const mirrorTag = () => (typeof store?.getLanguageTag === 'function' ? store.getLanguageTag() : null);
|
|
62
62
|
|
|
63
|
+
const explicitTag = () => (typeof store?.getExplicitTag === 'function' ? store.getExplicitTag() : null);
|
|
64
|
+
|
|
63
65
|
const resolution = () => resolveHostLanguageTag({
|
|
64
66
|
config: configLanguage,
|
|
67
|
+
explicit: explicitTag(),
|
|
65
68
|
settings: settingsTag(),
|
|
66
69
|
mirror: mirrorTag(),
|
|
67
70
|
});
|
|
@@ -85,6 +88,32 @@ export function createHostLanguageController({
|
|
|
85
88
|
/** The resolution as it stands, without switching the active language. */
|
|
86
89
|
snapshot: () => describe(resolution()),
|
|
87
90
|
|
|
91
|
+
/**
|
|
92
|
+
* Pin the plugin's own message language, or pass null (the settings page's
|
|
93
|
+
* "same as the DSH interface") to clear that selection. It outranks DSH's
|
|
94
|
+
* locale, so a reader who wants English DSH with Russian bot messages can
|
|
95
|
+
* say so; an operator's `language` option still outranks both.
|
|
96
|
+
*/
|
|
97
|
+
async select(value) {
|
|
98
|
+
const choice = value === null || value === undefined ? null : value;
|
|
99
|
+
if (typeof store?.setExplicitTag !== 'function') return apply();
|
|
100
|
+
if (choice === null) {
|
|
101
|
+
await store.setExplicitTag(null);
|
|
102
|
+
} else {
|
|
103
|
+
const tag = normalizeInterfaceLanguageTag(choice);
|
|
104
|
+
if (tag === null) {
|
|
105
|
+
const error = new Error('Invalid message language selection.');
|
|
106
|
+
error.code = 'interface-language-invalid';
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
await store.setExplicitTag(tag);
|
|
110
|
+
}
|
|
111
|
+
return apply();
|
|
112
|
+
},
|
|
113
|
+
|
|
114
|
+
/** The current explicit selection, or null when the plugin follows DSH. */
|
|
115
|
+
explicit: explicitTag,
|
|
116
|
+
|
|
88
117
|
/** Record the interface locale reported by the settings UI, then re-resolve. */
|
|
89
118
|
async mirror(value) {
|
|
90
119
|
if (typeof store?.setLanguageTag !== 'function') return apply();
|
|
@@ -22,9 +22,12 @@ import { createDeliveryService } from './delivery-service.mjs';
|
|
|
22
22
|
import { createDsBotClient } from './ds-bot-client.mjs';
|
|
23
23
|
import { installDsBotQuestionSync } from './ds-bot-question-sync.mjs';
|
|
24
24
|
import { installInboundTtlRpc } from './inbound-ttl-rpc.mjs';
|
|
25
|
+
import { installDeliverySyncRpc } from './delivery-sync-rpc.mjs';
|
|
25
26
|
import { installSidebarSettingsRpc } from './sidebar-settings.mjs';
|
|
26
27
|
import { installInjectedContext } from './injected-context.mjs';
|
|
27
28
|
import { installSessionSyncCoordinator } from './session-sync-coordinator.mjs';
|
|
29
|
+
import { deliverySwitchesOff } from '../../src/channels/shared/delivery-sync-settings.mjs';
|
|
30
|
+
import { getDeliverySyncSettingsStore } from '../../src/channels/shared/delivery-sync-settings-store.mjs';
|
|
28
31
|
import { installSessionTitlePrefix } from './session-title-prefix.mjs';
|
|
29
32
|
import { installUpdateRpc } from './update-rpc.mjs';
|
|
30
33
|
|
|
@@ -52,6 +55,7 @@ export function createImHostPlugin(internals = {}) {
|
|
|
52
55
|
const startHostLanguageRpc = internals.installHostLanguageRpc ?? installHostLanguageRpc;
|
|
53
56
|
const startUpdate = internals.installUpdateRpc ?? installUpdateRpc;
|
|
54
57
|
const startInboundTtl = internals.installInboundTtlRpc ?? installInboundTtlRpc;
|
|
58
|
+
const startDeliverySync = internals.installDeliverySyncRpc ?? installDeliverySyncRpc;
|
|
55
59
|
const startSidebarSettings = internals.installSidebarSettingsRpc ?? installSidebarSettingsRpc;
|
|
56
60
|
const startInjectedContext = internals.installInjectedContext ?? installInjectedContext;
|
|
57
61
|
const startDelivery = internals.installDeliveryRpc ?? installDeliveryRpc;
|
|
@@ -101,6 +105,21 @@ export function createImHostPlugin(internals = {}) {
|
|
|
101
105
|
unavailableSessionSyncChannels: unavailableSessionSyncChannels.map((channel) => channel === 'wecomApp' ? 'wecom-app' : channel),
|
|
102
106
|
dsBot: createDsBotClient(ctx),
|
|
103
107
|
});
|
|
108
|
+
// The delivery switches are the master for everything that follows a Session
|
|
109
|
+
// through its targets: with both off, `listSessionSyncTargets` answers empty,
|
|
110
|
+
// so neither the coordinator nor a channel's own mirror (Feishu card) sends.
|
|
111
|
+
// A settings read failure must not disable delivery, so it falls through.
|
|
112
|
+
if (typeof deliveryService.listSessionSyncTargets === 'function') {
|
|
113
|
+
const rawListSessionSyncTargets = deliveryService.listSessionSyncTargets.bind(deliveryService);
|
|
114
|
+
deliveryService.listSessionSyncTargets = async (sessionId) => {
|
|
115
|
+
try {
|
|
116
|
+
if (deliverySwitchesOff(await getDeliverySyncSettingsStore(config).get())) return [];
|
|
117
|
+
} catch {
|
|
118
|
+
// keep the unwrapped behaviour
|
|
119
|
+
}
|
|
120
|
+
return rawListSessionSyncTargets(sessionId);
|
|
121
|
+
};
|
|
122
|
+
}
|
|
104
123
|
/** Sessions already reported, so the log stays one line per session. */
|
|
105
124
|
const describedSessions = new Set();
|
|
106
125
|
const describeConversationLogged = async (sessionId) => {
|
|
@@ -125,6 +144,7 @@ export function createImHostPlugin(internals = {}) {
|
|
|
125
144
|
historyChecked: (botId, route, query, options) => deliveryService.historyChecked(botId, route, query, options),
|
|
126
145
|
replyChecked: (botId, route, text, options) => deliveryService.replyChecked(botId, route, text, options),
|
|
127
146
|
describeConversation: (sessionId) => describeConversationLogged(sessionId),
|
|
147
|
+
|
|
128
148
|
// Prompt assembly is synchronous, so a caller that needs the identity
|
|
129
149
|
// before the first step cannot await the async variant.
|
|
130
150
|
describeConversationSync: (sessionId) => deliveryService.describeConversationSync(sessionId),
|
|
@@ -213,6 +233,7 @@ export function createImHostPlugin(internals = {}) {
|
|
|
213
233
|
}
|
|
214
234
|
try {
|
|
215
235
|
startInboundTtl(ctx, { config });
|
|
236
|
+
startDeliverySync(ctx, { config });
|
|
216
237
|
} catch (error) {
|
|
217
238
|
logger.error?.('[dsh-im] failed to activate inbound TTL settings; continuing with channels', error);
|
|
218
239
|
}
|
|
@@ -241,6 +262,7 @@ export function createImHostPlugin(internals = {}) {
|
|
|
241
262
|
startSessionSync(ctx, deliveryService, {
|
|
242
263
|
logger,
|
|
243
264
|
inputScope: ctx.root ?? ctx,
|
|
265
|
+
config,
|
|
244
266
|
});
|
|
245
267
|
installDsBotQuestionSync(ctx, deliveryService, { logger });
|
|
246
268
|
} catch (error) {
|