@xmanrui/dsh-im 5.9.1 → 5.11.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 (135) hide show
  1. package/PROACTIVE_DELIVERY.en.md +33 -9
  2. package/PROACTIVE_DELIVERY.md +33 -9
  3. package/README.en.md +42 -7
  4. package/README.md +46 -8
  5. package/bin/dsh-im.mjs +65 -0
  6. package/docs/client-integration.md +4 -0
  7. package/lib/client.js +1735 -203
  8. package/lib/index.js +367 -341
  9. package/package.json +7 -6
  10. package/plugin-src/client/access-policy-settings.js +210 -12
  11. package/plugin-src/client/bot-general-settings.js +44 -3
  12. package/plugin-src/client/delivery-settings.js +2 -0
  13. package/plugin-src/client/delivery-sync-settings.js +269 -0
  14. package/plugin-src/client/global-settings.js +45 -7
  15. package/plugin-src/client/i18n-ru.js +112 -0
  16. package/plugin-src/client/i18n.js +110 -0
  17. package/plugin-src/client/im-channels.js +419 -0
  18. package/plugin-src/client/index.js +50 -2
  19. package/plugin-src/client/model-setting.js +6 -3
  20. package/plugin-src/client/styles.js +23 -7
  21. package/plugin-src/client/update-panel.js +2 -1
  22. package/plugin-src/host/channel-list-rpc.mjs +280 -0
  23. package/plugin-src/host/channels/dingtalk/production.mjs +28 -10
  24. package/plugin-src/host/channels/dingtalk/rpc.mjs +10 -1
  25. package/plugin-src/host/channels/feishu/production.mjs +50 -37
  26. package/plugin-src/host/channels/feishu/rpc.mjs +10 -1
  27. package/plugin-src/host/channels/matrix/production.mjs +28 -10
  28. package/plugin-src/host/channels/matrix/rpc.mjs +10 -0
  29. package/plugin-src/host/channels/qq/production.mjs +30 -11
  30. package/plugin-src/host/channels/qq/rpc.mjs +10 -1
  31. package/plugin-src/host/channels/shared/access-policy-production.mjs +9 -0
  32. package/plugin-src/host/channels/shared/binding-events.mjs +109 -0
  33. package/plugin-src/host/channels/shared/production.mjs +14 -1
  34. package/plugin-src/host/channels/shared/reply-content-rpc.mjs +17 -0
  35. package/plugin-src/host/channels/shared/rpc.mjs +9 -0
  36. package/plugin-src/host/channels/shared/workspace-rpc.mjs +1 -0
  37. package/plugin-src/host/channels/slack/production.mjs +28 -10
  38. package/plugin-src/host/channels/slack/rpc.mjs +10 -0
  39. package/plugin-src/host/channels/telegram/production.mjs +5 -0
  40. package/plugin-src/host/channels/wecom/production.mjs +28 -10
  41. package/plugin-src/host/channels/wecom/rpc.mjs +10 -1
  42. package/plugin-src/host/channels/wecom-app/production.mjs +28 -10
  43. package/plugin-src/host/channels/wecom-app/rpc.mjs +9 -0
  44. package/plugin-src/host/channels/weixin/production.mjs +28 -10
  45. package/plugin-src/host/channels/weixin/rpc.mjs +10 -1
  46. package/plugin-src/host/channels/whatsapp/production.mjs +28 -10
  47. package/plugin-src/host/channels/whatsapp/rpc.mjs +10 -1
  48. package/plugin-src/host/delivery-adapter.mjs +35 -20
  49. package/plugin-src/host/delivery-service.mjs +99 -1
  50. package/plugin-src/host/delivery-suggestions.mjs +31 -1
  51. package/plugin-src/host/delivery-sync-rpc.mjs +100 -0
  52. package/plugin-src/host/harness-connection.mjs +2 -1
  53. package/plugin-src/host/harness-peer.mjs +3 -1
  54. package/plugin-src/host/host-language-rpc.mjs +16 -2
  55. package/plugin-src/host/host-language.mjs +29 -0
  56. package/plugin-src/host/index.mjs +30 -1
  57. package/plugin-src/host/modern-harness-api.mjs +5 -1
  58. package/plugin-src/host/root-scope.mjs +32 -0
  59. package/plugin-src/host/session-sync-coordinator.mjs +290 -122
  60. package/plugin-src/host/session-sync-targets.mjs +71 -0
  61. package/plugin-src/management-rpc.mjs +18 -2
  62. package/scripts/verify-package.mjs +48 -10
  63. package/src/channels/dingtalk/dingtalk-bridge.mjs +50 -6
  64. package/src/channels/dingtalk/state-store.mjs +56 -0
  65. package/src/channels/discord/discord-api.mjs +2 -1
  66. package/src/channels/feishu/bridge.mjs +154 -58
  67. package/src/channels/feishu/feishu-cards.mjs +10 -4
  68. package/src/channels/feishu/feishu-runtime.mjs +11 -3
  69. package/src/channels/feishu/message-utils.mjs +106 -30
  70. package/src/channels/feishu/slash-command-panel.mjs +26 -0
  71. package/src/channels/feishu/state-store.mjs +14 -0
  72. package/src/channels/matrix/matrix-api.mjs +2 -1
  73. package/src/channels/qq/qq-bridge.mjs +114 -14
  74. package/src/channels/qq/state-store.mjs +55 -1
  75. package/src/channels/shared/access-policy.mjs +60 -7
  76. package/src/channels/shared/action-card.mjs +83 -7
  77. package/src/channels/shared/bot-workspace-store.mjs +255 -11
  78. package/src/channels/shared/busy-message-dispatcher.mjs +2 -2
  79. package/src/channels/shared/channel-capabilities.mjs +44 -0
  80. package/src/channels/shared/command-catalog.mjs +68 -3
  81. package/src/channels/shared/command-permission.mjs +6 -2
  82. package/src/channels/shared/conversation-state-store.mjs +16 -0
  83. package/src/channels/shared/deferred-delivery-coordinator.mjs +6 -1
  84. package/src/channels/shared/deferred-delivery.mjs +4 -0
  85. package/src/channels/shared/delivery-sync-settings-store.mjs +86 -0
  86. package/src/channels/shared/delivery-sync-settings.mjs +122 -0
  87. package/src/channels/shared/diagnostic-details.mjs +6 -1
  88. package/src/channels/shared/failure-log-file.mjs +79 -0
  89. package/src/channels/shared/harness-client.mjs +259 -96
  90. package/src/channels/shared/i18n-en/diagnostics.mjs +1 -0
  91. package/src/channels/shared/i18n-en/feishu.mjs +2 -2
  92. package/src/channels/shared/i18n-en/shared-a.mjs +13 -2
  93. package/src/channels/shared/i18n-en/shared-b.mjs +73 -4
  94. package/src/channels/shared/i18n-en/shared-d.mjs +144 -0
  95. package/src/channels/shared/i18n-en/weixin.mjs +4 -0
  96. package/src/channels/shared/i18n-en.mjs +2 -0
  97. package/src/channels/shared/i18n-ru/diagnostics.mjs +1 -0
  98. package/src/channels/shared/i18n-ru/feishu.mjs +2 -2
  99. package/src/channels/shared/i18n-ru/shared-a.mjs +13 -2
  100. package/src/channels/shared/i18n-ru/shared-b.mjs +72 -4
  101. package/src/channels/shared/i18n-ru/shared-d.mjs +144 -0
  102. package/src/channels/shared/i18n-ru/weixin.mjs +4 -0
  103. package/src/channels/shared/i18n-ru.mjs +2 -0
  104. package/src/channels/shared/inbound-access.mjs +10 -0
  105. package/src/channels/shared/interface-language-store.mjs +49 -10
  106. package/src/channels/shared/interface-language.mjs +19 -1
  107. package/src/channels/shared/markdown-chunks.mjs +5 -0
  108. package/src/channels/shared/message-failure.mjs +22 -1
  109. package/src/channels/shared/model-setting.mjs +6 -3
  110. package/src/channels/shared/new-command.mjs +158 -4
  111. package/src/channels/shared/plan-goal-command.mjs +132 -0
  112. package/src/channels/shared/qrcode.mjs +5 -0
  113. package/src/channels/shared/reply-content.mjs +102 -0
  114. package/src/channels/shared/reset-command.mjs +46 -0
  115. package/src/channels/shared/semantic/artifact.mjs +133 -29
  116. package/src/channels/shared/semantic/reply-reference.mjs +18 -3
  117. package/src/channels/shared/session-nav-command.mjs +999 -0
  118. package/src/channels/shared/session-ring-support.mjs +184 -0
  119. package/src/channels/shared/session-ring.mjs +202 -0
  120. package/src/channels/shared/session-title.mjs +11 -0
  121. package/src/channels/shared/status-command.mjs +2 -1
  122. package/src/channels/shared/text-harness-bridge.mjs +166 -7
  123. package/src/channels/shared/workspace-command.mjs +567 -31
  124. package/src/channels/shared/workspace-session.mjs +52 -4
  125. package/src/channels/slack/slack-api.mjs +2 -1
  126. package/src/channels/telegram/config-store.mjs +10 -2
  127. package/src/channels/telegram/telegram-api.mjs +19 -1
  128. package/src/channels/telegram/telegram-rich-message.mjs +17 -5
  129. package/src/channels/telegram/telegram-runtime.mjs +14 -1
  130. package/src/channels/wecom/state-store.mjs +13 -1
  131. package/src/channels/wecom/wecom-bridge.mjs +183 -26
  132. package/src/channels/wecom-app/state-store.mjs +13 -1
  133. package/src/channels/wecom-app/wecom-app-bridge.mjs +44 -4
  134. package/src/channels/weixin/state-store.mjs +13 -1
  135. package/src/channels/weixin/weixin-bridge.mjs +71 -4
