@xmanrui/dsh-im 5.8.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.
Files changed (66) hide show
  1. package/README.en.md +45 -8
  2. package/README.md +56 -8
  3. package/docs/preset-workspaces.md +37 -0
  4. package/lib/client.js +66 -7
  5. package/lib/index.js +329 -326
  6. package/package.json +3 -1
  7. package/plugin-src/client/connection-error.js +1 -1
  8. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  9. package/plugin-src/host/channels/feishu/production.mjs +2 -1
  10. package/plugin-src/host/channels/matrix/production.mjs +2 -1
  11. package/plugin-src/host/channels/qq/production.mjs +2 -1
  12. package/plugin-src/host/channels/shared/binding-events.mjs +130 -0
  13. package/plugin-src/host/channels/shared/production.mjs +32 -3
  14. package/plugin-src/host/channels/slack/production.mjs +2 -1
  15. package/plugin-src/host/channels/wecom/production.mjs +2 -1
  16. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  17. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  18. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  19. package/plugin-src/host/delivery-adapter.mjs +122 -1
  20. package/plugin-src/host/delivery-service.mjs +40 -0
  21. package/plugin-src/host/ds-bot-client.mjs +28 -2
  22. package/plugin-src/host/inbound-ttl-rpc.mjs +1 -1
  23. package/plugin-src/host/index.mjs +25 -2
  24. package/plugin-src/host/modern-harness-api.mjs +3 -0
  25. package/plugin-src/host/sidebar-settings.mjs +1 -2
  26. package/plugin-src/host/update-rpc.mjs +1 -1
  27. package/plugin-src/management-rpc.mjs +25 -3
  28. package/scripts/telegram-menu-scopes.mjs +57 -0
  29. package/scripts/verify-interface-language.mjs +60 -15
  30. package/scripts/verify-lan-management.mjs +58 -5
  31. package/src/channels/dingtalk/dingtalk-bridge.mjs +2 -3
  32. package/src/channels/dingtalk/dingtalk-menu.mjs +4 -5
  33. package/src/channels/email/email-runtime.mjs +27 -8
  34. package/src/channels/email/transports/imap-smtp.mjs +21 -11
  35. package/src/channels/feishu/bridge.mjs +296 -13
  36. package/src/channels/feishu/feishu-cards.mjs +96 -25
  37. package/src/channels/qq/qq-menu.mjs +3 -4
  38. package/src/channels/shared/action-card.mjs +331 -0
  39. package/src/channels/shared/bot-workspace-store.mjs +123 -8
  40. package/src/channels/shared/command-catalog.mjs +20 -5
  41. package/src/channels/shared/conversation/describe.mjs +116 -0
  42. package/src/channels/shared/conversation-state-store.mjs +62 -0
  43. package/src/channels/shared/diagnostic-details.mjs +38 -0
  44. package/src/channels/shared/harness-approval.mjs +58 -13
  45. package/src/channels/shared/harness-client.mjs +13 -0
  46. package/src/channels/shared/harness-session-binding.mjs +13 -1
  47. package/src/channels/shared/i18n-en/diagnostics.mjs +6 -1
  48. package/src/channels/shared/i18n-en/feishu.mjs +9 -0
  49. package/src/channels/shared/i18n-en/shared-a.mjs +9 -0
  50. package/src/channels/shared/i18n-en/telegram.mjs +14 -0
  51. package/src/channels/shared/i18n-ru/diagnostics.mjs +10 -0
  52. package/src/channels/shared/i18n-ru/feishu.mjs +8 -0
  53. package/src/channels/shared/i18n-ru/shared-a.mjs +9 -0
  54. package/src/channels/shared/i18n-ru/telegram.mjs +14 -0
  55. package/src/channels/shared/model-command.mjs +5 -0
  56. package/src/channels/shared/preset-workspaces.mjs +48 -0
  57. package/src/channels/shared/qr-encoding-error.mjs +8 -2
  58. package/src/channels/shared/status-command.mjs +159 -0
  59. package/src/channels/shared/text-harness-bridge.mjs +86 -4
  60. package/src/channels/shared/workspace-command.mjs +20 -12
  61. package/src/channels/shared/workspace-session.mjs +30 -5
  62. package/src/channels/telegram/approval-card.mjs +379 -0
  63. package/src/channels/telegram/telegram-api.mjs +10 -1
  64. package/src/channels/telegram/telegram-bridge.mjs +7 -0
  65. package/src/channels/telegram/telegram-runtime.mjs +125 -13
  66. package/src/channels/wecom/wecom-bridge.mjs +5 -3
