@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.
- package/PROACTIVE_DELIVERY.en.md +33 -9
- package/PROACTIVE_DELIVERY.md +33 -9
- package/README.en.md +6 -3
- package/README.md +7 -4
- package/lib/client.js +582 -130
- package/lib/index.js +325 -325
- 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/inbound-ttl-rpc.mjs +1 -1
- package/plugin-src/host/index.mjs +23 -1
- package/plugin-src/host/session-sync-coordinator.mjs +288 -121
- package/plugin-src/host/session-sync-targets.mjs +71 -0
- package/plugin-src/host/sidebar-settings.mjs +1 -2
- package/plugin-src/host/update-rpc.mjs +1 -1
- package/plugin-src/management-rpc.mjs +25 -3
- package/scripts/verify-lan-management.mjs +58 -5
- package/scripts/verify-package.mjs +14 -5
- package/src/channels/email/email-runtime.mjs +27 -8
- package/src/channels/feishu/bridge.mjs +250 -3
- 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 +7 -1
- package/src/channels/shared/i18n-en/feishu.mjs +3 -0
- package/src/channels/shared/i18n-en/shared-b.mjs +6 -0
- package/src/channels/shared/i18n-ru/diagnostics.mjs +11 -0
- package/src/channels/shared/i18n-ru/feishu.mjs +2 -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
|
@@ -16,8 +16,8 @@ const pluginRoot = resolve(import.meta.dirname, '..');
|
|
|
16
16
|
const cli = resolve(harnessRoot, 'apps/cli/lib/bin.js');
|
|
17
17
|
await access(cli);
|
|
18
18
|
await access(join(pluginRoot, 'lib/index.js'));
|
|
19
|
-
//
|
|
20
|
-
//
|
|
19
|
+
// Exercise the original HTTP carrier with trusted LAN authorities while keeping
|
|
20
|
+
// TCP local. A second-device browser and a real proxy need separate validation.
|
|
21
21
|
const lanIp = '192.168.1.100';
|
|
22
22
|
const domain = 'dsh.example.test';
|
|
23
23
|
|
|
@@ -132,6 +132,47 @@ function expectStatus(name, response, expected, businessOk = false) {
|
|
|
132
132
|
results.push({ check: name, status: response.status, result: 'PASS' });
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
+
const settings = [
|
|
136
|
+
['inbound-ttl', { ttlHours: 48 }],
|
|
137
|
+
['image-input', { maxDownloadMb: 30, maxImageMb: 6, maxTotalMb: 20, maxImages: 20 }],
|
|
138
|
+
['group-history', { groupHistoryRetentionDays: 21 }],
|
|
139
|
+
];
|
|
140
|
+
const protectedMethods = [
|
|
141
|
+
...settings.flatMap(([setting, value]) => [
|
|
142
|
+
['dsh-im-settings', `settings.${setting}.get`, {}],
|
|
143
|
+
['dsh-im-settings', `settings.${setting}.set`, value],
|
|
144
|
+
]),
|
|
145
|
+
['dsh-im-settings', 'settings.inbound-ttl.sweep', {}],
|
|
146
|
+
['dsh-im', 'update.status', {}],
|
|
147
|
+
['dsh-im', 'update.check', {}],
|
|
148
|
+
['dsh-im', 'update.install', { checkId: 'not-confirmed', requestId: 'must-not-install' }],
|
|
149
|
+
];
|
|
150
|
+
|
|
151
|
+
async function verifyDenied(name, browser, status, headers = {}) {
|
|
152
|
+
for (const [channel, method, payload] of protectedMethods) {
|
|
153
|
+
expectStatus(`${name}: ${method}`, await rpc(browser, channel, method, headers, payload), status);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function verifySettings(name, browser, persisted = false) {
|
|
158
|
+
for (const [setting, value] of settings) {
|
|
159
|
+
const read = await rpc(browser, 'dsh-im-settings', `settings.${setting}.get`);
|
|
160
|
+
expectStatus(`${name}: ${setting} read`, read, 200, true);
|
|
161
|
+
if (persisted) assert.deepEqual(JSON.parse(read.body).result.value, value, `${name}: settings survive restart`);
|
|
162
|
+
const saved = await rpc(browser, 'dsh-im-settings', `settings.${setting}.set`, {}, value);
|
|
163
|
+
expectStatus(`${name}: ${setting} save`, saved, 200, true);
|
|
164
|
+
assert.deepEqual(JSON.parse(saved.body).result.value, value);
|
|
165
|
+
const reread = await rpc(browser, 'dsh-im-settings', `settings.${setting}.get`);
|
|
166
|
+
expectStatus(`${name}: ${setting} reread`, reread, 200, true);
|
|
167
|
+
assert.deepEqual(JSON.parse(reread.body).result.value, value);
|
|
168
|
+
}
|
|
169
|
+
expectStatus(`${name}: sweep empty test home`, await rpc(browser, 'dsh-im-settings', 'settings.inbound-ttl.sweep'), 200, true);
|
|
170
|
+
const update = await rpc(browser, 'dsh-im', 'update.status');
|
|
171
|
+
expectStatus(`${name}: update status`, update, 200, true);
|
|
172
|
+
assert.equal(JSON.parse(update.body).result.value.canInstall, false, 'status alone must never authorize installation');
|
|
173
|
+
expectStatus(`${name}: sidebar`, await rpc(browser, 'dsh-im-sidebar', 'settings.sidebar-entry.get'), 200, true);
|
|
174
|
+
}
|
|
175
|
+
|
|
135
176
|
try {
|
|
136
177
|
await mkdir(profile, { recursive: true });
|
|
137
178
|
const packages = {
|
|
@@ -161,7 +202,7 @@ try {
|
|
|
161
202
|
headers: { cookie: lan.cookie },
|
|
162
203
|
}), 200);
|
|
163
204
|
const channels = ['feishu', 'weixin', 'dingtalk', 'wecom', 'wecom-app', 'qq',
|
|
164
|
-
'slack', 'telegram', 'discord', 'whatsapp', 'imessage', 'matrix', 'office'];
|
|
205
|
+
'slack', 'telegram', 'discord', 'whatsapp', 'imessage', 'email', 'matrix', 'office'];
|
|
165
206
|
for (const channel of channels) {
|
|
166
207
|
expectStatus(`LAN default: ${channel}`, await readyStatus(lan, channel), 200, true);
|
|
167
208
|
}
|
|
@@ -171,8 +212,12 @@ try {
|
|
|
171
212
|
expectStatus('LAN forged cookie', await rpc({ ...lan, cookie: 'invalid=invalid' }), 401);
|
|
172
213
|
expectStatus('Untrusted Host', await rpc(lan, 'feishu', 'connection.status', { host: 'untrusted.invalid' }), 403);
|
|
173
214
|
expectStatus('Cross-origin request', await rpc(lan, 'feishu', 'connection.status', { origin: 'https://untrusted.invalid' }), 403);
|
|
174
|
-
|
|
175
|
-
|
|
215
|
+
await verifyDenied('LAN anonymous management', anonymous, 401);
|
|
216
|
+
await verifyDenied('LAN forged cookie management', { ...lan, cookie: 'invalid=invalid' }, 401);
|
|
217
|
+
await verifyDenied('Untrusted management Host', lan, 403, { host: 'untrusted.invalid' });
|
|
218
|
+
await verifyDenied('Cross-origin management', lan, 403, { origin: 'https://untrusted.invalid' });
|
|
219
|
+
await verifyDenied('Cross-site management', lan, 403, { 'sec-fetch-site': 'cross-site' });
|
|
220
|
+
await verifySettings('LAN default', lan);
|
|
176
221
|
const local = await login(launchUrl, '127.0.0.1');
|
|
177
222
|
const localhost = await login(launchUrl, 'localhost');
|
|
178
223
|
for (const browser of [local, localhost]) {
|
|
@@ -180,6 +225,7 @@ try {
|
|
|
180
225
|
for (const channel of channels) {
|
|
181
226
|
expectStatus(`${hostname} default: ${channel}`, await readyStatus(browser, channel), 200, true);
|
|
182
227
|
}
|
|
228
|
+
await verifySettings(`${hostname} default`, browser);
|
|
183
229
|
// Emulate a browser/proxy dropping the Origin port; this is a header-level
|
|
184
230
|
// reproduction, not evidence that a particular browser emits that header.
|
|
185
231
|
expectStatus(`${hostname} port-less Origin rejected`, await rpc(browser, 'dingtalk',
|
|
@@ -193,6 +239,7 @@ try {
|
|
|
193
239
|
await rpc(await login(launchUrl, domain), 'dingtalk'), 403);
|
|
194
240
|
|
|
195
241
|
await stop();
|
|
242
|
+
await writeFile(join(profile, 'cordis.patch.yml'), '- id: xmanrui-dsh-im\n config:\n rpcAuthority: trusted-host\n');
|
|
196
243
|
const domainLaunchUrl = await start([lanIp, domain]);
|
|
197
244
|
const trustedDomain = await login(domainLaunchUrl, domain);
|
|
198
245
|
expectStatus('Trusted domain without login rejected',
|
|
@@ -200,17 +247,23 @@ try {
|
|
|
200
247
|
for (const channel of channels) {
|
|
201
248
|
expectStatus(`Domain with --trusted-host: ${channel}`, await readyStatus(trustedDomain, channel), 200, true);
|
|
202
249
|
}
|
|
250
|
+
await verifySettings('Domain trusted-host', trustedDomain, true);
|
|
251
|
+
await verifyDenied('Domain anonymous management', { origin: trustedDomain.origin }, 401);
|
|
203
252
|
const otherTrustedOrigin = new URL(trustedDomain.origin);
|
|
204
253
|
otherTrustedOrigin.hostname = lanIp;
|
|
205
254
|
expectStatus('Two trusted hosts still require matching Origin', await rpc(trustedDomain,
|
|
206
255
|
'dingtalk', 'connection.status', { origin: otherTrustedOrigin.origin }), 403);
|
|
256
|
+
await verifyDenied('Trusted management hosts still require matching Origin', trustedDomain, 403, { origin: otherTrustedOrigin.origin });
|
|
207
257
|
|
|
208
258
|
await stop();
|
|
209
259
|
await writeFile(join(profile, 'cordis.patch.yml'), '- id: xmanrui-dsh-im\n config:\n rpcAuthority: loopback\n');
|
|
210
260
|
const restrictedUrl = await start();
|
|
211
261
|
expectStatus('Explicit loopback rejects LAN', await rpc(await login(restrictedUrl, lanIp)), 403);
|
|
262
|
+
await verifyDenied('Explicit loopback management rejects LAN', await login(restrictedUrl, lanIp), 403);
|
|
212
263
|
expectStatus('Explicit loopback accepts 127.0.0.1', await readyStatus(await login(restrictedUrl, '127.0.0.1')), 200, true);
|
|
213
264
|
expectStatus('Explicit loopback accepts localhost', await readyStatus(await login(restrictedUrl, 'localhost')), 200, true);
|
|
265
|
+
await verifySettings('Explicit loopback management 127.0.0.1', await login(restrictedUrl, '127.0.0.1'), true);
|
|
266
|
+
await verifySettings('Explicit loopback management localhost', await login(restrictedUrl, 'localhost'), true);
|
|
214
267
|
console.table(results);
|
|
215
268
|
console.log(`Passed ${results.length} real HTTP checks using loopback, LAN ${lanIp} and domain ${domain}.`);
|
|
216
269
|
console.log('TCP connections stayed on loopback. This checks the original CLI, authentication and built plugin, not a second-device browser.');
|
|
@@ -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)) {
|
|
@@ -229,9 +229,28 @@ export function normalizeEmail(parsed, { address, state } = {}) {
|
|
|
229
229
|
class EmailBotClient {
|
|
230
230
|
#api;
|
|
231
231
|
#signal;
|
|
232
|
-
|
|
232
|
+
#state;
|
|
233
|
+
constructor(api, signal, state = null) {
|
|
233
234
|
this.#api = api;
|
|
234
235
|
this.#signal = signal;
|
|
236
|
+
this.#state = state;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Record the RFC Message-ID of our own reply in the thread map.
|
|
241
|
+
*
|
|
242
|
+
* A client that quotes only the immediate parent (iOS Mail sends a
|
|
243
|
+
* one-entry References header) points its next reply at this id. Outgoing
|
|
244
|
+
* ids were never registered, so the resolver found nothing familiar and
|
|
245
|
+
* forked a brand-new session on every phone reply.
|
|
246
|
+
*/
|
|
247
|
+
#rememberReply(target, sent) {
|
|
248
|
+
const parentId = parseMessageIds(target?.messageId)[0] ?? null;
|
|
249
|
+
const sentId = typeof sent?.messageId === 'string' ? sent.messageId : null;
|
|
250
|
+
if (!parentId || !sentId) return sent;
|
|
251
|
+
const conversation = this.#state?.conversationForThreadId?.(parentId) ?? null;
|
|
252
|
+
if (conversation) this.#state.rememberThreadId(sentId, conversation);
|
|
253
|
+
return sent;
|
|
235
254
|
}
|
|
236
255
|
|
|
237
256
|
async sendText(target, text) {
|
|
@@ -241,14 +260,14 @@ class EmailBotClient {
|
|
|
241
260
|
error.code = 'invalid-target';
|
|
242
261
|
throw error;
|
|
243
262
|
}
|
|
244
|
-
return this.#api.sendReply({
|
|
263
|
+
return this.#rememberReply(target, await this.#api.sendReply({
|
|
245
264
|
to,
|
|
246
265
|
subject: target.subject,
|
|
247
266
|
text,
|
|
248
267
|
inReplyTo: target.messageId,
|
|
249
268
|
transportMessageId: target.transportMessageId,
|
|
250
269
|
references: target.references,
|
|
251
|
-
});
|
|
270
|
+
}));
|
|
252
271
|
}
|
|
253
272
|
|
|
254
273
|
sendTyping() {
|
|
@@ -271,7 +290,7 @@ class EmailBotClient {
|
|
|
271
290
|
}
|
|
272
291
|
|
|
273
292
|
async sendFile(target, file) {
|
|
274
|
-
return this.#api.sendReply({
|
|
293
|
+
return this.#rememberReply(target, await this.#api.sendReply({
|
|
275
294
|
to: target?.to,
|
|
276
295
|
subject: target?.subject,
|
|
277
296
|
text: '',
|
|
@@ -279,11 +298,11 @@ class EmailBotClient {
|
|
|
279
298
|
transportMessageId: target?.transportMessageId,
|
|
280
299
|
references: target?.references,
|
|
281
300
|
attachments: [this.#attachmentFrom(file, 'attachment')],
|
|
282
|
-
});
|
|
301
|
+
}));
|
|
283
302
|
}
|
|
284
303
|
|
|
285
304
|
async sendImage(target, image) {
|
|
286
|
-
return this.#api.sendReply({
|
|
305
|
+
return this.#rememberReply(target, await this.#api.sendReply({
|
|
287
306
|
to: target?.to,
|
|
288
307
|
subject: target?.subject,
|
|
289
308
|
text: '',
|
|
@@ -291,7 +310,7 @@ class EmailBotClient {
|
|
|
291
310
|
transportMessageId: target?.transportMessageId,
|
|
292
311
|
references: target?.references,
|
|
293
312
|
attachments: [this.#attachmentFrom(image, 'image')],
|
|
294
|
-
});
|
|
313
|
+
}));
|
|
295
314
|
}
|
|
296
315
|
}
|
|
297
316
|
|
|
@@ -460,7 +479,7 @@ export class EmailRuntime {
|
|
|
460
479
|
await this.#state.setCursor(Math.max(0, tip - FIRST_CONNECT_WINDOW));
|
|
461
480
|
}
|
|
462
481
|
}
|
|
463
|
-
const client = new EmailBotClient(api, this.#abortController.signal);
|
|
482
|
+
const client = new EmailBotClient(api, this.#abortController.signal, this.#state);
|
|
464
483
|
this.#bridge = new EmailHarnessBridge({
|
|
465
484
|
bot: client,
|
|
466
485
|
harness: this.#harness,
|
|
@@ -138,6 +138,8 @@ const ROOT_CANDIDATE_TTL_MS = 30 * 60_000;
|
|
|
138
138
|
/** Bound main-feed roots awaiting a topic so silent drops cannot grow them. */
|
|
139
139
|
const MAX_ROOT_CANDIDATES = 512;
|
|
140
140
|
const MAX_TOPIC_ANCHORS = 4_000;
|
|
141
|
+
/** Conversations remembered as auto-continued-round delivery targets (LRU). */
|
|
142
|
+
const MAX_CONVERSATION_ROUTES = 512;
|
|
141
143
|
|
|
142
144
|
const MENU_COMMAND = /^\/m(?:enu)?$/i;
|
|
143
145
|
const REPAIR_COMMAND_PREFIX = /^\/repair(?:\s|$)/i;
|
|
@@ -219,6 +221,18 @@ const MIRROR_CHECK_MS = 30_000;
|
|
|
219
221
|
const MIRROR_STALE_MS = 14 * 24 * 60 * 60_000;
|
|
220
222
|
const MIRROR_RECOVERY_MAX_FAILURES = 20;
|
|
221
223
|
|
|
224
|
+
/**
|
|
225
|
+
* The one-line label an auto-continued round shows in the conversation. The
|
|
226
|
+
* Harness goal driver feeds the round a `<goal_round>` prompt that must never
|
|
227
|
+
* reach the chat, so both the goal-round card and the session-sync mirror
|
|
228
|
+
* announce the round by number instead of echoing that text.
|
|
229
|
+
*/
|
|
230
|
+
function goalRoundLabel(round) {
|
|
231
|
+
return Number.isSafeInteger(round) && round > 0
|
|
232
|
+
? t('🔄 目标自动续跑(第 {round} 轮)', { round })
|
|
233
|
+
: t('🔄 目标自动续跑');
|
|
234
|
+
}
|
|
235
|
+
|
|
222
236
|
function mirrorErrorText(error) {
|
|
223
237
|
return [error?.response?.data?.msg, error?.msg, error?.message]
|
|
224
238
|
.filter((value) => typeof value === 'string' && value.trim()).join('; ') || String(error);
|
|
@@ -747,6 +761,14 @@ export class FeishuHarnessBridge {
|
|
|
747
761
|
#sessionSyncIdleTimers = new Map();
|
|
748
762
|
/** Conversation keys with an IM ask in flight (set BEFORE the turn starts). */
|
|
749
763
|
#imTurnKeys = new Set();
|
|
764
|
+
/** Where each conversation posts: { chatId, replyToMessageId } (last inbound). */
|
|
765
|
+
#conversationRoutes = new Map();
|
|
766
|
+
/** Goal rounds currently rendering into a bound conversation, by key. */
|
|
767
|
+
#goalRounds = new Map();
|
|
768
|
+
// A goal round's user/message carries `source.kind === 'goal'` but no
|
|
769
|
+
// `data.turn`; the turn/start right before it does. Keep the latest start
|
|
770
|
+
// so the round can still be identified without inventing a turn.
|
|
771
|
+
#goalTurnStarts = new Map();
|
|
750
772
|
#cardDataTimeoutMs;
|
|
751
773
|
#requestTimeoutMs;
|
|
752
774
|
/** When true, approval/question interactions render as Feishu cards (buttons). */
|
|
@@ -1164,6 +1186,24 @@ export class FeishuHarnessBridge {
|
|
|
1164
1186
|
}
|
|
1165
1187
|
}
|
|
1166
1188
|
|
|
1189
|
+
/**
|
|
1190
|
+
* Remember where a conversation posts, so a turn opened outside the IM can
|
|
1191
|
+
* render into it later. Called for every accepted inbound message; a host
|
|
1192
|
+
* that already knows a binding can register it the same way.
|
|
1193
|
+
*/
|
|
1194
|
+
rememberConversationRoute(key, { chatId, replyToMessageId = null } = {}) {
|
|
1195
|
+
const conversation = nonEmptyString(chatId);
|
|
1196
|
+
if (!nonEmptyString(key) || !conversation) return;
|
|
1197
|
+
this.#conversationRoutes.delete(key);
|
|
1198
|
+
this.#conversationRoutes.set(key, {
|
|
1199
|
+
chatId: conversation,
|
|
1200
|
+
replyToMessageId: nonEmptyString(replyToMessageId),
|
|
1201
|
+
});
|
|
1202
|
+
while (this.#conversationRoutes.size > MAX_CONVERSATION_ROUTES) {
|
|
1203
|
+
this.#conversationRoutes.delete(this.#conversationRoutes.keys().next().value);
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1167
1207
|
accept(event) {
|
|
1168
1208
|
if (!this.#groupHistory || event?.message?.chat_type !== 'group') return this.#accept(event);
|
|
1169
1209
|
const content = extractInboundMessage({ ...event, message: { ...event.message, mentions: [] } }, this.#client);
|
|
@@ -1214,6 +1254,10 @@ export class FeishuHarnessBridge {
|
|
|
1214
1254
|
return Promise.resolve();
|
|
1215
1255
|
}
|
|
1216
1256
|
this.#rememberTopicReply(messageId, key);
|
|
1257
|
+
this.rememberConversationRoute(key, {
|
|
1258
|
+
chatId: event.message.chat_id,
|
|
1259
|
+
replyToMessageId: messageId,
|
|
1260
|
+
});
|
|
1217
1261
|
|
|
1218
1262
|
const commandMessage = extractInboundMessage(event, this.#client);
|
|
1219
1263
|
const commandText = nonEmptyString(commandMessage.content) ?? '';
|
|
@@ -4417,7 +4461,12 @@ export class FeishuHarnessBridge {
|
|
|
4417
4461
|
this.#scheduleMirrorCheck(key, () => this.#checkMirror(mirror));
|
|
4418
4462
|
const openId = mirror.target.openId;
|
|
4419
4463
|
if (type === 'user/message' && event.surfaceOp === 'append') {
|
|
4420
|
-
const
|
|
4464
|
+
const source = event.data?.source;
|
|
4465
|
+
// Goal rounds carry a `<goal_round>` driver prompt: announce the round
|
|
4466
|
+
// instead of echoing that machine text into the chat.
|
|
4467
|
+
const text = source?.kind === 'goal'
|
|
4468
|
+
? goalRoundLabel(source.round)
|
|
4469
|
+
: textFromHarnessContent(event.data?.content);
|
|
4421
4470
|
if (text.trim()) {
|
|
4422
4471
|
const excerpt = text.length > 400 ? `${text.slice(0, 399)}…` : text;
|
|
4423
4472
|
await this.#appendStepCardUpdate(key, openId, null,
|
|
@@ -4445,6 +4494,199 @@ export class FeishuHarnessBridge {
|
|
|
4445
4494
|
}
|
|
4446
4495
|
}
|
|
4447
4496
|
|
|
4497
|
+
// ── Goal rounds opened outside the IM ───────────────────────────────────
|
|
4498
|
+
|
|
4499
|
+
/** Any conversation route bound to this session (the goal-round target). */
|
|
4500
|
+
#hasConversationFor(sessionId) {
|
|
4501
|
+
for (const key of this.#conversationRoutes.keys()) {
|
|
4502
|
+
if (this.#state.sessionFor?.(key) === sessionId) return true;
|
|
4503
|
+
}
|
|
4504
|
+
return false;
|
|
4505
|
+
}
|
|
4506
|
+
|
|
4507
|
+
/**
|
|
4508
|
+
* A goal round is injected by the Harness goal driver: no inbound message
|
|
4509
|
+
* opened it, so the step-card ladder of #answerWithStepPush never runs and
|
|
4510
|
+
* a conversation bound to that session stays silent for the whole round.
|
|
4511
|
+
* Announce the round and stream its tools/answer into the same live card
|
|
4512
|
+
* the IM turns use, so a long auto-run still shows progress and delivers
|
|
4513
|
+
* each round's result. IM-owned turns and sessions already mirrored into a
|
|
4514
|
+
* synced DM are skipped.
|
|
4515
|
+
*/
|
|
4516
|
+
async #feedGoalRoundTurn(sessionId, event, imOwned = false) {
|
|
4517
|
+
if (this.#signal?.aborted) return;
|
|
4518
|
+
const type = event.type;
|
|
4519
|
+
if (type === 'turn/start') {
|
|
4520
|
+
const started = event.data?.turn;
|
|
4521
|
+
if (Number.isSafeInteger(started)) {
|
|
4522
|
+
this.#goalTurnStarts.set(sessionId, { turn: started, seq: event.seq });
|
|
4523
|
+
}
|
|
4524
|
+
return;
|
|
4525
|
+
}
|
|
4526
|
+
if (type === 'user/message') {
|
|
4527
|
+
const source = event.data?.source;
|
|
4528
|
+
if (source?.kind !== 'goal' || imOwned) return;
|
|
4529
|
+
const turn = this.#goalRoundTurn(sessionId, event);
|
|
4530
|
+
if (!Number.isSafeInteger(turn) || this.#goalRoundsFor(sessionId, turn).length > 0) return;
|
|
4531
|
+
await this.#openGoalRounds(sessionId, turn, source.round);
|
|
4532
|
+
return;
|
|
4533
|
+
}
|
|
4534
|
+
if (type !== 'tool/call' && type !== 'assistant/message' && type !== 'turn/end') return;
|
|
4535
|
+
const turn = event.data?.turn;
|
|
4536
|
+
// A later turn proves earlier rounds are over even when their turn/end was
|
|
4537
|
+
// lost, so close them instead of leaving a card open forever.
|
|
4538
|
+
if (Number.isSafeInteger(turn)) await this.#sealStaleGoalRounds(sessionId, turn);
|
|
4539
|
+
const rounds = Number.isSafeInteger(turn)
|
|
4540
|
+
? this.#goalRoundsFor(sessionId, turn)
|
|
4541
|
+
: this.#goalRoundsFor(sessionId);
|
|
4542
|
+
if (!rounds.length) return;
|
|
4543
|
+
if (imOwned) {
|
|
4544
|
+
// The user took the conversation back with a real IM turn: that turn's
|
|
4545
|
+
// ask owns this key's card now, so sealing it here would truncate the
|
|
4546
|
+
// reply the user is waiting for. Hand the round over instead — whatever
|
|
4547
|
+
// streamed so far stays on the card the ask continues.
|
|
4548
|
+
for (const round of rounds) {
|
|
4549
|
+
round.finished = true;
|
|
4550
|
+
this.#goalRounds.delete(round.key);
|
|
4551
|
+
}
|
|
4552
|
+
return;
|
|
4553
|
+
}
|
|
4554
|
+
for (const round of rounds) {
|
|
4555
|
+
if (round.finished || event.seq <= round.lastSeq) continue;
|
|
4556
|
+
if (this.#state.sessionFor?.(round.key) !== sessionId) {
|
|
4557
|
+
// The conversation was rebound to another session: this session's
|
|
4558
|
+
// later output must not land in the card the user now sees there.
|
|
4559
|
+
await this.#sealGoalRound(round, 'completed');
|
|
4560
|
+
continue;
|
|
4561
|
+
}
|
|
4562
|
+
round.lastSeq = event.seq;
|
|
4563
|
+
if (type === 'tool/call') {
|
|
4564
|
+
if (round.pendingStep) {
|
|
4565
|
+
this.#morphStepCardAnswerToNote(round.key, round.pendingStep);
|
|
4566
|
+
round.pendingStep = null;
|
|
4567
|
+
}
|
|
4568
|
+
await this.#appendStepCardUpdate(round.key, round.chatId, round.replyToMessageId,
|
|
4569
|
+
this.#stepCardToolBlock({
|
|
4570
|
+
name: event.data?.name ?? '',
|
|
4571
|
+
arguments: typeof event.data?.arguments === 'string' ? event.data.arguments : '',
|
|
4572
|
+
}), { billable: false });
|
|
4573
|
+
} else if (type === 'assistant/message'
|
|
4574
|
+
&& event.surfaceOp === 'append'
|
|
4575
|
+
&& event.data?.interrupted !== true) {
|
|
4576
|
+
const text = textFromHarnessContent(event.data?.message?.content);
|
|
4577
|
+
if (!text.trim()) continue;
|
|
4578
|
+
round.assistant.setCanonical(event.data?.step, text);
|
|
4579
|
+
round.pendingStep = text;
|
|
4580
|
+
this.#streamStepCardAnswer(round.key, round.chatId, round.replyToMessageId, text);
|
|
4581
|
+
} else if (type === 'turn/end') {
|
|
4582
|
+
const reason = typeof event.data?.reason === 'string' ? event.data.reason : event.data?.reason?.kind;
|
|
4583
|
+
await this.#sealGoalRound(round, reason);
|
|
4584
|
+
}
|
|
4585
|
+
}
|
|
4586
|
+
}
|
|
4587
|
+
|
|
4588
|
+
/**
|
|
4589
|
+
* The turn a goal round belongs to. Harness `user/message` events injected by
|
|
4590
|
+
* the goal driver omit `data.turn`, so fall back to the turn/start that
|
|
4591
|
+
* opened the turn immediately before it.
|
|
4592
|
+
*/
|
|
4593
|
+
#goalRoundTurn(sessionId, event) {
|
|
4594
|
+
const declared = event.data?.turn;
|
|
4595
|
+
if (Number.isSafeInteger(declared)) return declared;
|
|
4596
|
+
const started = this.#goalTurnStarts.get(sessionId);
|
|
4597
|
+
if (!started || !validEventSeq(started.seq) || started.seq >= event.seq) return undefined;
|
|
4598
|
+
return started.turn;
|
|
4599
|
+
}
|
|
4600
|
+
|
|
4601
|
+
#goalRoundsFor(sessionId, turn = null) {
|
|
4602
|
+
const rounds = [];
|
|
4603
|
+
for (const round of this.#goalRounds.values()) {
|
|
4604
|
+
if (round.sessionId !== sessionId) continue;
|
|
4605
|
+
if (turn !== null && round.turn !== turn) continue;
|
|
4606
|
+
rounds.push(round);
|
|
4607
|
+
}
|
|
4608
|
+
return rounds;
|
|
4609
|
+
}
|
|
4610
|
+
|
|
4611
|
+
async #openGoalRounds(sessionId, turn, roundNumber) {
|
|
4612
|
+
const syncedOpenIds = await this.#sessionSyncOpenIds(sessionId);
|
|
4613
|
+
for (const [key, route] of this.#conversationRoutes) {
|
|
4614
|
+
// Only this session's own conversations take part. A key bound to some
|
|
4615
|
+
// other session is not "rebound" from here — it is another session's
|
|
4616
|
+
// card, and its round keeps running until that session says otherwise.
|
|
4617
|
+
if (this.#state.sessionFor?.(key) !== sessionId) continue;
|
|
4618
|
+
const existing = this.#goalRounds.get(key);
|
|
4619
|
+
if (existing && existing.turn !== turn) {
|
|
4620
|
+
// The previous round never reported turn/end (dropped event, crashed
|
|
4621
|
+
// Host): it cannot be updated any more, so close it instead of
|
|
4622
|
+
// letting it block this round.
|
|
4623
|
+
await this.#sealGoalRound(existing);
|
|
4624
|
+
}
|
|
4625
|
+
if (this.#isSyncedDmKey(key, syncedOpenIds)) continue;
|
|
4626
|
+
if (this.#goalRounds.has(key)) continue;
|
|
4627
|
+
// A card left open by an abnormal exit is sealed before the new round
|
|
4628
|
+
// reuses the conversation's card slot.
|
|
4629
|
+
if (this.#stepCards.has(key)) await this.#finishStepCard(key);
|
|
4630
|
+
this.#goalRounds.set(key, {
|
|
4631
|
+
key,
|
|
4632
|
+
sessionId,
|
|
4633
|
+
turn,
|
|
4634
|
+
chatId: route.chatId,
|
|
4635
|
+
replyToMessageId: route.replyToMessageId,
|
|
4636
|
+
assistant: new AssistantTextAccumulator(),
|
|
4637
|
+
pendingStep: null,
|
|
4638
|
+
lastSeq: -1,
|
|
4639
|
+
finished: false,
|
|
4640
|
+
});
|
|
4641
|
+
await this.#appendStepCardUpdate(key, route.chatId, route.replyToMessageId,
|
|
4642
|
+
{ kind: 'message', text: goalRoundLabel(roundNumber) }, { billable: false });
|
|
4643
|
+
}
|
|
4644
|
+
}
|
|
4645
|
+
|
|
4646
|
+
/**
|
|
4647
|
+
* Peers whose synced DM already mirrors this session with this bot. The
|
|
4648
|
+
* mirror owns exactly that direct chat, not every conversation bound to the
|
|
4649
|
+
* session, so a group topic keeps rendering alongside it.
|
|
4650
|
+
*/
|
|
4651
|
+
async #sessionSyncOpenIds(sessionId) {
|
|
4652
|
+
if (!this.#sessionSyncTargetsFor) return new Set();
|
|
4653
|
+
try {
|
|
4654
|
+
const targets = await this.#sessionSyncTargetsFor(sessionId);
|
|
4655
|
+
const openIds = new Set();
|
|
4656
|
+
for (const target of Array.isArray(targets) ? targets : []) {
|
|
4657
|
+
if (target?.botId === this.#botId && nonEmptyString(target?.openId)) openIds.add(target.openId);
|
|
4658
|
+
}
|
|
4659
|
+
return openIds;
|
|
4660
|
+
} catch {
|
|
4661
|
+
return new Set();
|
|
4662
|
+
}
|
|
4663
|
+
}
|
|
4664
|
+
|
|
4665
|
+
/** The plain peer DM key the session-sync mirror delivers into. */
|
|
4666
|
+
#isSyncedDmKey(key, openIds) {
|
|
4667
|
+
if (!(openIds instanceof Set) || openIds.size === 0) return false;
|
|
4668
|
+
if (!key.startsWith('p2p:')) return false;
|
|
4669
|
+
const peer = key.slice(4);
|
|
4670
|
+
// Managed topics inside a DM are separate surfaces the mirror does not
|
|
4671
|
+
// reach: only the plain direct chat is duplicated by it.
|
|
4672
|
+
return !peer.includes(':') && openIds.has(peer);
|
|
4673
|
+
}
|
|
4674
|
+
|
|
4675
|
+
async #sealStaleGoalRounds(sessionId, turn) {
|
|
4676
|
+
const stale = this.#goalRoundsFor(sessionId).filter((round) => round.turn < turn);
|
|
4677
|
+
for (const round of stale) await this.#sealGoalRound(round, 'completed');
|
|
4678
|
+
}
|
|
4679
|
+
|
|
4680
|
+
async #sealGoalRound(round, reason = 'completed') {
|
|
4681
|
+
if (round.finished) return;
|
|
4682
|
+
round.finished = true;
|
|
4683
|
+
this.#goalRounds.delete(round.key);
|
|
4684
|
+
await this.#finishStepCard(round.key, {
|
|
4685
|
+
stopped: reason === 'stopped' || reason === 'aborted' || reason === 'cancelled',
|
|
4686
|
+
answerText: round.assistant.text,
|
|
4687
|
+
});
|
|
4688
|
+
}
|
|
4689
|
+
|
|
4448
4690
|
#onHarnessEvent({ sessionId, event }) {
|
|
4449
4691
|
if (this.#signal?.aborted
|
|
4450
4692
|
|| !sessionId
|
|
@@ -4458,10 +4700,15 @@ export class FeishuHarnessBridge {
|
|
|
4458
4700
|
// card, tool/call and assistant/message feed it, turn/end seals it);
|
|
4459
4701
|
// IM-opened turns are skipped — they already own their card via the ask
|
|
4460
4702
|
// callbacks. turn/end ALSO continues below for watch completions.
|
|
4703
|
+
const imOwned = this.#isImTurn(sessionId);
|
|
4461
4704
|
if (this.#sessionSyncTargetsFor) {
|
|
4462
|
-
const imOwned = this.#isImTurn(sessionId);
|
|
4463
4705
|
void this.#queueEventTask(sessionId, () => this.#feedSessionSyncTurn(sessionId, event, imOwned));
|
|
4464
|
-
|
|
4706
|
+
}
|
|
4707
|
+
// Goal auto-continuation: a round opened by the Harness goal driver has
|
|
4708
|
+
// no inbound message behind it, so it renders into the bound conversation
|
|
4709
|
+
// through this bridge instead of an ask callback. Same event ladder.
|
|
4710
|
+
if (this.#goalRounds.size > 0 || this.#hasConversationFor(sessionId)) {
|
|
4711
|
+
void this.#queueEventTask(sessionId, () => this.#feedGoalRoundTurn(sessionId, event, imOwned));
|
|
4465
4712
|
}
|
|
4466
4713
|
if (event.type !== 'turn/end') return;
|
|
4467
4714
|
// Record before consulting state: /watch may still be resolving its target
|
|
@@ -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();
|
|
@@ -5,8 +5,30 @@ import { dirname } from 'node:path';
|
|
|
5
5
|
import { qqStateError } from './state-error.mjs';
|
|
6
6
|
|
|
7
7
|
const PENDING_MESSAGE_LIMIT = 200;
|
|
8
|
+
const AUTHOR_LIMIT = 500;
|
|
8
9
|
const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [] });
|
|
9
10
|
|
|
11
|
+
function normalizeAuthor(value) {
|
|
12
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
13
|
+
const senderId = typeof value.senderId === 'string' ? value.senderId : '';
|
|
14
|
+
if (!senderId) return null;
|
|
15
|
+
const author = { senderId, isBot: value.isBot === true };
|
|
16
|
+
if (typeof value.senderName === 'string' && value.senderName) author.senderName = value.senderName;
|
|
17
|
+
if (typeof value.senderUsername === 'string' && value.senderUsername) author.senderUsername = value.senderUsername;
|
|
18
|
+
if (typeof value.at === 'string' && value.at) author.at = value.at;
|
|
19
|
+
return author;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function normalizeAuthors(value) {
|
|
23
|
+
const authors = {};
|
|
24
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return authors;
|
|
25
|
+
for (const key of Object.keys(value).slice(-AUTHOR_LIMIT)) {
|
|
26
|
+
const author = normalizeAuthor(value[key]);
|
|
27
|
+
if (author) authors[key] = author;
|
|
28
|
+
}
|
|
29
|
+
return authors;
|
|
30
|
+
}
|
|
31
|
+
|
|
10
32
|
/**
|
|
11
33
|
* A message persisted when it enters the QQ bridge's in-memory queue, so a
|
|
12
34
|
* restart before its turn runs can replay it (submitted: false) or report it
|
|
@@ -62,6 +84,7 @@ function normalizeState(value) {
|
|
|
62
84
|
return {
|
|
63
85
|
version: 1,
|
|
64
86
|
sessions,
|
|
87
|
+
...(value.authors ? { authors: normalizeAuthors(value.authors) } : {}),
|
|
65
88
|
includeArchivedSessions: value.includeArchivedSessions === true,
|
|
66
89
|
...(pendingMessages.length ? { pendingMessages } : {}),
|
|
67
90
|
...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}),
|
|
@@ -168,6 +191,25 @@ export class QqStateStore {
|
|
|
168
191
|
|
|
169
192
|
includesArchivedSessions() { return this.#state.includeArchivedSessions === true; }
|
|
170
193
|
|
|
194
|
+
authorFor(key) {
|
|
195
|
+
const author = this.#state.authors?.[key];
|
|
196
|
+
return author ? structuredClone(author) : null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async rememberAuthor(key, value) {
|
|
200
|
+
const author = normalizeAuthor({ at: new Date().toISOString(), ...value });
|
|
201
|
+
if (typeof key !== 'string' || !key || !author) return null;
|
|
202
|
+
const authors = this.#state.authors ??= {};
|
|
203
|
+
delete authors[key];
|
|
204
|
+
authors[key] = author;
|
|
205
|
+
const keys = Object.keys(authors);
|
|
206
|
+
if (keys.length > AUTHOR_LIMIT) {
|
|
207
|
+
for (const stale of keys.slice(0, keys.length - AUTHOR_LIMIT)) delete authors[stale];
|
|
208
|
+
}
|
|
209
|
+
await this.#persist();
|
|
210
|
+
return structuredClone(author);
|
|
211
|
+
}
|
|
212
|
+
|
|
171
213
|
async setIncludeArchivedSessions(include) {
|
|
172
214
|
this.#state.includeArchivedSessions = include === true;
|
|
173
215
|
await this.#persist();
|