@xmanrui/dsh-im 5.9.0 → 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.
Files changed (52) hide show
  1. package/PROACTIVE_DELIVERY.en.md +33 -9
  2. package/PROACTIVE_DELIVERY.md +33 -9
  3. package/README.en.md +6 -3
  4. package/README.md +7 -4
  5. package/lib/client.js +582 -130
  6. package/lib/index.js +325 -325
  7. package/package.json +1 -1
  8. package/plugin-src/client/delivery-settings.js +2 -0
  9. package/plugin-src/client/delivery-sync-settings.js +269 -0
  10. package/plugin-src/client/global-settings.js +45 -7
  11. package/plugin-src/client/i18n-ru.js +27 -0
  12. package/plugin-src/client/i18n.js +27 -0
  13. package/plugin-src/client/index.js +17 -1
  14. package/plugin-src/client/model-setting.js +6 -3
  15. package/plugin-src/client/styles.js +16 -0
  16. package/plugin-src/host/channels/feishu/production.mjs +11 -27
  17. package/plugin-src/host/channels/shared/workspace-rpc.mjs +1 -0
  18. package/plugin-src/host/delivery-adapter.mjs +35 -20
  19. package/plugin-src/host/delivery-service.mjs +100 -1
  20. package/plugin-src/host/delivery-suggestions.mjs +28 -0
  21. package/plugin-src/host/delivery-sync-rpc.mjs +100 -0
  22. package/plugin-src/host/host-language-rpc.mjs +16 -2
  23. package/plugin-src/host/host-language.mjs +29 -0
  24. package/plugin-src/host/inbound-ttl-rpc.mjs +1 -1
  25. package/plugin-src/host/index.mjs +23 -1
  26. package/plugin-src/host/session-sync-coordinator.mjs +288 -121
  27. package/plugin-src/host/session-sync-targets.mjs +71 -0
  28. package/plugin-src/host/sidebar-settings.mjs +1 -2
  29. package/plugin-src/host/update-rpc.mjs +1 -1
  30. package/plugin-src/management-rpc.mjs +25 -3
  31. package/scripts/verify-lan-management.mjs +58 -5
  32. package/scripts/verify-package.mjs +14 -5
  33. package/src/channels/email/email-runtime.mjs +27 -8
  34. package/src/channels/feishu/bridge.mjs +250 -3
  35. package/src/channels/qq/qq-bridge.mjs +9 -0
  36. package/src/channels/qq/state-store.mjs +42 -0
  37. package/src/channels/shared/action-card.mjs +83 -7
  38. package/src/channels/shared/bot-workspace-store.mjs +100 -8
  39. package/src/channels/shared/delivery-sync-settings-store.mjs +86 -0
  40. package/src/channels/shared/delivery-sync-settings.mjs +122 -0
  41. package/src/channels/shared/harness-client.mjs +148 -90
  42. package/src/channels/shared/i18n-en/diagnostics.mjs +7 -1
  43. package/src/channels/shared/i18n-en/feishu.mjs +3 -0
  44. package/src/channels/shared/i18n-en/shared-b.mjs +6 -0
  45. package/src/channels/shared/i18n-ru/diagnostics.mjs +11 -0
  46. package/src/channels/shared/i18n-ru/feishu.mjs +2 -0
  47. package/src/channels/shared/i18n-ru/shared-b.mjs +5 -0
  48. package/src/channels/shared/interface-language-store.mjs +49 -10
  49. package/src/channels/shared/interface-language.mjs +19 -1
  50. package/src/channels/shared/model-setting.mjs +6 -3
  51. package/src/channels/shared/workspace-session.mjs +13 -1
  52. package/src/channels/telegram/telegram-api.mjs +19 -1
@@ -1,87 +1,283 @@
1
1
  import {
2
+ accumulateFinalAssistantText,
2
3
  AssistantTextAccumulator,
3
- consumeDshImInputOrigin,
4
+ isDshImInputOrigin,
4
5
  textFromHarnessContent,
5
6
  } from '../../src/channels/shared/harness-client.mjs';
7
+ import {
8
+ DEFAULT_DELIVERY_SYNC_SETTINGS,
9
+ normalizeDeliverySyncSettings,
10
+ withDeliverySyncIcon,
11
+ } from '../../src/channels/shared/delivery-sync-settings.mjs';
12
+ import { getDeliverySyncSettingsStore } from '../../src/channels/shared/delivery-sync-settings-store.mjs';
6
13
  import { deliverSessionSyncMirror } from '../../src/channels/shared/session-sync-registry.mjs';
