@xmanrui/dsh-im 5.9.0 → 5.9.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xmanrui/dsh-im",
3
- "version": "5.9.0",
3
+ "version": "5.9.1",
4
4
  "icon": "./assets/logo-plugin-message-link-gradient.webp",
5
5
  "description": "把微信、飞书、企微、钉钉、QQ、Telegram、WhatsApp、Slack、Discord、Matrix接入DSH。 Connect Telegram, WhatsApp, Slack, Discord, Matrix, WeChat, Feishu, WeCom, DingTalk, and QQ to DSH.",
6
6
  "keywords": [
@@ -85,6 +85,6 @@ export function installInboundTtlRpc(ctx, options = {}) {
85
85
  (endpoint, payload, signal) => Object.values(GROUP_HISTORY_ENDPOINTS).includes(endpoint)
86
86
  ? history(endpoint, payload, signal) : Object.values(IMAGE_INPUT_ENDPOINTS).includes(endpoint)
87
87
  ? image(endpoint, payload, signal) : ttl(endpoint, payload, signal),
88
- { authority: 'loopback' },
88
+ { authority: options.config?.rpcAuthority },
89
89
  );
90
90
  }
@@ -202,7 +202,7 @@ export function createImHostPlugin(internals = {}) {
202
202
  }
203
203
  }
204
204
  try {
205
- startUpdate(ctx);
205
+ startUpdate(ctx, { authority: config.rpcAuthority });
206
206
  } catch (error) {
207
207
  logger.error?.('[dsh-im] failed to activate update management; continuing with channels', error);
208
208
  }
@@ -106,8 +106,7 @@ export function createSidebarSettingsRpcHandler({ config = {}, store, configured
106
106
  }
107
107
 
108
108
  export function installSidebarSettingsRpc(ctx, { config = {} } = {}) {
109
- // Visibility follows ordinary channel management authority. Keep it separate
110
- // from the general settings route, whose TTL operations remain loopback-only.
109
+ // Visibility follows the same authority as channels and general settings.
111
110
  return registerManagementRpc(ctx, SIDEBAR_SETTINGS_RPC_CHANNEL,
112
111
  createSidebarSettingsRpcHandler({ config }), { authority: config.rpcAuthority });
113
112
  }
@@ -44,7 +44,7 @@ export function installUpdateRpc(ctx, options = {}) {
44
44
  const runtime = options.runtime ?? createUpdateRuntime({ ctx, moduleUrl: import.meta.url });
45
45
  const service = options.service ?? createUpdateService({ runtime });
46
46
  const dispose = registerManagementRpc(ctx, UPDATE_RPC_CHANNEL, createUpdateRpcHandler(service), {
47
- authority: 'loopback',
47
+ authority: options.authority,
48
48
  });
49
49
  ctx.effect(() => () => service.close(), 'dsh-im: close update installer');
50
50
  return dispose;
@@ -71,16 +71,38 @@ export function registerManagementRpc(ctx, channel, handler, { authority } = {})
71
71
  });
72
72
  }
73
73
 
74
+ function managementHttpStatus(cause, endpoint) {
75
+ if (Number.isInteger(cause?.status) && cause.status >= 100 && cause.status <= 599) return cause.status;
76
+ // DSH 0.2.x throws a plain Error for HTTP failures. Accept only its exact
77
+ // transport message for this request, never an arbitrary embedded number.
78
+ const prefix = `transport failure for /api/${endpoint}: HTTP `;
79
+ if (!endpoint || typeof cause?.message !== 'string' || !cause.message.startsWith(prefix)) return undefined;
80
+ const status = Number(cause.message.slice(prefix.length));
81
+ return Number.isInteger(status) && status >= 100 && status <= 599 && cause.message === `${prefix}${status}`
82
+ ? status : undefined;
83
+ }
84
+
85
+ function managementErrorMessage(status) {
86
+ if (status === 401) return 'DSH 登录状态无效或已过期,请通过有效启动链接重新登录。';
87
+ if (status === 403) return 'DSH 拒绝了当前管理请求(HTTP 403)。请检查访问权限、可信地址配置及代理设置;若启用了仅本机访问,请按该限制访问。';
88
+ if (status === 404) return 'DSH 管理接口不存在(HTTP 404),请检查 Host 与插件版本及代理路径,重启后重试。';
89
+ if (status >= 500) return 'DSH 管理服务暂时异常,请检查服务状态或稍后重试。';
90
+ return 'DSH 管理请求失败,请检查服务状态和网络连接后重试。';
91
+ }
92
+
74
93
  /** Keep channel UI callers unchanged while using DSH's native correlation and response validation. */