@@ -1,87 +1,284 @@
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';
14
+ import { rootScope } from './root-scope.mjs';
15
+
16
+ /**
17
+ * Where the turn came from, as far as a chat mirror is concerned.
18
+ *
19
+ * - `im`: the turn was started by a message from this very messenger. Its
20
+ * answer is already rendered there, so nothing is delivered.
21
+ * - `web`: the reader typed in the DSH Web GUI. Their own input may be mirrored
22
+ * into the chat, and the answer may be delivered.
23
+ * - `internal`: a service started the turn — a schedule reminder, an answered
24
+ * question, a notice such as `subagent-settled`, or the context the Host
25
+ * injects into every turn. The framing is internal and is never echoed, and
26
+ * it never decides where the turn came from: only a turn that locked no
27
+ * meaningful origin at all is delivered as a service turn.
28
+ */
29
+ export const TURN_INPUT_ORIGINS = Object.freeze({ im: 'im', web: 'web', internal: 'internal' });
30
+
31
+ /** Origins that may own a turn; `internal` is a fact about one message, not the turn. */
32
+ const MEANINGFUL_ORIGINS = new Set([TURN_INPUT_ORIGINS.im, TURN_INPUT_ORIGINS.web]);
7
33
 
8
- const DSH_USER_PREFIX = '[来自 DSH]\n';
9
- const DSH_ASSISTANT_PREFIX = '[DSH 助手]\n\n';
34
+ /** Kinds whose turn is started by the Host rather than by a reader. */
35
+ const INTERNAL_KINDS = new Set(['schedule', 'user-question-reply']);
10
36
 