7
14
 
8
- const DSH_USER_PREFIX = '[来自 DSH]\n';
9
- const DSH_ASSISTANT_PREFIX = '[DSH 助手]\n\n';
15
+ /**
16
+ * Where the turn came from, as far as a chat mirror is concerned.
17
+ *
18
+ * - `im`: the turn was started by a message from this very messenger. Its
19
+ * answer is already rendered there, so nothing is delivered.
20
+ * - `web`: the reader typed in the DSH Web GUI. Their own input may be mirrored
21
+ * into the chat, and the answer may be delivered.
22
+ * - `internal`: a service started the turn — a schedule reminder, an answered
23
+ * question, a notice such as `subagent-settled`, or the context the Host
24
+ * injects into every turn. The framing is internal and is never echoed, and
25
+ * it never decides where the turn came from: only a turn that locked no
26
+ * meaningful origin at all is delivered as a service turn.
27
+ */
28
+ export const TURN_INPUT_ORIGINS = Object.freeze({ im: 'im', web: 'web', internal: 'internal' });
29
+
30
+ /** Origins that may own a turn; `internal` is a fact about one message, not the turn. */
31
+ const MEANINGFUL_ORIGINS = new Set([TURN_INPUT_ORIGINS.im, TURN_INPUT_ORIGINS.web]);
32
+
33
+ /** Kinds whose turn is started by the Host rather than by a reader. */
34
+ const INTERNAL_KINDS = new Set(['schedule', 'user-question-reply']);
10
35
 
11
36
  function completedTurn(reason) {
12
37
  return (typeof reason === 'string' ? reason : reason?.kind) === 'completed';
13
38
  }
14
39
 
15
- function recipientKey(target) {
16
- return JSON.stringify([target.channel, target.botId, target.targetId]);
17
- }
18
-
19
40
  function sessionIdOf(session) {
20
41
  const value = session?.id ?? session?.sessionId;
21
42
  return typeof value === 'string' && value ? value : null;
22
43
  }
23
44
 