75
94
  export async function callManagementRpc(connection, channel, method, payload, signal) {
95
+ let endpoint;
76
96
  try {
77
- return await connection.rpc.call('/api', rpcEndpoint(channel), { method, payload }, signal);
97
+ endpoint = rpcEndpoint(channel);
98
+ return await connection.rpc.call('/api', endpoint, { method, payload }, signal);
78
99
  } catch (cause) {
79
100
  if (signal?.aborted || cause?.name === 'AbortError') throw cause;
80
- const error = new Error('无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。', { cause });
101
+ const httpStatus = managementHttpStatus(cause, endpoint);
102
+ const error = new Error(managementErrorMessage(httpStatus), { cause });
81
103
  error.code = 'management-unreachable';
82
104
  error.details = { operation: method, stage: 'management.request', occurredAt: new Date().toISOString(),
83
- ...(Number.isInteger(cause?.status) && cause.status >= 100 && cause.status <= 599 ? { httpStatus: cause.status } : {}),
105
+ ...(httpStatus === undefined ? {} : { httpStatus }),
84
106
  };
85
107
  throw error;
86
108
  }
@@ -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
- // DSH 0.1.5 CLI intentionally permits only loopback listening. Exercise its
20
- // real HTTP carrier with a trusted LAN authority, while keeping TCP local.
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
- expectStatus('LAN update remains local-only', await rpc(lan, 'dsh-im', 'update.status'), 403);
175
- expectStatus('LAN TTL remains local-only', await rpc(lan, 'dsh-im-settings', 'settings.inbound-ttl.get'), 403);
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.');
@@ -229,9 +229,28 @@ export function normalizeEmail(parsed, { address, state } = {}) {
229
229
  class EmailBotClient {
230
230
  #api;
231
231
  #signal;
232
- constructor(api, signal) {
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 text = textFromHarnessContent(event.data?.content);
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
- if (event.type !== 'turn/end') return;
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
@@ -85,5 +85,10 @@ export default Object.freeze({
85
85
  "超时阈值(毫秒)": "Timeout (ms)",
86
86
  "Node 版本": "Node version",
87
87
  "运行平台": "Platform",
88
- "无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。": "Cannot access the DSH management API. Check the DSH connection or sign in again."
88
+ "无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。": "Cannot access the DSH management API. Check the DSH connection or sign in again.",
89
+ "DSH 登录状态无效或已过期,请通过有效启动链接重新登录。": "Your DSH session is invalid or expired. Sign in again using a valid launch link.",
90
+ "DSH 拒绝了当前管理请求(HTTP 403)。请检查访问权限、可信地址配置及代理设置;若启用了仅本机访问,请按该限制访问。": "DSH denied this management request (HTTP 403). Check access permissions, trusted hosts and proxy settings. If local-only access is enabled, use an allowed local connection.",
91
+ "DSH 管理接口不存在(HTTP 404),请检查 Host 与插件版本及代理路径,重启后重试。": "The DSH management API was not found (HTTP 404). Check the Host and plugin versions and proxy path, then restart and retry.",
92
+ "DSH 管理服务暂时异常,请检查服务状态或稍后重试。": "The DSH management service encountered an error. Check its status or try again later.",
93
+ "DSH 管理请求失败,请检查服务状态和网络连接后重试。": "The DSH management request failed. Check the service status and network connection, then retry."
89
94
  });
@@ -407,6 +407,9 @@ export default {
407
407
  '任务失败': 'Failed',
408
408
  // feishu/bridge.mjs — step push context injection
409
409
  '📎 已注入会话上下文': '📎 Context injected',
410
+ // feishu/bridge.mjs — goal rounds opened outside the IM (issue #454)
411
+ '🔄 目标自动续跑': '🔄 Goal auto-continued',
412
+ '🔄 目标自动续跑(第 {round} 轮)': '🔄 Goal auto-continued (round {round})',
410
413
  // feishu/feishu-cards.mjs — question card answered state + custom entry (issue #162)
411
414
  '✏️ 其他答案…': '✏️ Other answer…',
412
415
  '✅ 已回答{progress}': '✅ Answered{progress}',
@@ -103,4 +103,14 @@ export default Object.freeze({
103
103
  '运行平台': 'Платформа',
104
104
  '无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。':
105
105
  'Нет доступа к административному API DSH. Проверьте соединение с DSH или войдите заново.',
106
+ 'DSH 登录状态无效或已过期,请通过有效启动链接重新登录。':
107
+ 'Сеанс DSH недействителен или истёк. Войдите снова по действующей ссылке запуска.',
108
+ 'DSH 拒绝了当前管理请求(HTTP 403)。请检查访问权限、可信地址配置及代理设置;若启用了仅本机访问,请按该限制访问。':
109
+ 'DSH отклонил запрос управления (HTTP 403). Проверьте права доступа, доверенные адреса и настройки прокси. Если разрешён только локальный доступ, используйте разрешённое локальное подключение.',
110
+ 'DSH 管理接口不存在(HTTP 404),请检查 Host 与插件版本及代理路径,重启后重试。':
111
+ 'API управления DSH не найден (HTTP 404). Проверьте версии Host и плагина, а также путь прокси, затем перезапустите и повторите попытку.',
112
+ 'DSH 管理服务暂时异常,请检查服务状态或稍后重试。':
113
+ 'В службе управления DSH произошла ошибка. Проверьте её состояние или повторите попытку позже.',
114
+ 'DSH 管理请求失败,请检查服务状态和网络连接后重试。':
115
+ 'Запрос управления DSH не выполнен. Проверьте состояние службы и подключение к сети, затем повторите попытку.',
106
116
  });