@@ -96,6 +96,7 @@ import { isSharedLocalCommand } from '../shared/command-permission.mjs';
96
96
  import {
97
97
  MENU_PAGE_SIZE,
98
98
  PRESET_FOLLOW_DEFAULT_SENTINEL,
99
+ REASONING_DEFAULT_SENTINEL,
99
100
  STEER_CUSTOM_SENTINEL,
100
101
  approvalCard,
101
102
  completionCard,
@@ -137,6 +138,8 @@ const ROOT_CANDIDATE_TTL_MS = 30 * 60_000;
137
138
  /** Bound main-feed roots awaiting a topic so silent drops cannot grow them. */
138
139
  const MAX_ROOT_CANDIDATES = 512;
139
140
  const MAX_TOPIC_ANCHORS = 4_000;
141
+ /** Conversations remembered as auto-continued-round delivery targets (LRU). */
142
+ const MAX_CONVERSATION_ROUTES = 512;
140
143
 
141
144
  const MENU_COMMAND = /^\/m(?:enu)?$/i;
142
145
  const REPAIR_COMMAND_PREFIX = /^\/repair(?:\s|$)/i;
@@ -218,6 +221,18 @@ const MIRROR_CHECK_MS = 30_000;
218
221
  const MIRROR_STALE_MS = 14 * 24 * 60 * 60_000;
219
222
  const MIRROR_RECOVERY_MAX_FAILURES = 20;
220
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
+
221
236
  function mirrorErrorText(error) {
222
237
  return [error?.response?.data?.msg, error?.msg, error?.message]
223
238
  .filter((value) => typeof value === 'string' && value.trim()).join('; ') || String(error);
@@ -746,6 +761,14 @@ export class FeishuHarnessBridge {
746
761
  #sessionSyncIdleTimers = new Map();
747
762
  /** Conversation keys with an IM ask in flight (set BEFORE the turn starts). */
748
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();
749
772
  #cardDataTimeoutMs;
750
773
  #requestTimeoutMs;
751
774
  /** When true, approval/question interactions render as Feishu cards (buttons). */
@@ -1163,6 +1186,24 @@ export class FeishuHarnessBridge {
1163
1186
  }
1164
1187
  }
1165
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
+
1166
1207
  accept(event) {
1167
1208
  if (!this.#groupHistory || event?.message?.chat_type !== 'group') return this.#accept(event);
1168
1209
  const content = extractInboundMessage({ ...event, message: { ...event.message, mentions: [] } }, this.#client);
@@ -1213,6 +1254,10 @@ export class FeishuHarnessBridge {
1213
1254
  return Promise.resolve();
1214
1255
  }
1215
1256
  this.#rememberTopicReply(messageId, key);
1257
+ this.rememberConversationRoute(key, {
1258
+ chatId: event.message.chat_id,
1259
+ replyToMessageId: messageId,
1260
+ });
1216
1261
 
1217
1262
  const commandMessage = extractInboundMessage(event, this.#client);
1218
1263
  const commandText = nonEmptyString(commandMessage.content) ?? '';
@@ -2429,7 +2474,9 @@ export class FeishuHarnessBridge {
2429
2474
  ? `preset:select:${option}`
2430
2475
  : action === 'model_pick' && typeof option === 'string'
2431
2476
  ? `model:select:${option}`
2432
- : action === 'archive_pick' && typeof option === 'string'
2477
+ : action === 'reasoning_pick' && typeof option === 'string'
2478
+ ? `reasoning:select:${option}`
2479
+ : action === 'archive_pick' && typeof option === 'string'
2433
2480
  ? `archive:${option}`
2434
2481
  : action === 'steer_pick' && typeof option === 'string'
2435
2482
  ? `steer:${option}`
@@ -2438,6 +2485,7 @@ export class FeishuHarnessBridge {
2438
2485
  ?? nonEmptyString(event?.open_message_id)
2439
2486
  ?? nonEmptyString(event?.message_id);
2440
2487
  const route = messageId ? this.#cardKeys.get(messageId) : null;
2488
+ const modelPage = route?.modelPage ?? 0;
2441
2489
  if (!route) {
2442
2490
  // A route is also the trusted direct/group scope for the unified policy.
2443
2491
  // Without it, fail closed instead of producing an unauthorised side effect.
@@ -2479,7 +2527,7 @@ export class FeishuHarnessBridge {
2479
2527
  this.#cardKeys.set(messageId, route);
2480
2528
  const newSessionActionId = nonEmptyString(actionValue.newSessionActionId);
2481
2529
  if (resolvedAction === 'new' && (!route.menuContext || !newSessionActionId)) return Promise.resolve();
2482
- const entry = { ...route, messageId, selections: multiValues, operatorOpenId, newSessionActionId };
2530
+ const entry = { ...route, messageId, selections: multiValues, operatorOpenId, newSessionActionId, modelPage };
2483
2531
  const source = nonEmptyString(actionValue.source);
2484
2532
  const formText = nonEmptyString(formValue.steer_text);
2485
2533
  const eventId = nonEmptyString(event?.event_id)
@@ -2688,6 +2736,7 @@ export class FeishuHarnessBridge {
2688
2736
  sessionWorkspace = null,
2689
2737
  sessionPage = 0,
2690
2738
  sessionLimit = null,
2739
+ modelPage = 0,
2691
2740
  selections = [],
2692
2741
  actor = null,
2693
2742
  menuContext = null,
@@ -2908,8 +2957,9 @@ export class FeishuHarnessBridge {
2908
2957
  await this.#showPresetCard(key, chatId, { updateMessageId: messageId });
2909
2958
  return;
2910
2959
  }
2911
- if (action === 'models') {
2912
- await this.#showModelCard(key, chatId, { updateMessageId: messageId });
2960
+ if (action === 'models' || /^models:\d+$/.test(action)) {
2961
+ const page = action === 'models' ? 0 : Number(action.slice('models:'.length));
2962
+ await this.#showModelCard(key, chatId, { updateMessageId: messageId, page: Math.max(0, page) });
2913
2963
  return;
2914
2964
  }
2915
2965
  if (action === 'status') {
@@ -2940,7 +2990,12 @@ export class FeishuHarnessBridge {
2940
2990
  }
2941
2991
  if (action.startsWith('model:select:')) {
2942
2992
  const modelId = action.slice('model:select:'.length);
2943
- await this.#handleModelSelect(key, chatId, modelId, { updateMessageId: messageId });
2993
+ await this.#handleModelSelect(key, chatId, modelId, { updateMessageId: messageId, page: modelPage });
2994
+ return;
2995
+ }
2996
+ if (action.startsWith('reasoning:select:')) {
2997
+ const effort = action.slice('reasoning:select:'.length);
2998
+ await this.#handleReasoningSelect(key, chatId, effort, { updateMessageId: messageId, page: modelPage });
2944
2999
  return;
2945
3000
  }
2946
3001
  if (action.startsWith('use:')) {
@@ -3252,6 +3307,9 @@ export class FeishuHarnessBridge {
3252
3307
  sessionPage: Number.isSafeInteger(options.sessionPage) && options.sessionPage >= 0
3253
3308
  ? options.sessionPage
3254
3309
  : 0,
3310
+ modelPage: Number.isSafeInteger(options.modelPage) && options.modelPage >= 0
3311
+ ? options.modelPage
3312
+ : 0,
3255
3313
  sessionLimit: Number.isSafeInteger(options.sessionLimit) && options.sessionLimit > 0
3256
3314
  ? options.sessionLimit
3257
3315
  : null,
@@ -3532,7 +3590,7 @@ export class FeishuHarnessBridge {
3532
3590
  /**
3533
3591
  * Fetch the model catalog and show the model selection card.
3534
3592
  */
3535
- async #showModelCard(key, chatId, { updateMessageId = null } = {}) {
3593
+ async #showModelCard(key, chatId, { updateMessageId = null, page = 0 } = {}) {
3536
3594
  try {
3537
3595
  const signal = this.#cardDataSignal();
3538
3596
  await this.#harness.ensureRunning({ signal });
@@ -3548,7 +3606,7 @@ export class FeishuHarnessBridge {
3548
3606
  if (!catalog) {
3549
3607
  catalog = await this.#harness.listModels({ signal });
3550
3608
  }
3551
- await this.#sendCard(chatId, modelCard(catalog), { key, updateMessageId });
3609
+ await this.#sendCard(chatId, modelCard(catalog, { page }), { key, updateMessageId, modelPage: page });
3552
3610
  } catch (error) {
3553
3611
  await this.#sendFailure(chatId, error, { logLabel: 'model card', replyTo: updateMessageId });
3554
3612
  }
@@ -3792,7 +3850,29 @@ export class FeishuHarnessBridge {
3792
3850
  * catalog validation, busy checks, pending-interaction checks and the
3793
3851
  * session binding lock stay in one place.
3794
3852
  */
3795
- async #handleModelSelect(key, chatId, modelId, { updateMessageId = null, replyTo = null } = {}) {
3853
+ async #handleReasoningSelect(key, chatId, effort, { updateMessageId = null, replyTo = null, page = 0 } = {}) {
3854
+ try {
3855
+ const command = effort === REASONING_DEFAULT_SENTINEL ? '/reasoning --default' : `/reasoning ${effort}`;
3856
+ const result = await runModelCommand(command, this.#harness, this.#state, key, {
3857
+ signal: this.#signal,
3858
+ pendingInteraction: this.#hasPendingInteraction(key),
3859
+ control: { owner: this, key },
3860
+ });
3861
+ for (const reply of result?.messages ?? [result?.message]) {
3862
+ if (reply) await this.#send(chatId, reply, { replyTo });
3863
+ }
3864
+ } catch (error) {
3865
+ await this.#sendFailure(chatId, error, { logLabel: 'reasoning selection', replyTo: updateMessageId });
3866
+ return;
3867
+ }
3868
+ try {
3869
+ await this.#showModelCard(key, chatId, { updateMessageId, page });
3870
+ } catch (error) {
3871
+ this.#logger.warn?.('[dsh-feishu] model card refresh failed after reasoning select:', error.message);
3872
+ }
3873
+ }
3874
+
3875
+ async #handleModelSelect(key, chatId, modelId, { updateMessageId = null, replyTo = null, page = 0 } = {}) {
3796
3876
  try {
3797
3877
  const result = await runModelCommand(
3798
3878
  `/model ${modelId}`, this.#harness, this.#state, key, {
@@ -3809,9 +3889,9 @@ export class FeishuHarnessBridge {
3809
3889
  return;
3810
3890
  }
3811
3891
  try {
3812
- await this.#sendMenuCard(key, chatId, { updateMessageId, replyTo });
3892
+ await this.#showModelCard(key, chatId, { updateMessageId, page });
3813
3893
  } catch (error) {
3814
- this.#logger.warn?.('[dsh-feishu] menu refresh failed after model select:', error.message);
3894
+ this.#logger.warn?.('[dsh-feishu] model card refresh failed after model select:', error.message);
3815
3895
  }
3816
3896
  }
3817
3897
 
@@ -4381,7 +4461,12 @@ export class FeishuHarnessBridge {
4381
4461
  this.#scheduleMirrorCheck(key, () => this.#checkMirror(mirror));
4382
4462
  const openId = mirror.target.openId;
4383
4463
  if (type === 'user/message' && event.surfaceOp === 'append') {
4384
- 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);
4385
4470
  if (text.trim()) {
4386
4471
  const excerpt = text.length > 400 ? `${text.slice(0, 399)}…` : text;
4387
4472
  await this.#appendStepCardUpdate(key, openId, null,
@@ -4409,6 +4494,199 @@ export class FeishuHarnessBridge {
4409
4494
  }
4410
4495
  }
4411
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
+
4412
4690
  #onHarnessEvent({ sessionId, event }) {
4413
4691
  if (this.#signal?.aborted
4414
4692
  || !sessionId
@@ -4422,10 +4700,15 @@ export class FeishuHarnessBridge {
4422
4700
  // card, tool/call and assistant/message feed it, turn/end seals it);
4423
4701
  // IM-opened turns are skipped — they already own their card via the ask
4424
4702
  // callbacks. turn/end ALSO continues below for watch completions.
4703
+ const imOwned = this.#isImTurn(sessionId);
4425
4704
  if (this.#sessionSyncTargetsFor) {
4426
- const imOwned = this.#isImTurn(sessionId);
4427
4705
  void this.#queueEventTask(sessionId, () => this.#feedSessionSyncTurn(sessionId, event, imOwned));
4428
- 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));
4429
4712
  }
4430
4713
  if (event.type !== 'turn/end') return;
4431
4714
  // Record before consulting state: /watch may still be resolving its target
@@ -19,9 +19,12 @@ import { workspaceLabels } from '../shared/workspace-labels.mjs';
19
19
  import { normalizeFeishuStepCardPanels } from './step-push-mode.mjs';
20
20
 
21
21
  export const MENU_PAGE_SIZE = 10;
22
+ export const MODEL_PAGE_SIZE = 20;
23
+ const MODEL_CARD_TEXT_LIMIT = 200;
22
24
 
23
25
  /** 预设下拉中「跟随默认」(null) 的哨兵值,供 initial_index 命中与回调识别。 */
24
26
  export const PRESET_FOLLOW_DEFAULT_SENTINEL = '__preset_follow_default__';
27
+ export const REASONING_DEFAULT_SENTINEL = '__reasoning_default__';
25
28
 
26
29
  function plainText(content) {
27
30
  return { tag: 'plain_text', content: String(content) };
@@ -240,10 +243,19 @@ export function menuCard(ctx) {
240
243
  const curModelId = curModel ? `${curModel.provider}/${curModel.model}` : null;
241
244
  const flat = [];
242
245
  for (const group of groups) {
243
- for (const model of (group.models || [])) flat.push({ id: `${group.id}/${model.id}`, name: `${group.name} - ${model.name}` });
246
+ for (const model of (group.models || [])) {
247
+ flat.push({
248
+ id: `${group.id}/${model.id}`,
249
+ name: `${group.name} - ${model.name}`,
250
+ reasoning: model.reasoning,
251
+ });
252
+ }
244
253
  }
245
254
  let modelDropdown = null;
255
+ let reasoningDropdown = null;
246
256
  if (flat.length > 1) {
257
+ // Keep the compact menu within Feishu select limits; the dedicated model
258
+ // card exposes the complete catalog.
247
259
  const setModelOptions = flat.slice(0, 30).map((opt) => ({
248
260
  text: { tag: 'plain_text', content: `${opt.id === curModelId ? '✓ ' : ''}${opt.name}` },
249
261
  value: opt.id,
@@ -257,6 +269,28 @@ export function menuCard(ctx) {
257
269
  behaviors: [{ type: 'callback', value: { action: 'model_pick' } }],
258
270
  };
259
271
  }
272
+ const selectedModel = flat.find((opt) => opt.id === curModelId);
273
+ const efforts = Array.isArray(selectedModel?.reasoning?.efforts)
274
+ ? selectedModel.reasoning.efforts.filter((effort) => typeof effort?.id === 'string' && effort.id)
275
+ : [];
276
+ if (efforts.length > 0) {
277
+ const currentEffort = curModel?.reasoningEffort ?? selectedModel.reasoning.defaultEffort;
278
+ const effortOptions = [
279
+ { id: REASONING_DEFAULT_SENTINEL, name: t('默认等级') },
280
+ ...efforts.map((effort) => ({ id: effort.id, name: effort.name || effort.id })),
281
+ ].map((effort) => ({
282
+ text: { tag: 'plain_text', content: `${effort.id === (currentEffort ?? REASONING_DEFAULT_SENTINEL) ? '✓ ' : ''}${effort.name}` },
283
+ value: effort.id,
284
+ }));
285
+ reasoningDropdown = {
286
+ tag: 'select_static',
287
+ name: 'reasoning_pick',
288
+ placeholder: { tag: 'plain_text', content: t('切换推理等级') },
289
+ initial_index: initialIndex(effortOptions, currentEffort ?? REASONING_DEFAULT_SENTINEL),
290
+ options: effortOptions,
291
+ behaviors: [{ type: 'callback', value: { action: 'reasoning_pick' } }],
292
+ };
293
+ }
260
294
 
261
295
  // 渲染 2×2 网格:图标 + 下拉并列
262
296
  // 每一行用 4 列 column_set:图标 | 下拉 | 图标 | 下拉
@@ -291,6 +325,12 @@ export function menuCard(ctx) {
291
325
  tag: 'column_set', flex_mode: 'none',
292
326
  columns: [iconCol('🤖'), dropdownCol(row2[0]), iconCol('🧠'), dropdownCol(row2[1])],
293
327
  });
328
+ if (reasoningDropdown) {
329
+ elements.push({
330
+ tag: 'column_set', flex_mode: 'none',
331
+ columns: [iconCol('🧠'), dropdownCol(reasoningDropdown)],
332
+ });
333
+ }
294
334
 
295
335
  // 新会话 + 全部会话按钮
296
336
  const sessionButtons = buttonPair(newSessionLabel, 'new', t('📋 会话/关注'), 'sessions');
@@ -419,46 +459,52 @@ export function presetCard(catalog) {
419
459
  * The catalog comes from `harness.listModels()` or `session.models()`.
420
460
  * Groups are shown as text, then a flat dropdown for selection.
421
461
  */
422
- export function modelCard(catalog) {
462
+ export function modelCard(catalog, { page = 0 } = {}) {
423
463
  const { groups, current } = catalog;
424
464
  const currentId = current ? `${current.provider}/${current.model}` : null;
465
+ const allModels = groups.flatMap((group) => group.models.map((model) => ({
466
+ group, model, id: `${group.id}/${model.id}`,
467
+ })));
468
+ const pages = Math.max(1, Math.ceil(allModels.length / MODEL_PAGE_SIZE));
469
+ const selectedPage = Number.isSafeInteger(page) && page >= 0 ? Math.min(page, pages - 1) : 0;
470
+ const currentOrdinal = currentId ? allModels.findIndex((entry) => entry.id === currentId) : -1;
471
+ const visibleModels = allModels.slice(selectedPage * MODEL_PAGE_SIZE, (selectedPage + 1) * MODEL_PAGE_SIZE);
425
472
 
426
473
  const elements = [
427
474
  { tag: 'div', text: markdown(t('**当前模型**:{model}', { model: currentId || t('未设置') })) },
428
475
  { tag: 'hr' },
429
476
  ];
430
477
 
431
- // Count total models
432
- let total = 0;
433
- for (const group of groups) total += group.models.length;
434
-
435
- if (total === 0) {
478
+ if (allModels.length === 0) {
436
479
  elements.push(
437
480
  { tag: 'div', text: markdown(t('当前没有可用模型。')) },
438
481
  backButton(),
439
482
  );
440
483
  } else {
441
- // Show groups as text
484
+ const currentUnavailable = currentId && currentOrdinal < 0;
485
+ elements.push({ tag: 'div', text: markdown(t('第 {page}/{pages} 页 · 共 {total} 个模型', {
486
+ page: selectedPage + 1, pages, total: allModels.length,
487
+ })) });
488
+ if (currentUnavailable) elements.push({ tag: 'div', text: markdown(t('当前模型不可用:{model}', { model: currentId })) });
489
+ // Bound the Markdown and the picker together, so a large catalog does not
490
+ // produce an oversized card or silently hide selectable entries.
442
491
  for (const group of groups) {
443
- const modelLines = group.models.map((m) => {
444
- const id = `${group.id}/${m.id}`;
445
- return `${id}${id === currentId ? ' ✓' : ''}`;
446
- });
447
- elements.push(
492
+ const modelLines = visibleModels.filter((entry) => entry.group === group).map(({ id }) => (
493
+ `${id}${id === currentId ? ' ✓' : ''}`
494
+ ));
495
+ if (modelLines.length) elements.push(
448
496
  { tag: 'div', text: markdown(`**${group.name}**\n${modelLines.join('\n')}`) },
449
497
  );
450
498
  }
451
499
 
452
- // Flatten all models into a dropdown
453
- const allOptions = [];
454
- for (const group of groups) {
455
- for (const model of group.models) {
456
- allOptions.push({
457
- value: `${group.id}/${model.id}`,
458
- text: { tag: 'plain_text', content: `${group.name} - ${model.name}` },
459
- });
460
- }
461
- }
500
+ const allOptions = visibleModels.map(({ group, model, id }) => ({
501
+ value: id,
502
+ text: { tag: 'plain_text', content: `${group.name} - ${model.name}`.slice(0, MODEL_CARD_TEXT_LIMIT) },
503
+ }));
504
+ const currentOption = allModels.find((entry) => entry.id === currentId)?.model;
505
+ const efforts = Array.isArray(currentOption?.reasoning?.efforts)
506
+ ? currentOption.reasoning.efforts.filter((effort) => typeof effort?.id === 'string' && effort.id)
507
+ : [];
462
508
 
463
509
  elements.push(
464
510
  { tag: 'hr' },
@@ -473,9 +519,34 @@ export function modelCard(catalog) {
473
519
  })),
474
520
  behaviors: [{ type: 'callback', value: { action: 'model_pick' } }],
475
521
  },
476
- { tag: 'hr' },
477
- backButton(),
478
522
  );
523
+ if (efforts.length > 0) {
524
+ const currentEffort = current?.reasoningEffort ?? currentOption.reasoning.defaultEffort;
525
+ const effortOptions = [
526
+ { id: REASONING_DEFAULT_SENTINEL, name: t('默认等级') },
527
+ ...efforts.map((effort) => ({ id: effort.id, name: effort.name || effort.id })),
528
+ ].map((effort) => ({
529
+ text: { tag: 'plain_text', content: `${effort.id === (currentEffort ?? REASONING_DEFAULT_SENTINEL) ? '✓ ' : ''}${effort.name}` },
530
+ value: effort.id,
531
+ }));
532
+ elements.push({
533
+ tag: 'select_static',
534
+ name: 'reasoning_pick',
535
+ placeholder: { tag: 'plain_text', content: t('切换推理等级') },
536
+ initial_index: initialIndex(effortOptions, currentEffort ?? REASONING_DEFAULT_SENTINEL),
537
+ options: effortOptions,
538
+ behaviors: [{ type: 'callback', value: { action: 'reasoning_pick' } }],
539
+ });
540
+ }
541
+ if (pages > 1) {
542
+ elements.push(buttonPair(
543
+ selectedPage > 0 ? t('◀ 上一页') : t('第一页'),
544
+ selectedPage > 0 ? `models:${selectedPage - 1}` : 'models:0',
545
+ selectedPage + 1 < pages ? t('下一页 ▶') : t('最后一页'),
546
+ selectedPage + 1 < pages ? `models:${selectedPage + 1}` : `models:${pages - 1}`,
547
+ ));
548
+ }
549
+ elements.push({ tag: 'hr' }, backButton());
479
550
  }
480
551
  return cardWith(t('🧠 模型列表'), elements);
481
552
  }
@@ -1,6 +1,6 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { ApiError } from '@tencent-connect/qqbot-nodejs';
3
- import { workspacePathSnapshot } from '../shared/workspace-command.mjs';
3
+ import { conversationSessionWorkspace, workspacePathSnapshot } from '../shared/workspace-command.mjs';
4
4
  import { t } from '../shared/i18n.mjs';
5
5
 
6
6
  export const QQ_MENU_TTL_MS = 15 * 60_000;
@@ -88,8 +88,7 @@ async function catalogFor(harness, sessionId, key, options) {
88
88
 
89
89
  export async function qqMenuView(name, harness, state, key, { signal, busy = false } = {}) {
90
90
  const workspace = harness.currentWorkspace?.();
91
- const sessionWorkspace = typeof harness.currentConversationWorkspace === 'function'
92
- ? harness.currentConversationWorkspace(key) : workspace;
91
+ const sessionWorkspace = await conversationSessionWorkspace(harness, key, { signal });
93
92
  const sessionId = state.sessionFor(key);
94
93
  const options = { signal };
95
94
  const archived = state.includesArchivedSessions?.() === true;
@@ -97,7 +96,7 @@ export async function qqMenuView(name, harness, state, key, { signal, busy = fal
97
96
  if (name === 'main' || name === 'status') {
98
97
  if (name === 'status') await harness.ensureRunning(options);
99
98
  const results = await Promise.allSettled([
100
- harness.listWorkspaceSessions?.(name === 'main' ? sessionWorkspace : workspace, options),
99
+ harness.listWorkspaceSessions?.(sessionWorkspace, options),
101
100
  catalogFor(harness, sessionId, key, options),
102
101
  harness.agentPresetSettings?.(options),
103
102
  ]);