11
37
  function completedTurn(reason) {
12
38
  return (typeof reason === 'string' ? reason : reason?.kind) === 'completed';
13
39
  }
14
40
 
15
- function recipientKey(target) {
16
- return JSON.stringify([target.channel, target.botId, target.targetId]);
17
- }
18
-
19
41
  function sessionIdOf(session) {
20
42
  const value = session?.id ?? session?.sessionId;
21
43
  return typeof value === 'string' && value ? value : null;
22
44
  }
23
45
 
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';
46
+ /**
47
+ * Classify one `user/message` by the source of that very message.
48
+ *
49
+ * `imOwned` is the answer of `isDshImInputOrigin` for this message: only the
50
+ * messenger that received the input has its rpcId registered, so everything
51
+ * else is a different origin even though DSH models both as `kind: 'user'`.
52
+ * The lookup is non-destructive, so it never races the channel that owns the
53
+ * id and never turns the same messenger turn into a mirrored one.
54
+ */
55
+ export function classifyTurnInput(source, { imOwned = false } = {}) {
56
+ // A notice is Host framing whatever its kind says; `subagent-settled` and
57
+ // future notice kinds must never be echoed as if the reader had typed them.
58
+ if (source?.form === 'notice') return 'internal';
59
+ if (INTERNAL_KINDS.has(source?.kind)) return 'internal';
60
+ if (source?.kind !== 'user') return 'internal';
61
+ return imOwned ? 'im' : 'web';
31
62
  }