24
- function userInputOrigin(scope, event) {
25
- const source = event?.data?.source;
26
- if (source?.kind === 'schedule' || source?.kind === 'user-question-reply') return 'dsh';
27
- if (source?.kind !== 'user' || typeof source.rpcId !== 'string' || !source.rpcId) {
28
- return 'other';
29
- }
30
- return consumeDshImInputOrigin(scope, source.rpcId) ? 'im' : 'dsh';
45
+ /**
46
+ * Classify one `user/message` by the source of that very message.
47
+ *
48
+ * `imOwned` is the answer of `isDshImInputOrigin` for this message: only the
49
+ * messenger that received the input has its rpcId registered, so everything
50
+ * else is a different origin even though DSH models both as `kind: 'user'`.
51
+ * The lookup is non-destructive, so it never races the channel that owns the
52
+ * id and never turns the same messenger turn into a mirrored one.
53
+ */
54
+ export function classifyTurnInput(source, { imOwned = false } = {}) {
55
+ // A notice is Host framing whatever its kind says; `subagent-settled` and
56
+ // future notice kinds must never be echoed as if the reader had typed them.
57
+ if (source?.form === 'notice') return 'internal';
58
+ if (INTERNAL_KINDS.has(source?.kind)) return 'internal';
59
+ if (source?.kind !== 'user') return 'internal';
60
+ return imOwned ? 'im' : 'web';
31
61
  }
32
62
 
33
- function validRecipient(target) {
34
- return target && typeof target === 'object'
35
- && typeof target.channel === 'string' && target.channel
36
- && typeof target.botId === 'string' && target.botId
37
- && typeof target.targetId === 'string' && target.targetId;
38
- }
63
+ /**
64
+ * Settings used when the document cannot be read at all.
65
+ *
66
+ * A snapshot that cannot be loaded is not a reason to start mirroring: both
67
+ * switches are held off, so a broken or unreadable file fails closed and the
68
+ * chat simply receives nothing until the document is readable again.
69
+ */
70
+ const UNREADABLE_SETTINGS = Object.freeze({
71
+ ...DEFAULT_DELIVERY_SYNC_SETTINGS,
72
+ mirrorUserInput: false,
73
+ deliverModelAnswers: false,
74
+ });
39
75
 
40
- export function createSessionSyncCoordinator({ deliveryService, logger = console }) {
41
- if (typeof deliveryService?.listSessionSyncTargets !== 'function'
42
- || typeof deliveryService?.sendSessionSyncText !== 'function') {
43
- throw new TypeError('Session sync requires a complete delivery service');
76
+ /**
77
+ * @param options.loadSettings - Async getter of the delivery-sync settings
78
+ * document. Read once per turn. A failure is logged and mirrored nowhere: the
79
+ * reader asked for no mirroring by default, so an unreadable document must
80
+ * never become one.
81
+ */
82
+ export function createSessionSyncCoordinator({
83
+ deliveryService,
84
+ logger = console,
85
+ loadSettings = null,
86
+ } = {}) {
87
+ if (typeof deliveryService?.deliverSessionText !== 'function') {
88
+ throw new TypeError('Session sync requires a delivery service that can follow a Session binding');
44
89
  }
45
90
 
46
91
  const turns = new Map();
47
92
  const tails = new Map();
48
93
  let closed = false;
49
94
 
50
- const logFailure = (phase, target, error) => {
95
+ const logFailure = (phase, error) => {
51
96
  logger.warn?.(
52
97
  `[dsh-im] ignored Session sync ${phase} failure`
53
- + (target ? ` (${target.channel}/${target.botId}/${target.targetId})` : '')
54
98
  + ` [${error?.code ?? error?.name ?? 'unknown-error'}]`,
55
99
  );
56
100
  };
57
101
 
58
- const deliver = async (sessionId, targets, text, phase, format = 'plain') => {
59
- const unique = new Map();
60
- for (const target of targets) {
61
- if (validRecipient(target)) unique.set(recipientKey(target), target);
102
+ const logUndelivered = (sessionId, phase, reason) => {
103
+ // The address comes from the binding, so there is nothing secret to hide
104
+ // here, but the message text never appears in a log line.
105
+ logger.warn?.(
106
+ `[dsh-im] Session sync ${phase} found no delivery address`
107
+ + ` [${reason ?? 'no-reason'}] session=${sessionId}`,
108
+ );
109
+ };
110
+
111
+ const readSettings = async (state) => {
112
+ if (state.settings) return state.settings;
113
+ try {
114
+ const value = typeof loadSettings === 'function'
115
+ ? await loadSettings()
116
+ : DEFAULT_DELIVERY_SYNC_SETTINGS;
117
+ state.settings = normalizeDeliverySyncSettings(value) ?? DEFAULT_DELIVERY_SYNC_SETTINGS;
118
+ } catch (error) {
119
+ logFailure('settings', error);
120
+ state.settings = UNREADABLE_SETTINGS;
121
+ }
122
+ return state.settings;
123
+ };
124
+
125
+ // Saved targets keep control of delivery even when all their sync switches
126
+ // are off; an empty sync list must not bypass them through the binding path.
127
+ const botHasSavedTargets = async (sessionId) => {
128
+ try {
129
+ const described = await deliveryService.describeConversation(sessionId);
130
+ if (!described) return false;
131
+ const listed = await deliveryService.listTargets(described.botId);
132
+ return Array.isArray(listed?.targets) && listed.targets.length > 0;
133
+ } catch {
134
+ return false;
135
+ }
136
+ };
137
+
138
+ // A channel may render the answer itself — the Feishu process card does — so a
139
+ // target is not automatically a text recipient. A pending card is not proof of
140
+ // delivery either: the renderer is asked first and only the targets it did not
141
+ // confirm receive the text. Targets without a renderer keep the text path.
142
+ const renderFinalAnswer = async (targets, sessionId, turn, text) => {
143
+ if (!Number.isSafeInteger(turn)) return targets.map(() => false);
144
+ return await Promise.all(targets.map(async (target) => {
145
+ try {
146
+ return await deliverSessionSyncMirror(target, sessionId, turn, text) === true;
147
+ } catch (error) {
148
+ logFailure(`card delivery (${target.channel})`, error);
149
+ return false;
150
+ }
151
+ }));
152
+ };
153
+
154
+ // Saved sync targets and DS Bot bindings share the same card receipt path.
155
+ const deliverToTargets = async (sessionId, targets, text, phase, format, { turn = null, cardText = null } = {}) => {
156
+ if (!Array.isArray(targets) || targets.length === 0) {
157
+ logUndelivered(sessionId, phase, 'no-sync-targets');
158
+ return false;
62
159
  }
63
- const entries = [...unique.entries()];
64
- const results = await Promise.allSettled(entries.map(([, target]) => (
160
+ // Only the final answer has a card renderer; a mirrored user message has no
161
+ // receipt to wait for, so it keeps its text path untouched.
162
+ const rendered = cardText === null
163
+ ? targets.map(() => false)
164
+ : await renderFinalAnswer(targets, sessionId, turn, cardText);
165
+ const pending = targets.filter((_target, index) => !rendered[index]);
166
+ if (pending.length === 0) return true;
167
+ const results = await Promise.allSettled(pending.map((target) => (
65
168
  deliveryService.sendSessionSyncText(
66
- target.botId,
67
- target.targetId,
68
- sessionId,
69
- text,
70
- // Feishu has already tried its dedicated mirror card. Preserve its
71
- // existing plain fallback instead of attempting another rich card.
169
+ target.botId, target.targetId, sessionId, text,
170
+ // Feishu renders its own card; preserve its plain fallback instead of
171
+ // attempting another rich card.
72
172
  { format: target.channel === 'feishu' ? 'plain' : format },
73
173
  )
74
174
  )));
75
- const successful = new Map();
76
175
  results.forEach((result, index) => {
77
- const [key, target] = entries[index];
78
- if (result.status === 'fulfilled') successful.set(key, target);
79
- else logFailure(phase, target, result.reason);
176
+ if (result.status === 'rejected') {
177
+ logFailure(`${phase} (${pending[index].channel})`, result.reason);
178
+ }
80
179
  });
81
- return successful;
180
+ // A confirmed card is a delivered answer even when no text was sent.
181
+ return results.some((result) => result.status === 'fulfilled');
182
+ };
183
+
184
+ // New path: no targets configured, so the address comes from the Session binding.
185
+ const deliverToBinding = async (sessionId, text, phase, format) => {
186
+ const attempt = (value) => deliveryService.deliverSessionText(sessionId, text, { format: value });
187
+ try {
188
+ const result = await attempt(format);
189
+ if (result?.sent === true) return true;
190
+ logUndelivered(sessionId, phase, result?.reason);
191
+ return false;
192
+ } catch (error) {
193
+ logFailure(phase, error);
194
+ // Rich text is an extra: a channel that refuses the markdown rendering
195
+ // would otherwise lose the answer entirely, so the same text goes once
196
+ // more as plain. An uncertain send is never repeated — it may already be
197
+ // visible in the chat.
198
+ if (format === 'plain' || error?.code === 'send-result-unknown' || error?.code === 'cancelled') {
199
+ return false;
200
+ }
201
+ try {
202
+ const fallback = await attempt('plain');
203
+ if (fallback?.sent === true) return true;
204
+ logUndelivered(sessionId, `${phase} (plain fallback)`, fallback?.reason);
205
+ return false;
206
+ } catch (fallbackError) {
207
+ logFailure(`${phase} (plain fallback)`, fallbackError);
208
+ return false;
209
+ }
210
+ }
211
+ };
212
+
213
+ const deliver = async (sessionId, text, phase, format = 'plain', card = null) => {
214
+ // DS Bot bindings can supply sync targets without any saved delivery target,
215
+ // including after rollover when the persisted Session map is still stale.
216
+ const targets = await deliveryService.listSessionSyncTargets?.(sessionId) ?? [];
217
+ if (targets.length > 0 || await botHasSavedTargets(sessionId)) {
218
+ return deliverToTargets(sessionId, targets, text, phase, format, card ?? {});
219
+ }
220
+ return deliverToBinding(sessionId, text, phase, format);
82
221
  };
83
222
 
84
- const processEvent = async (sessionId, event, origin) => {
223
+ const onUserMessage = async (sessionId, state, event, originHint) => {
224
+ if (event.surfaceOp !== 'append') return;
225
+ const origin = classifyTurnInput(event.data?.source, { imOwned: originHint === 'im' });
226
+ // Only a message that says where the reader was may own the turn. A service
227
+ // injection — the runtime context the Host prepends, a reminder, a notice —
228
+ // is often the first message of a turn and says nothing about the reader,
229
+ // so it is remembered as a hint for `turn/end` instead of locking the turn.
230
+ if (MEANINGFUL_ORIGINS.has(origin)) {
231
+ // The chat answers this turn itself as soon as any of its messages came
232
+ // from there, so an IM message outranks an earlier Web one and the whole
233
+ // turn is never delivered; a Web message only claims a turn still free.
234
+ if (origin === TURN_INPUT_ORIGINS.im || state.origin === null) state.origin = origin;
235
+ } else {
236
+ state.sawInternal = true;
237
+ }
238
+ if (state.origin === TURN_INPUT_ORIGINS.im) return;
239
+ // Every message decides its own echo from its own origin: Host framing that
240
+ // appears inside a Web turn never reaches the chat.
241
+ if (origin !== TURN_INPUT_ORIGINS.web) return;
242
+
243
+ const settings = await readSettings(state);
244
+ const text = textFromHarnessContent(event.data?.content);
245
+ if (settings.mirrorUserInput !== true || !text) return;
246
+ // The same text twice in one turn is one echo: a retry or a re-appended
247
+ // input must not arrive in the chat twice.
248
+ if (state.echoed.has(text)) return;
249
+ state.echoed.add(text);
250
+ if (!await deliver(sessionId, withDeliverySyncIcon(settings.inputIcon, text), 'user delivery')) {
251
+ state.echoFailed = true;
252
+ }
253
+ };
254
+
255
+ const onTurnEnd = async (sessionId, state, event) => {
256
+ // A Web turn is mirrored because the reader was there; a turn that locked no
257
+ // meaningful origin is a service turn only when at least one service
258
+ // message announced it. Anything else — no input at all — stays silent.
259
+ const serviceTurn = state.origin === null && state.sawInternal === true;
260
+ const mirroredTurn = state.origin === TURN_INPUT_ORIGINS.web;
261
+ if (!mirroredTurn && !serviceTurn) return;
262
+ const settings = await readSettings(state);
263
+ if (!settings.deliverModelAnswers || !completedTurn(event.data?.reason)) return;
264
+ // An answer the reader cannot connect to their own input is worse than no
265
+ // answer at all: a turn whose input mirror failed stays silent.
266
+ if (state.echoFailed) return;
267
+ const text = state.assistant.text;
268
+ if (!text) return;
269
+ // The card carries the answer itself, so it gets the text without the icon
270
+ // label that marks a delivered message.
271
+ await deliver(
272
+ sessionId,
273
+ withDeliverySyncIcon(settings.modelIcon, text),
274
+ 'assistant delivery',
275
+ 'markdown',
276
+ { turn: state.turn, cardText: text },
277
+ );
278
+ };
279
+
280
+ const processEvent = async (sessionId, event, origin = 'other') => {
85
281
  if (closed || !event || typeof event !== 'object') return;
86
282
 
87
283
  if (event.type === 'turn/start') {
@@ -89,9 +285,11 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
89
285
  if (!Number.isSafeInteger(turn)) return;
90
286
  turns.set(sessionId, {
91
287
  turn,
92
- step: null,
93
- origin: 'unknown',
94
- recipients: null,
288
+ origin: null,
289
+ sawInternal: false,
290
+ settings: null,
291
+ echoed: new Set(),
292
+ echoFailed: false,
95
293
  assistant: new AssistantTextAccumulator(),
96
294
  });
97
295
  return;
@@ -100,83 +298,28 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
100
298
  const state = turns.get(sessionId);
101
299
  if (!state) return;
102
300
 
103
- if (event.type === 'step/start') {
104
- if (event.data?.turn !== undefined && event.data.turn !== state.turn) return;
105
- state.step = Number.isSafeInteger(event.data?.step) ? event.data.step : null;
106
- return;
107
- }
108
-
109
- if (event.type === 'step/end') {
110
- if (event.data?.turn !== undefined && event.data.turn !== state.turn) return;
111
- if (event.data?.step === undefined || event.data.step === state.step) state.step = null;
112
- return;
113
- }
114
-
115
301
  if (event.type === 'user/message') {
116
- if (event.surfaceOp !== 'append') return;
117
- if (state.origin === 'unknown') state.origin = origin;
118
- if (state.origin !== 'dsh' || origin !== 'dsh') return;
119
- const internalInput = ['schedule', 'user-question-reply'].includes(event.data?.source?.kind);
120
- const text = textFromHarnessContent(event.data?.content);
121
- if (!text && !internalInput) return;
122
-
123
- let targets;
124
- try {
125
- targets = await deliveryService.listSessionSyncTargets(sessionId);
126
- } catch (error) {
127
- logFailure('lookup', null, error);
128
- targets = [];
129
- }
130
- // Reminder/question-answer framing is internal: select recipients without echoing it.
131
- // Direct DSH input still requires a successful echo before the final answer.
132
- const recipients = internalInput
133
- ? new Map(targets.filter(validRecipient).map((target) => [recipientKey(target), target]))
134
- : await deliver(sessionId, targets, `${DSH_USER_PREFIX}${text}`, 'user delivery');
135
- if (state.recipients === null) {
136
- state.recipients = recipients;
137
- } else {
138
- for (const key of [...state.recipients.keys()]) {
139
- if (!recipients.has(key)) state.recipients.delete(key);
140
- }
141
- }
302
+ await onUserMessage(sessionId, state, event, origin);
142
303
  return;
143
304
  }
144
305
 
145
- if (event.type === 'assistant/message') {
146
- if (state.origin !== 'dsh' || event.surfaceOp !== 'append'
147
- || event.data?.interrupted === true
148
- || (event.data?.turn !== undefined && event.data.turn !== state.turn)) return;
149
- const text = textFromHarnessContent(event.data?.message?.content);
150
- const step = Number.isSafeInteger(event.data?.step) ? event.data.step : state.step;
151
- state.assistant.setCanonical(step, text);
306
+ // The chat gets the final answer of the turn, not a transcript of it: the
307
+ // accumulator keeps only what arrived after the last tool call.
308
+ if (event.type === 'assistant/message' || event.type === 'assistant/chunk'
309
+ || event.type === 'tool/call') {
310
+ // An IM-owned turn is answered by the chat itself; every other turn keeps
311
+ // its final text, since `turn/end` decides whether it may be delivered.
312
+ if (state.origin === TURN_INPUT_ORIGINS.im) return;
313
+ if (event.surfaceOp !== undefined && event.surfaceOp !== 'append') return;
314
+ if (event.data?.interrupted === true) return;
315
+ if (event.data?.turn !== undefined && event.data.turn !== state.turn) return;
316
+ accumulateFinalAssistantText(state.assistant, event);
152
317
  return;
153
318
  }
154
319
 
155
320
  if (event.type !== 'turn/end' || event.data?.turn !== state.turn) return;
156
321
  turns.delete(sessionId);
157
- if (state.origin !== 'dsh' || !completedTurn(event.data?.reason)
158
- || !state.recipients?.size || !state.assistant.text) return;
159
- // A pending card is not proof of delivery. Only suppress this target's
160
- // text after its renderer confirms the complete final answer is visible.
161
- // Targets without a renderer retain the original text delivery path.
162
- const recipients = [...state.recipients.values()];
163
- const rendered = await Promise.all(recipients.map(async (target) => {
164
- try {
165
- return await deliverSessionSyncMirror(target, sessionId, state.turn, state.assistant.text);
166
- } catch (error) {
167
- logFailure('card delivery', target, error);
168
- return false;
169
- }
170
- }));
171
- const fallback = recipients.filter((_target, index) => !rendered[index]);
172
- if (fallback.length === 0) return;
173
- await deliver(
174
- sessionId,
175
- fallback,
176
- `${DSH_ASSISTANT_PREFIX}${state.assistant.text}`,
177
- 'assistant delivery',
178
- 'markdown',
179
- );
322
+ await onTurnEnd(sessionId, state, event);
180
323
  };
181
324
 
182
325
  const enqueue = (sessionId, event, origin = 'other') => {
@@ -186,7 +329,7 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
186
329
  () => processEvent(sessionId, event, origin),
187
330
  () => processEvent(sessionId, event, origin),
188
331
  );
189
- const tail = task.catch((error) => logFailure('event handling', null, error)).finally(() => {
332
+ const tail = task.catch((error) => logFailure('event handling', error)).finally(() => {
190
333
  if (tails.get(sessionId) === tail) tails.delete(sessionId);
191
334
  });
192
335
  tails.set(sessionId, tail);
@@ -205,21 +348,45 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
205
348
  });
206
349
  }
207
350
 
351
+ /**
352
+ * Whether this input was submitted by the messenger that is currently asking.
353
+ *
354
+ * The registered rpcId is only read here, never claimed: the channel that owns
355
+ * it stays able to consume it, and every later reader of the same event sees
356
+ * the same answer instead of a turn that changes its origin between handlers.
357
+ */
358
+ export function isImOwnedInput(scope, event) {
359
+ const source = event?.data?.source;
360
+ if (source?.kind !== 'user' || typeof source.rpcId !== 'string' || !source.rpcId) return false;
361
+ return isDshImInputOrigin(scope, source.rpcId);
362
+ }
363
+
208
364
  export function installSessionSyncCoordinator(ctx, deliveryService, {
209
365
  logger = console,
210
366
  inputScope = ctx?.root ?? ctx,
367
+ loadSettings = null,
368
+ imInputOwnership = isImOwnedInput,
369
+ config = {},
211
370
  } = {}) {
212
371
  if (typeof ctx?.on !== 'function') {
213
372
  throw new TypeError('Session sync requires Host session events');
214
373
  }
215
- const coordinator = createSessionSyncCoordinator({ deliveryService, logger });
374
+ // The settings page writes this document over RPC; the coordinator reads it
375
+ // once per turn, so a save applies to the next turn without a restart.
376
+ const readSettings = loadSettings ?? (() => getDeliverySyncSettingsStore(config).get());
377
+ const coordinator = createSessionSyncCoordinator({
378
+ deliveryService,
379
+ logger,
380
+ loadSettings: readSettings,
381
+ });
216
382
  const disposeEvent = ctx.on('session/event', (session, event) => {
217
383
  const sessionId = sessionIdOf(session);
218
384
  if (!sessionId) return;
219
- // Origin lookup must be synchronous: the originating ask may clean its id
220
- // immediately after this event callback returns.
221
- const origin = event?.type === 'user/message'
222
- ? userInputOrigin(inputScope, event)
385
+ // Only messenger ownership is decided here, synchronously and without
386
+ // claiming the id; the coordinator classifies the rest of the turn, and a
387
+ // message's origin is read from that same message, never from the turn.
388
+ const origin = event?.type === 'user/message' && imInputOwnership(inputScope, event)
389
+ ? 'im'
223
390
  : 'other';
224
391
  void coordinator.enqueue(sessionId, event, origin);
225
392
  }, { global: true });
@@ -0,0 +1,71 @@
1
+ import {
2
+ configuredSessionSyncTargets,
3
+ sessionSyncTarget,
4
+ } from './delivery-adapter.mjs';
5
+ import { deliverySwitchesOff } from '../../src/channels/shared/delivery-sync-settings.mjs';
6
+ import { getDeliverySyncSettingsStore } from '../../src/channels/shared/delivery-sync-settings-store.mjs';
7
+
8
+ /**
9
+ * Which synced chats of one channel currently mirror `sessionId`.
10
+ *
11
+ * This is the channel's own view of its targets — the Feishu bridge asks it
12
+ * before it draws a process card — and it therefore has to honour the same
13
+ * delivery switches as the coordinator's target path. Both consult
14
+ * `deliverySwitchesOff`, so "both switches off" silences the card and the text
15
+ * together instead of leaving one of the two paths alive.
16
+ *
17
+ * @param options.workspaces - the channel's workspace store.
18
+ * @param options.stateForBotId - async bot state getter, used to read the
19
+ * persisted conversation → Session map.
20
+ * @param options.loadSettings - async settings getter. A document that cannot
21
+ * be read is not a reason to silence the existing mirror, so a failure here
22
+ * keeps the previous behaviour.
23
+ */
24
+ export function createSessionSyncTargetsFor({
25
+ channel,
26
+ workspaces,
27
+ config = {},
28
+ stateForBotId,
29
+ deliveryService = config.deliveryService,
30
+ loadSettings = () => getDeliverySyncSettingsStore(config).get(),
31
+ } = {}) {
32
+ if (typeof channel !== 'string' || !channel) {
33
+ throw new TypeError('a Session sync target resolver needs a channel name');
34
+ }
35
+
36
+ const switchesOff = async () => {
37
+ try {
38
+ return deliverySwitchesOff(await loadSettings());
39
+ } catch {
40
+ return false;
41
+ }
42
+ };
43
+
44
+ return async function sessionSyncTargetsFor(sessionId) {
45
+ if (typeof workspaces?.listSessionSyncTargets !== 'function') return [];
46
+ if (typeof sessionId !== 'string' || !sessionId) return [];
47
+ if (await switchesOff()) return [];
48
+ const matches = [];
49
+ for (const entry of configuredSessionSyncTargets(workspaces)) {
50
+ let state;
51
+ try {
52
+ state = await stateForBotId(entry.botId);
53
+ } catch {
54
+ continue;
55
+ }
56
+ let bound;
57
+ try {
58
+ bound = entry.dsBotId
59
+ ? (await deliveryService?.dsBot?.resolve(entry.dsBotId))?.sessionId
60
+ : state?.snapshot?.().sessions?.[entry.conversationKey];
61
+ } catch {
62
+ continue;
63
+ }
64
+ if (bound !== sessionId) continue;
65
+ const target = sessionSyncTarget(channel, workspaces, entry);
66
+ const openId = target?.route?.openId;
67
+ if (openId) matches.push({ openId, botId: entry.botId, targetId: entry.targetId });
68
+ }
69
+ return matches;
70
+ };
71
+ }
@@ -106,8 +106,7 @@ export function createSidebarSettingsRpcHandler({ config = {}, store, configured
106
106
  }
107
107
 
108
108
  export function installSidebarSettingsRpc(ctx, { config = {} } = {}) {
109
- // Visibility follows ordinary channel management authority. Keep it separate
110
- // from the general settings route, whose TTL operations remain loopback-only.
109
+ // Visibility follows the same authority as channels and general settings.
111
110
  return registerManagementRpc(ctx, SIDEBAR_SETTINGS_RPC_CHANNEL,
112
111
  createSidebarSettingsRpcHandler({ config }), { authority: config.rpcAuthority });
113
112
  }
@@ -44,7 +44,7 @@ export function installUpdateRpc(ctx, options = {}) {
44
44
  const runtime = options.runtime ?? createUpdateRuntime({ ctx, moduleUrl: import.meta.url });
45
45
  const service = options.service ?? createUpdateService({ runtime });
46
46
  const dispose = registerManagementRpc(ctx, UPDATE_RPC_CHANNEL, createUpdateRpcHandler(service), {
47
- authority: 'loopback',
47
+ authority: options.authority,
48
48
  });
49
49
  ctx.effect(() => () => service.close(), 'dsh-im: close update installer');
50
50
  return dispose;
@@ -71,16 +71,38 @@ export function registerManagementRpc(ctx, channel, handler, { authority } = {})
71
71
  });
72
72
  }
73
73
 
74
+ function managementHttpStatus(cause, endpoint) {
75
+ if (Number.isInteger(cause?.status) && cause.status >= 100 && cause.status <= 599) return cause.status;
76
+ // DSH 0.2.x throws a plain Error for HTTP failures. Accept only its exact
77
+ // transport message for this request, never an arbitrary embedded number.
78
+ const prefix = `transport failure for /api/${endpoint}: HTTP `;
79
+ if (!endpoint || typeof cause?.message !== 'string' || !cause.message.startsWith(prefix)) return undefined;
80
+ const status = Number(cause.message.slice(prefix.length));
81
+ return Number.isInteger(status) && status >= 100 && status <= 599 && cause.message === `${prefix}${status}`
82
+ ? status : undefined;
83
+ }
84
+
85
+ function managementErrorMessage(status) {
86
+ if (status === 401) return 'DSH 登录状态无效或已过期,请通过有效启动链接重新登录。';
87
+ if (status === 403) return 'DSH 拒绝了当前管理请求(HTTP 403)。请检查访问权限、可信地址配置及代理设置;若启用了仅本机访问,请按该限制访问。';
88
+ if (status === 404) return 'DSH 管理接口不存在(HTTP 404),请检查 Host 与插件版本及代理路径,重启后重试。';
89
+ if (status >= 500) return 'DSH 管理服务暂时异常,请检查服务状态或稍后重试。';
90
+ return 'DSH 管理请求失败,请检查服务状态和网络连接后重试。';
91
+ }
92
+
74
93
  /** Keep channel UI callers unchanged while using DSH's native correlation and response validation. */
75
94
  export async function callManagementRpc(connection, channel, method, payload, signal) {
95
+ let endpoint;
76
96
  try {
77
- return await connection.rpc.call('/api', rpcEndpoint(channel), { method, payload }, signal);
97
+ endpoint = rpcEndpoint(channel);
98
+ return await connection.rpc.call('/api', endpoint, { method, payload }, signal);
78
99
  } catch (cause) {
79
100
  if (signal?.aborted || cause?.name === 'AbortError') throw cause;
80
- const error = new Error('无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。', { cause });
101
+ const httpStatus = managementHttpStatus(cause, endpoint);
102
+ const error = new Error(managementErrorMessage(httpStatus), { cause });
81
103
  error.code = 'management-unreachable';
82
104
  error.details = { operation: method, stage: 'management.request', occurredAt: new Date().toISOString(),
83
- ...(Number.isInteger(cause?.status) && cause.status >= 100 && cause.status <= 599 ? { httpStatus: cause.status } : {}),
105
+ ...(httpStatus === undefined ? {} : { httpStatus }),
84
106
  };
85
107
  throw error;
86
108
  }