@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
|
@@ -1,87 +1,283 @@
|
|
|
1
1
|
import {
|
|
2
|
+
accumulateFinalAssistantText,
|
|
2
3
|
AssistantTextAccumulator,
|
|
3
|
-
|
|
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
|
-
|
|
9
|
-
|
|
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
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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,
|
|
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
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
-
|
|
64
|
-
|
|
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
|
-
|
|
68
|
-
|
|
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
|
-
|
|
78
|
-
|
|
79
|
-
|
|
176
|
+
if (result.status === 'rejected') {
|
|
177
|
+
logFailure(`${phase} (${pending[index].channel})`, result.reason);
|
|
178
|
+
}
|
|
80
179
|
});
|
|
81
|
-
|
|
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
|
|
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
|
-
|
|
93
|
-
|
|
94
|
-
|
|
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
|
-
|
|
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
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
state.
|
|
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
|
-
|
|
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',
|
|
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
|
-
|
|
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
|
-
//
|
|
220
|
-
//
|
|
221
|
-
|
|
222
|
-
|
|
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
|
+
}
|
|
@@ -149,26 +149,33 @@ if (client.includes('settings.plugins.tab') || clientSources.includes('settings.
|
|
|
149
149
|
// Connections still have no channel-enable toggle. Checkable inputs are owned
|
|
150
150
|
// only by the shared context editor, the saved-target Session sync row, the
|
|
151
151
|
// email settings, the Telegram thinking-traces block, Feishu panel settings,
|
|
152
|
-
//
|
|
152
|
+
// the conversation-directory settings form, and the general Delivery tab.
|
|
153
153
|
// The context editor contains one switch template and one mapped field-input
|
|
154
154
|
// template; the delivery target adds one ordinary checkbox template; the
|
|
155
155
|
// Telegram thinking-traces block adds two ordinary checkbox templates (traces
|
|
156
156
|
// and frame numbering). General settings adds one mapped switch template for
|
|
157
157
|
// the two Feishu panel preferences. Conversation-directory settings adds one
|
|
158
|
-
// switch template reused for the bot override and channel default.
|
|
158
|
+
// switch template reused for the bot override and channel default. The Delivery
|
|
159
|
+
// tab adds one ordinary checkbox template mapped over its two switches (mirror
|
|
160
|
+
// Web input, deliver model answers).
|
|
159
161
|
const contextEditorSource = await readFile(resolve(root, 'plugin-src/client/context-enhancement.js'), 'utf8');
|
|
160
162
|
const deliverySettingsSource = await readFile(resolve(root, 'plugin-src/client/delivery-settings.js'), 'utf8');
|
|
161
163
|
const emailSettingsSource = await readFile(resolve(root, 'plugin-src/client/channels/email/index.js'), 'utf8');
|
|
162
164
|
const thinkingTracesSource = await readFile(resolve(root, 'plugin-src/client/channels/telegram/thinking-traces.js'), 'utf8');
|
|
163
165
|
const botGeneralSettingsSource = await readFile(resolve(root, 'plugin-src/client/bot-general-settings.js'), 'utf8');
|
|
164
166
|
const conversationDirectorySettingsSource = await readFile(resolve(root, 'plugin-src/client/channels/feishu/conversation-directory-settings.js'), 'utf8');
|
|
167
|
+
const deliverySyncSettingsSource = await readFile(
|
|
168
|
+
resolve(root, 'plugin-src/client/delivery-sync-settings.js'),
|
|
169
|
+
'utf8',
|
|
170
|
+
);
|
|
165
171
|
const otherClientSources = clientSources
|
|
166
172
|
.replace(contextEditorSource, '')
|
|
167
173
|
.replace(deliverySettingsSource, '')
|
|
168
174
|
.replace(emailSettingsSource, '')
|
|
169
175
|
.replace(thinkingTracesSource, '')
|
|
170
176
|
.replace(botGeneralSettingsSource, '')
|
|
171
|
-
.replace(conversationDirectorySettingsSource, '')
|
|
177
|
+
.replace(conversationDirectorySettingsSource, '')
|
|
178
|
+
.replace(deliverySyncSettingsSource, '');
|
|
172
179
|
if (/role:\s*["']switch|type:\s*["']checkbox/.test(otherClientSources)
|
|
173
180
|
|| (deliverySettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
|
|
174
181
|
|| /role:\s*["']switch["']/u.test(deliverySettingsSource)
|
|
@@ -178,9 +185,11 @@ if (/role:\s*["']switch|type:\s*["']checkbox/.test(otherClientSources)
|
|
|
178
185
|
|| (botGeneralSettingsSource.match(/role:\s*["']switch["']/g) ?? []).length !== 1
|
|
179
186
|
|| (conversationDirectorySettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
|
|
180
187
|
|| (conversationDirectorySettingsSource.match(/role:\s*["']switch["']/g) ?? []).length !== 1
|
|
188
|
+
|| (deliverySyncSettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
|
|
189
|
+
|| /role:\s*["']switch["']/u.test(deliverySyncSettingsSource)
|
|
181
190
|
|| (client.match(/role:\s*["']switch["']/g) ?? []).length !== 3
|
|
182
|
-
|| (client.match(/type:\s*["']checkbox["']/g) ?? []).length !==
|
|
183
|
-
throw new Error('checkable inputs must be limited to context enhancement, Session sync, email settings, Telegram thinking traces, Feishu panel settings,
|
|
191
|
+
|| (client.match(/type:\s*["']checkbox["']/g) ?? []).length !== 8) {
|
|
192
|
+
throw new Error('checkable inputs must be limited to context enhancement, Session sync, email settings, Telegram thinking traces, Feishu panel settings, conversation-directory settings, and the Delivery tab');
|
|
184
193
|
}
|
|
185
194
|
for (const marker of ['bot.conversation-directory.set', 'bot.conversation-directory.default.set']) {
|
|
186
195
|
if (!host.includes(marker) || !client.includes(marker)) {
|
|
@@ -1302,6 +1302,15 @@ export class QqHarnessBridge {
|
|
|
1302
1302
|
let answer;
|
|
1303
1303
|
let artifacts = [];
|
|
1304
1304
|
try {
|
|
1305
|
+
try {
|
|
1306
|
+
await this.#state.rememberAuthor?.(key, {
|
|
1307
|
+
senderId: sender,
|
|
1308
|
+
senderName: message.kind === 'group' ? message.senderName : undefined,
|
|
1309
|
+
isBot: message.senderIsBot === true,
|
|
1310
|
+
});
|
|
1311
|
+
} catch (error) {
|
|
1312
|
+
this.#logger.warn?.('[dsh-im:qq] unable to remember the conversation author:', error?.message ?? error);
|
|
1313
|
+
}
|
|
1305
1314
|
// Persist consumption before handing the prompt to Harness. Provider
|
|
1306
1315
|
// redelivery after a failed error notice must never execute it twice.
|
|
1307
1316
|
await markMessageSeen();
|