32
63
 
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
- }
64
+ /**
65
+ * Settings used when the document cannot be read at all.
66
+ *
67
+ * A snapshot that cannot be loaded is not a reason to start mirroring: both
68
+ * switches are held off, so a broken or unreadable file fails closed and the
69
+ * chat simply receives nothing until the document is readable again.
70
+ */
71
+ const UNREADABLE_SETTINGS = Object.freeze({
72
+ ...DEFAULT_DELIVERY_SYNC_SETTINGS,
73
+ mirrorUserInput: false,
74
+ deliverModelAnswers: false,
75
+ });
39
76
 
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');
77
+ /**
78
+ * @param options.loadSettings - Async getter of the delivery-sync settings
79
+ * document. Read once per turn. A failure is logged and mirrored nowhere: the
80
+ * reader asked for no mirroring by default, so an unreadable document must
81
+ * never become one.
82
+ */
83
+ export function createSessionSyncCoordinator({
84
+ deliveryService,
85
+ logger = console,
86
+ loadSettings = null,
87
+ } = {}) {
88
+ if (typeof deliveryService?.deliverSessionText !== 'function') {
89
+ throw new TypeError('Session sync requires a delivery service that can follow a Session binding');
44
90
  }
45
91
 
46
92
  const turns = new Map();
47
93
  const tails = new Map();
48
94
  let closed = false;
49
95
 
50
- const logFailure = (phase, target, error) => {
96
+ const logFailure = (phase, error) => {
51
97
  logger.warn?.(
52
98
  `[dsh-im] ignored Session sync ${phase} failure`
53
- + (target ? ` (${target.channel}/${target.botId}/${target.targetId})` : '')
54
99
  + ` [${error?.code ?? error?.name ?? 'unknown-error'}]`,
55
100
  );
56
101
  };
57
102
 
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);
103
+ const logUndelivered = (sessionId, phase, reason) => {
104
+ // The address comes from the binding, so there is nothing secret to hide
105
+ // here, but the message text never appears in a log line.
106
+ logger.warn?.(
107
+ `[dsh-im] Session sync ${phase} found no delivery address`
108
+ + ` [${reason ?? 'no-reason'}] session=${sessionId}`,
109
+ );
110
+ };
111
+
112
+ const readSettings = async (state) => {
113
+ if (state.settings) return state.settings;
114
+ try {
115
+ const value = typeof loadSettings === 'function'
116
+ ? await loadSettings()
117
+ : DEFAULT_DELIVERY_SYNC_SETTINGS;
118
+ state.settings = normalizeDeliverySyncSettings(value) ?? DEFAULT_DELIVERY_SYNC_SETTINGS;
119
+ } catch (error) {
120
+ logFailure('settings', error);
121
+ state.settings = UNREADABLE_SETTINGS;
122
+ }
123
+ return state.settings;
124
+ };
125
+
126
+ // Saved targets keep control of delivery even when all their sync switches
127
+ // are off; an empty sync list must not bypass them through the binding path.
128
+ const botHasSavedTargets = async (sessionId) => {
129
+ try {
130
+ const described = await deliveryService.describeConversation(sessionId);
131
+ if (!described) return false;
132
+ const listed = await deliveryService.listTargets(described.botId);
133
+ return Array.isArray(listed?.targets) && listed.targets.length > 0;
134
+ } catch {
135
+ return false;
136
+ }
137
+ };
138
+
139
+ // A channel may render the answer itself — the Feishu process card does — so a
140
+ // target is not automatically a text recipient. A pending card is not proof of
141
+ // delivery either: the renderer is asked first and only the targets it did not
142
+ // confirm receive the text. Targets without a renderer keep the text path.
143
+ const renderFinalAnswer = async (targets, sessionId, turn, text) => {
144
+ if (!Number.isSafeInteger(turn)) return targets.map(() => false);
145
+ return await Promise.all(targets.map(async (target) => {
146
+ try {
147
+ return await deliverSessionSyncMirror(target, sessionId, turn, text) === true;
148
+ } catch (error) {
149
+ logFailure(`card delivery (${target.channel})`, error);
150
+ return false;
151
+ }
152
+ }));
153
+ };
154
+
155
+ // Saved sync targets and DS Bot bindings share the same card receipt path.
156
+ const deliverToTargets = async (sessionId, targets, text, phase, format, { turn = null, cardText = null } = {}) => {
157
+ if (!Array.isArray(targets) || targets.length === 0) {
158
+ logUndelivered(sessionId, phase, 'no-sync-targets');
159
+ return false;
62
160
  }
63
- const entries = [...unique.entries()];
64
- const results = await Promise.allSettled(entries.map(([, target]) => (
161
+ // Only the final answer has a card renderer; a mirrored user message has no
162
+ // receipt to wait for, so it keeps its text path untouched.
163
+ const rendered = cardText === null
164
+ ? targets.map(() => false)
165
+ : await renderFinalAnswer(targets, sessionId, turn, cardText);
166
+ const pending = targets.filter((_target, index) => !rendered[index]);
167
+ if (pending.length === 0) return true;
168
+ const results = await Promise.allSettled(pending.map((target) => (
65
169
  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.
170
+ target.botId, target.targetId, sessionId, text,
171
+ // Feishu renders its own card; preserve its plain fallback instead of
172
+ // attempting another rich card.
72
173
  { format: target.channel === 'feishu' ? 'plain' : format },
73
174
  )
74
175
  )));
75
- const successful = new Map();
76
176
  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);
177
+ if (result.status === 'rejected') {
178
+ logFailure(`${phase} (${pending[index].channel})`, result.reason);
179
+ }
80
180
  });
81
- return successful;
181
+ // A confirmed card is a delivered answer even when no text was sent.
182
+ return results.some((result) => result.status === 'fulfilled');
183
+ };
184
+
185
+ // New path: no targets configured, so the address comes from the Session binding.
186
+ const deliverToBinding = async (sessionId, text, phase, format) => {
187
+ const attempt = (value) => deliveryService.deliverSessionText(sessionId, text, { format: value });
188
+ try {
189
+ const result = await attempt(format);
190
+ if (result?.sent === true) return true;
191
+ logUndelivered(sessionId, phase, result?.reason);
192
+ return false;
193
+ } catch (error) {
194
+ logFailure(phase, error);
195
+ // Rich text is an extra: a channel that refuses the markdown rendering
196
+ // would otherwise lose the answer entirely, so the same text goes once
197
+ // more as plain. An uncertain send is never repeated — it may already be
198
+ // visible in the chat.
199
+ if (format === 'plain' || error?.code === 'send-result-unknown' || error?.code === 'cancelled') {
200
+ return false;
201
+ }
202
+ try {
203
+ const fallback = await attempt('plain');
204
+ if (fallback?.sent === true) return true;
205
+ logUndelivered(sessionId, `${phase} (plain fallback)`, fallback?.reason);
206
+ return false;
207
+ } catch (fallbackError) {
208
+ logFailure(`${phase} (plain fallback)`, fallbackError);
209
+ return false;
210
+ }
211
+ }
212
+ };
213
+
214
+ const deliver = async (sessionId, text, phase, format = 'plain', card = null) => {
215
+ // DS Bot bindings can supply sync targets without any saved delivery target,
216
+ // including after rollover when the persisted Session map is still stale.
217
+ const targets = await deliveryService.listSessionSyncTargets?.(sessionId) ?? [];
218
+ if (targets.length > 0 || await botHasSavedTargets(sessionId)) {
219
+ return deliverToTargets(sessionId, targets, text, phase, format, card ?? {});
220
+ }
221
+ return deliverToBinding(sessionId, text, phase, format);
82
222
  };
83
223
 
84
- const processEvent = async (sessionId, event, origin) => {
224
+ const onUserMessage = async (sessionId, state, event, originHint) => {
225
+ if (event.surfaceOp !== 'append') return;
226
+ const origin = classifyTurnInput(event.data?.source, { imOwned: originHint === 'im' });
227
+ // Only a message that says where the reader was may own the turn. A service
228
+ // injection — the runtime context the Host prepends, a reminder, a notice —
229
+ // is often the first message of a turn and says nothing about the reader,
230
+ // so it is remembered as a hint for `turn/end` instead of locking the turn.
231
+ if (MEANINGFUL_ORIGINS.has(origin)) {
232
+ // The chat answers this turn itself as soon as any of its messages came
233
+ // from there, so an IM message outranks an earlier Web one and the whole
234
+ // turn is never delivered; a Web message only claims a turn still free.
235
+ if (origin === TURN_INPUT_ORIGINS.im || state.origin === null) state.origin = origin;
236
+ } else {
237
+ state.sawInternal = true;
238
+ }
239
+ if (state.origin === TURN_INPUT_ORIGINS.im) return;
240
+ // Every message decides its own echo from its own origin: Host framing that
241
+ // appears inside a Web turn never reaches the chat.
242
+ if (origin !== TURN_INPUT_ORIGINS.web) return;
243
+
244
+ const settings = await readSettings(state);
245
+ const text = textFromHarnessContent(event.data?.content);
246
+ if (settings.mirrorUserInput !== true || !text) return;
247
+ // The same text twice in one turn is one echo: a retry or a re-appended
248
+ // input must not arrive in the chat twice.
249
+ if (state.echoed.has(text)) return;
250
+ state.echoed.add(text);
251
+ if (!await deliver(sessionId, withDeliverySyncIcon(settings.inputIcon, text), 'user delivery')) {
252
+ state.echoFailed = true;
253
+ }
254
+ };
255
+
256
+ const onTurnEnd = async (sessionId, state, event) => {
257
+ // A Web turn is mirrored because the reader was there; a turn that locked no
258
+ // meaningful origin is a service turn only when at least one service
259
+ // message announced it. Anything else — no input at all — stays silent.
260
+ const serviceTurn = state.origin === null && state.sawInternal === true;
261
+ const mirroredTurn = state.origin === TURN_INPUT_ORIGINS.web;
262
+ if (!mirroredTurn && !serviceTurn) return;
263
+ const settings = await readSettings(state);
264
+ if (!settings.deliverModelAnswers || !completedTurn(event.data?.reason)) return;
265
+ // An answer the reader cannot connect to their own input is worse than no
266
+ // answer at all: a turn whose input mirror failed stays silent.
267
+ if (state.echoFailed) return;
268
+ const text = state.assistant.text;
269
+ if (!text) return;
270
+ // The card carries the answer itself, so it gets the text without the icon
271
+ // label that marks a delivered message.
272
+ await deliver(
273
+ sessionId,
274
+ withDeliverySyncIcon(settings.modelIcon, text),
275
+ 'assistant delivery',
276
+ 'markdown',
277
+ { turn: state.turn, cardText: text },
278
+ );
279
+ };
280
+
281
+ const processEvent = async (sessionId, event, origin = 'other') => {
85
282
  if (closed || !event || typeof event !== 'object') return;
86
283
 
87
284
  if (event.type === 'turn/start') {
@@ -89,9 +286,11 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
89
286
  if (!Number.isSafeInteger(turn)) return;
90
287
  turns.set(sessionId, {
91
288
  turn,
92
- step: null,
93
- origin: 'unknown',
94
- recipients: null,
289
+ origin: null,
290
+ sawInternal: false,
291
+ settings: null,
292
+ echoed: new Set(),
293
+ echoFailed: false,
95
294
  assistant: new AssistantTextAccumulator(),
96
295
  });
97
296
  return;
@@ -100,83 +299,28 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
100
299
  const state = turns.get(sessionId);
101
300
  if (!state) return;
102
301
 
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
302
  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
- }
303
+ await onUserMessage(sessionId, state, event, origin);
142
304
  return;
143
305
  }
144
306
 
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);
307
+ // The chat gets the final answer of the turn, not a transcript of it: the
308
+ // accumulator keeps only what arrived after the last tool call.
309
+ if (event.type === 'assistant/message' || event.type === 'assistant/chunk'
310
+ || event.type === 'tool/call') {
311
+ // An IM-owned turn is answered by the chat itself; every other turn keeps
312
+ // its final text, since `turn/end` decides whether it may be delivered.
313
+ if (state.origin === TURN_INPUT_ORIGINS.im) return;
314
+ if (event.surfaceOp !== undefined && event.surfaceOp !== 'append') return;
315
+ if (event.data?.interrupted === true) return;
316
+ if (event.data?.turn !== undefined && event.data.turn !== state.turn) return;
317
+ accumulateFinalAssistantText(state.assistant, event);
152
318
  return;
153
319
  }
154
320
 
155
321
  if (event.type !== 'turn/end' || event.data?.turn !== state.turn) return;
156
322
  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
- );
323
+ await onTurnEnd(sessionId, state, event);
180
324
  };
181
325
 
182
326
  const enqueue = (sessionId, event, origin = 'other') => {
@@ -186,7 +330,7 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
186
330
  () => processEvent(sessionId, event, origin),
187
331
  () => processEvent(sessionId, event, origin),
188
332
  );
189
- const tail = task.catch((error) => logFailure('event handling', null, error)).finally(() => {
333
+ const tail = task.catch((error) => logFailure('event handling', error)).finally(() => {
190
334
  if (tails.get(sessionId) === tail) tails.delete(sessionId);
191
335
  });
192
336
  tails.set(sessionId, tail);
@@ -205,21 +349,45 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
205
349
  });
206
350
  }
207
351
 
352
+ /**
353
+ * Whether this input was submitted by the messenger that is currently asking.
354
+ *
355
+ * The registered rpcId is only read here, never claimed: the channel that owns
356
+ * it stays able to consume it, and every later reader of the same event sees
357
+ * the same answer instead of a turn that changes its origin between handlers.
358
+ */
359
+ export function isImOwnedInput(scope, event) {
360
+ const source = event?.data?.source;
361
+ if (source?.kind !== 'user' || typeof source.rpcId !== 'string' || !source.rpcId) return false;
362
+ return isDshImInputOrigin(scope, source.rpcId);
363
+ }
364
+
208
365
  export function installSessionSyncCoordinator(ctx, deliveryService, {
209
366
  logger = console,
210
- inputScope = ctx?.root ?? ctx,
367
+ inputScope = rootScope(ctx),
368
+ loadSettings = null,
369
+ imInputOwnership = isImOwnedInput,
370
+ config = {},
211
371
  } = {}) {
212
372
  if (typeof ctx?.on !== 'function') {
213
373
  throw new TypeError('Session sync requires Host session events');
214
374
  }
215
- const coordinator = createSessionSyncCoordinator({ deliveryService, logger });
375
+ // The settings page writes this document over RPC; the coordinator reads it
376
+ // once per turn, so a save applies to the next turn without a restart.
377
+ const readSettings = loadSettings ?? (() => getDeliverySyncSettingsStore(config).get());
378
+ const coordinator = createSessionSyncCoordinator({
379
+ deliveryService,
380
+ logger,
381
+ loadSettings: readSettings,
382
+ });
216
383
  const disposeEvent = ctx.on('session/event', (session, event) => {
217
384
  const sessionId = sessionIdOf(session);
218
385
  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)
386
+ // Only messenger ownership is decided here, synchronously and without
387
+ // claiming the id; the coordinator classifies the rest of the turn, and a
388
+ // message's origin is read from that same message, never from the turn.
389
+ const origin = event?.type === 'user/message' && imInputOwnership(inputScope, event)
390
+ ? 'im'
223
391
  : 'other';
224
392
  void coordinator.enqueue(sessionId, event, origin);
225
393
  }, { 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
+ }
@@ -37,14 +37,30 @@ function reply(rpcId, result) {
37
37
  return Response.json({ type: 'server-response', rpcId, result: value });
38
38
  }
39
39
 
40
+ function resolveFetchRegistry(ctx) {
41
+ // `ctx.connection` may be a Cordis service proxy whose `fetch` is a getter.
42
+ // Reading it once inside try/catch both triggers the getter and tolerates a
43
+ // proxy that has not resolved yet; fall back to an explicitly resolved service.
44
+ const candidates = [];
45
+ try { candidates.push(ctx?.connection); } catch { /* unresolved proxy */ }
46
+ try { candidates.push(ctx?.get?.('connection')); } catch { /* service not ready */ }
47
+ for (const connection of candidates) {
48
+ if (!connection) continue;
49
+ let registry;
50
+ try { registry = connection.fetch; } catch { continue; }
51
+ if (typeof registry?.register === 'function') return registry;
52
+ }
53
+ return null;
54
+ }
40
55
  /** Register an IM channel through the public /api carrier shared by supported DSH releases. */
41
56
  export function registerManagementRpc(ctx, channel, handler, { authority } = {}) {
42
57
  const policy = resolveRpcAuthority(authority);
43
58
  const endpoint = rpcEndpoint(channel);
44
- if (typeof ctx?.connection?.fetch?.register !== 'function') {
59
+ const registry = resolveFetchRegistry(ctx);
60
+ if (typeof registry?.register !== 'function') {
45
61
  throw new TypeError('DSH Host Connection Fetch registry is required');
46
62
  }
47
- return ctx.connection.fetch.register({
63
+ return registry.register({
48
64
  path: `/api/${endpoint}`,
49
65
  methods: ['POST'],
50
66
  requestBody: 'buffered',