@xmanrui/dsh-im 4.38.2 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.en.md +10 -2
  2. package/README.md +10 -2
  3. package/lib/client.js +7 -4
  4. package/lib/index.js +311 -306
  5. package/package.json +4 -3
  6. package/plugin-src/host/injected-context.mjs +13 -1
  7. package/plugin-src/host/modern-harness-api.mjs +10 -4
  8. package/src/channels/matrix/matrix-api.mjs +34 -0
  9. package/src/channels/matrix/matrix-config-store.mjs +50 -2
  10. package/src/channels/matrix/matrix-normalize.mjs +106 -14
  11. package/src/channels/matrix/matrix-room-history.mjs +240 -8
  12. package/src/channels/matrix/matrix-runtime.mjs +563 -3
  13. package/src/channels/qq/qq-bridge.mjs +147 -1
  14. package/src/channels/qq/state-store.mjs +89 -0
  15. package/src/channels/shared/context-enhancement.mjs +2 -0
  16. package/src/channels/shared/conversation/ambient-provider.mjs +115 -0
  17. package/src/channels/shared/conversation/context-builder.mjs +148 -0
  18. package/src/channels/shared/conversation/reply-context.mjs +95 -0
  19. package/src/channels/shared/conversation/root-context.mjs +101 -0
  20. package/src/channels/shared/conversation/route.mjs +71 -0
  21. package/src/channels/shared/conversation/semantic-message.mjs +75 -0
  22. package/src/channels/shared/conversation/trigger-policy.mjs +80 -0
  23. package/src/channels/shared/conversation-state-store.mjs +95 -1
  24. package/src/channels/shared/deferred-delivery-coordinator.mjs +5 -1
  25. package/src/channels/shared/harness-approval.mjs +19 -0
  26. package/src/channels/shared/harness-client.mjs +9 -1
  27. package/src/channels/shared/i18n-en/shared-a.mjs +2 -0
  28. package/src/channels/shared/i18n-en/shared-b.mjs +2 -0
  29. package/src/channels/shared/injected-context.mjs +64 -2
  30. package/src/channels/shared/prompt-failure-tracker.mjs +65 -0
  31. package/src/channels/shared/speaker-label.mjs +46 -0
  32. package/src/channels/shared/text-harness-bridge.mjs +504 -33
  33. package/src/channels/wecom/wecom-cards.mjs +1 -1
@@ -34,7 +34,7 @@ import {
34
34
  runPresetCommand,
35
35
  } from './preset-command.mjs';
36
36
  import { askInWorkspaceSession } from './workspace-session.mjs';
37
- import { HarnessApprovalQueue } from './harness-approval.mjs';
37
+ import { HarnessApprovalQueue, harnessApprovalDecision } from './harness-approval.mjs';
38
38
  import {
39
39
  BatchInputManager,
40
40
  batchInputBusyMessage,
@@ -56,6 +56,7 @@ import {
56
56
  validHarnessQuestion,
57
57
  } from './harness-question.mjs';
58
58
  import { deliverOutboundArtifacts } from './semantic/artifact-delivery.mjs';
59
+ import { prependSpeakerLabel } from './speaker-label.mjs';
59
60
  import {
60
61
  hasReplyReference,
61
62
  promptContentForInboundMessage,
@@ -85,6 +86,8 @@ const FILE_ONLY_COMPLETION_TEXT = '任务已完成。';
85
86
  * attempts the mark stays and the message is treated as handled.
86
87
  */
87
88
  const MAX_DELIVERY_ATTEMPTS = 3;
89
+ /** How many plain-text messages one coalescing window folds into one dispatch. */
90
+ const MAX_COALESCE_MEMBERS = 8;
88
91
 
89
92
  function cleanText(value) {
90
93
  return typeof value === 'string' ? value.trim() : '';
@@ -165,6 +168,13 @@ function controlTextOf(message) {
165
168
  return cleanText(message?.controlText ?? message?.content);
166
169
  }
167
170
 
171
+ /** Durable queue-entry id; the conversation key keeps ids unique across chats. */
172
+ function pendingMessageId(key, messageId) {
173
+ return `${key}\u0000${messageId}`;
174
+ }
175
+
176
+ const PENDING_RESTART_NOTICE = '排队中的消息在服务重启时被中断。为避免重复执行,未自动重放;如果该消息尚未处理,请重新发送。';
177
+
168
178
  export class TextHarnessBridge {
169
179
  #descriptor;
170
180
  #bot;
@@ -180,6 +190,8 @@ export class TextHarnessBridge {
180
190
  #signal;
181
191
  #keepaliveIntervalMs;
182
192
  #queues = new Map();
193
+ // Crash-recovery for #queues, started with the bridge; see recoverPendingMessages().
194
+ #pendingRecovery = null;
183
195
  #busyMessages = new BusyMessageDispatcher();
184
196
  #pendingInteractions = new Map();
185
197
  #interactionKeys = new Map();
@@ -190,10 +202,18 @@ export class TextHarnessBridge {
190
202
  #approvals;
191
203
  #batches = new BatchInputManager();
192
204
  #interactionCard;
205
+ #contextHooks = null;
193
206
  // Delivery attempts per message id. A failed turn releases its `markSeen` so
194
207
  // the next poll can retry, and this counter is what keeps that from becoming
195
208
  // an infinite loop on a mail that always fails.
196
209
  #deliveryAttempts = new Map();
210
+ // Who opened the in-flight turn per conversation key, for the same-sender
211
+ // auto-steer lane; and the open coalescing windows awaiting their flush.
212
+ #turnAuthors = new Map();
213
+ #coalescing = new Map();
214
+ #autoSteerSameSender = false;
215
+ #autoSteerLimit = 0;
216
+ #coalesceWindowMs = 0;
197
217
 
198
218
  constructor({
199
219
  descriptor,
@@ -209,6 +229,10 @@ export class TextHarnessBridge {
209
229
  signal,
210
230
  keepaliveIntervalMs = 4_000,
211
231
  interactionCard = null,
232
+ contextHooks = null,
233
+ autoSteerSameSender = false,
234
+ autoSteerLimit = 0,
235
+ coalesceWindowMs = 0,
212
236
  }) {
213
237
  if (!descriptor?.key || !descriptor?.label) throw new TypeError('A channel descriptor is required');
214
238
  if (!bot || typeof bot.sendText !== 'function') throw new TypeError('A bot client is required');
@@ -226,6 +250,23 @@ export class TextHarnessBridge {
226
250
  this.#signal = signal;
227
251
  this.#keepaliveIntervalMs = keepaliveIntervalMs;
228
252
  this.#interactionCard = interactionCard ?? null;
253
+ // Opt-in follow-up lanes for channels whose groups run on rapid consecutive
254
+ // posts: fold a same sender's burst into one dispatch, and steer that
255
+ // sender's own mid-turn follow-ups into the in-flight turn instead of
256
+ // queueing them behind the answer they are meant to correct. Off unless a
257
+ // channel asks for them, so every other channel keeps the plain queue.
258
+ this.#autoSteerSameSender = autoSteerSameSender === true;
259
+ this.#autoSteerLimit = Number.isSafeInteger(autoSteerLimit) && autoSteerLimit > 0
260
+ ? Math.min(autoSteerLimit, 20)
261
+ : 0;
262
+ this.#coalesceWindowMs = Number.isSafeInteger(coalesceWindowMs) && coalesceWindowMs > 0
263
+ ? Math.min(coalesceWindowMs, 3_000)
264
+ : 0;
265
+ // Channel-supplied conversation context pipeline (collect/render/consume/deliver).
266
+ // Channels own what context means and how it is framed; the bridge only runs
267
+ // the steps at the right points of one turn, so every hook is optional and a
268
+ // channel without one pays no context work at all.
269
+ this.#contextHooks = contextHooks && typeof contextHooks === 'object' ? contextHooks : null;
229
270
  this.#deferred = createDeferredDeliveryCoordinator({ harness, state, signal, logger,
230
271
  deliver: (entry, outcome) => this.#deliverDeferredOutcome(entry, outcome),
231
272
  });
@@ -233,6 +274,10 @@ export class TextHarnessBridge {
233
274
  label: descriptor.key,
234
275
  logger,
235
276
  });
277
+ // A queued message lives only in #queues. If the process dies before its
278
+ // turn runs the user has already been told it is queued, so the persisted
279
+ // entry must be replayed or reported as soon as the bridge starts.
280
+ this.recoverPendingMessages();
236
281
  }
237
282
 
238
283
  get status() {
@@ -410,6 +455,31 @@ export class TextHarnessBridge {
410
455
  this.#commandTasks.add(task);
411
456
  return task;
412
457
  }
458
+ // An addressed plain-text request that is no approve/reject token while only
459
+ // an approval waits is the sender moving on, not a decision: reject the
460
+ // waiting tool call and run this message as its own turn, so the room is not
461
+ // held behind a decision that is not coming. A pending question keeps its
462
+ // ordinary flow — the asking actor's @ text answers it, and other senders
463
+ // queue behind the turn (questions belong to the asking actor). Direct chats
464
+ // keep the plain decide-by-token path; their exits are the commands.
465
+ const addressedTrigger = normalized.kind === 'group' && normalized.addressed === true
466
+ && normalized.plainText !== false
467
+ && !hasInboundImages(normalized) && !hasInboundFiles(normalized)
468
+ && Boolean(text);
469
+ if (addressedTrigger && !pending
470
+ && this.#approvals.hasPending(key) && harnessApprovalDecision(text) === null) {
471
+ let task;
472
+ task = this.#retireWaitingInteractions(key, pending)
473
+ .then(() => this.#bot.sendText(normalized.replyTarget, t('已不再等待原有的待回答或待审批,已将其取消,先回应你的新请求。')))
474
+ .catch(() => undefined)
475
+ .then(() => this.#dispatchTrigger(normalized, messageId, senderId, key))
476
+ .finally(() => {
477
+ this.#acceptedMessageIds.delete(messageId);
478
+ this.#commandTasks.delete(task);
479
+ });
480
+ this.#commandTasks.add(task);
481
+ return task;
482
+ }
413
483
  const approval = this.#approvals.claimReply({
414
484
  key,
415
485
  actor: senderId,
@@ -474,35 +544,187 @@ export class TextHarnessBridge {
474
544
  pending.queue = current;
475
545
  return current;
476
546
  }
477
- return this.#busyMessages.dispatch({
478
- key, messageId, text: normalized.content,
479
- commandText: text, mode: busyMessageMode,
480
- onFailure: (error) => this.#signal?.aborted || error?.code === 'turn-stopped'
481
- ? normalized.statusReaction?.clear() : normalized.statusReaction?.error(),
482
- eligible: () => normalized.plainText !== false
483
- && !hasInboundImages(normalized) && !hasInboundFiles(normalized)
484
- && !hasReplyReference(normalized)
485
- && canAutomaticallySteer(this.#accessPolicy, normalized.kind,
486
- [senderId, normalized.senderAlternateId].filter(Boolean)),
487
- harness: this.#harness, state: this.#state, status: this.#status,
488
- signal: this.#signal, control: { owner: this, key }, logger: this.#logger,
489
- acceptedMessageIds: this.#acceptedMessageIds,
490
- pendingInteraction: () => this.#pendingInteractions.has(key) || this.#approvals.hasPending(key),
491
- enhancement: {
492
- snapshot: this.#acceptedMessageIds.get(messageId),
493
- source: () => {
494
- const source = normalized.contextSource?.();
495
- return { channel: this.#descriptor.key, senderId, senderName: source?.senderName,
496
- conversationTitle: source?.conversationTitle,
497
- chatId: source?.chatId ?? normalized.conversationId, threadId: source?.threadId };
547
+ return this.#dispatchTrigger(normalized, messageId, senderId, key, {
548
+ // Ordinary destinations of the lanes fall through to the busy-mode dispatcher,
549
+ // keeping its steering, receipts, and routing serialization for what the lanes decline.
550
+ exit: (exitOptions) => this.#busyMessages.dispatch({
551
+ key, messageId, text: normalized.content,
552
+ commandText: text, mode: busyMessageMode,
553
+ onFailure: (error) => this.#signal?.aborted || error?.code === 'turn-stopped'
554
+ ? normalized.statusReaction?.clear() : normalized.statusReaction?.error(),
555
+ eligible: () => normalized.plainText !== false
556
+ && !hasInboundImages(normalized) && !hasInboundFiles(normalized)
557
+ && !hasReplyReference(normalized)
558
+ && canAutomaticallySteer(this.#accessPolicy, normalized.kind,
559
+ [senderId, normalized.senderAlternateId].filter(Boolean)),
560
+ harness: this.#harness, state: this.#state, status: this.#status,
561
+ signal: this.#signal, control: { owner: this, key }, logger: this.#logger,
562
+ acceptedMessageIds: this.#acceptedMessageIds,
563
+ pendingInteraction: () => this.#pendingInteractions.has(key) || this.#approvals.hasPending(key),
564
+ enhancement: {
565
+ snapshot: this.#acceptedMessageIds.get(messageId),
566
+ source: () => {
567
+ const source = normalized.contextSource?.();
568
+ return { channel: this.#descriptor.key, senderId, senderName: source?.senderName,
569
+ conversationTitle: source?.conversationTitle,
570
+ chatId: source?.chatId ?? normalized.conversationId, threadId: source?.threadId };
571
+ },
498
572
  },
499
- },
500
- isQueued: () => this.#queues.has(key),
501
- enqueue: (options) => this.#enqueueMessage(normalized, messageId, senderId, key, options),
502
- send: (reply) => this.#bot.sendText(normalized.replyTarget, reply),
573
+ isQueued: () => this.#queues.has(key),
574
+ enqueue: (enqueueOptions) => this.#enqueueMessage(normalized, messageId, senderId, key, enqueueOptions),
575
+ send: (reply) => this.#bot.sendText(normalized.replyTarget, reply),
576
+ }),
503
577
  });
504
578
  }
505
579
 
580
+ /**
581
+ * The ordinary trigger exit, where a message becomes a turn. Three lanes:
582
+ * while the conversation runs, a plain-text follow-up from the very sender
583
+ * who opened the in-flight turn steers that turn (the room hears the
584
+ * correction at the next model step instead of after the whole answer);
585
+ * on an idle conversation, consecutive plain-text posts from one sender fold
586
+ * into a single dispatch inside a short window, so a burst split across
587
+ * bubbles becomes one turn; everything else — other senders, media, composed
588
+ * payloads — keeps the per-conversation queue that preserves one voice at a
589
+ * time.
590
+ * An `exit` hook, when provided, receives every ordinary queue destination of
591
+ * the lanes, so a channel can fall through to richer routing (busy-mode steering
592
+ * and queue receipts) for what these lanes decline.
593
+ */
594
+ #dispatchTrigger(message, messageId, senderId, key, { exit } = {}) {
595
+ const toQueue = (options) => (exit
596
+ ? exit(options)
597
+ : this.#enqueueMessage(message, messageId, senderId, key, options));
598
+ const plainText = !hasInboundImages(message) && !hasInboundFiles(message)
599
+ && message.plainText !== false
600
+ && Boolean(controlTextOf(message));
601
+ const author = this.#turnAuthors.get(key);
602
+ if (author !== undefined && plainText
603
+ && this.#autoSteerSameSender && this.#autoSteerLimit > 0
604
+ && author.senderId === senderId && author.steered < this.#autoSteerLimit) {
605
+ const text = this.#steerTextFor(message, messageId, senderId);
606
+ const sessionId = this.#state.sessionFor?.(key) ?? null;
607
+ if (text && sessionId !== null && typeof this.#harness.steerActiveTurn === 'function') {
608
+ return this.#harness
609
+ .steerActiveTurn(sessionId, text, { owner: this, key }, this.#signal ? { signal: this.#signal } : undefined)
610
+ .then((steered) => (steered
611
+ ? this.#settleSteeredTurn(author, messageId, key)
612
+ : toQueue()))
613
+ .catch(() => toQueue());
614
+ }
615
+ }
616
+ if (!this.#queues.has(key) && !this.#pendingInteractions.has(key) && !this.#approvals.hasPending(key)) {
617
+ const open = this.#coalescing.get(key);
618
+ if (open !== undefined) {
619
+ if (open.senderId === senderId && plainText && open.members.length < MAX_COALESCE_MEMBERS) {
620
+ open.members.push({ message, messageId });
621
+ return Promise.resolve();
622
+ }
623
+ // A different sender, or a payload the window may not fold: this
624
+ // message dispatches on its own while the window keeps collecting.
625
+ return toQueue();
626
+ }
627
+ if (this.#coalesceWindowMs > 0 && plainText) {
628
+ const opened = { senderId, members: [{ message, messageId }] };
629
+ const timer = setTimeout(() => { void this.#flushCoalesced(key); }, this.#coalesceWindowMs);
630
+ timer.unref?.();
631
+ this.#coalescing.set(key, opened);
632
+ return Promise.resolve();
633
+ }
634
+ }
635
+ return toQueue();
636
+ }
637
+
638
+ /**
639
+ * Tag a turn's own delivery target with its conversation key so the channel can
640
+ * retire the resulting bubble from that conversation's ambient window: the text
641
+ * is in the Session transcript already. Local notices, command output, and
642
+ * interaction prompts send on unstamped targets and stay readable as room facts.
643
+ */
644
+ #turnDeliveryTarget(target, conversationKey) {
645
+ if (!target || typeof target !== 'object'
646
+ || typeof conversationKey !== 'string' || !conversationKey) return target;
647
+ return { ...target, dshTurnKey: conversationKey };
648
+ }
649
+
650
+ /** The model-facing body of an auto-steered follow-up, labelled like a turn. */
651
+ #steerTextFor(message, messageId, senderId) {
652
+ const body = cleanText(message.content) || controlTextOf(message);
653
+ if (!body) return null;
654
+ const labelled = message.kind === 'group' ? prependSpeakerLabel(body, message.speakerName) : body;
655
+ const snapshot = this.#acceptedMessageIds.get(messageId);
656
+ if (!snapshot) return labelled;
657
+ // A mid-turn follow-up carries the same provenance as the message that
658
+ // opened the turn, so the member who steers is identified to the model too.
659
+ const contextSource = message.contextSource?.();
660
+ return enhanceContextContent(labelled, snapshot, () => ({
661
+ channel: this.#descriptor.key,
662
+ senderId,
663
+ senderName: contextSource?.senderName,
664
+ conversationTitle: contextSource?.conversationTitle,
665
+ chatId: contextSource?.chatId ?? message.conversationId,
666
+ threadId: contextSource?.threadId,
667
+ }));
668
+ }
669
+
670
+ /** A steered message became part of the in-flight turn: settle its receipt. */
671
+ async #settleSteeredTurn(author, messageId, key) {
672
+ author.steered += 1;
673
+ if (!this.#state.hasSeen(messageId)) await this.#state.markSeen(messageId);
674
+ this.#status.messagesReceived += 1;
675
+ this.#status.lastMessageAt = new Date().toISOString();
676
+ this.#acceptedMessageIds.delete(messageId);
677
+ // The steered body now lives in the in-flight turn, just like a folded
678
+ // coalescer member: the channel retires its bubble from the ambient window
679
+ // with the turn instead of re-serving text this session has taken in.
680
+ if (this.#contextHooks?.onSteered) {
681
+ void Promise.resolve(this.#contextHooks.onSteered({ conversationKey: key, messageId }))
682
+ .catch((error) => {
683
+ this.#logger.warn?.(
684
+ `[dsh-im:${this.#descriptor.key}] could not retire a steered follow-up from the ambient window:`,
685
+ error?.message ?? error,
686
+ );
687
+ });
688
+ }
689
+ return true;
690
+ }
691
+
692
+ /**
693
+ * Dispatch a folded window as one turn: the merged body carries every
694
+ * member's text, the answer targets the newest message, and the extra
695
+ * members travel as `coalescedEventIds` so the channel ledger can retire
696
+ * them from its ambient window before it re-serves what this turn already
697
+ * says.
698
+ */
699
+ async #flushCoalesced(key) {
700
+ const open = this.#coalescing.get(key);
701
+ if (open === undefined) return;
702
+ this.#coalescing.delete(key);
703
+ if (this.#signal?.aborted) {
704
+ for (const member of open.members) this.#acceptedMessageIds.delete(member.messageId);
705
+ return;
706
+ }
707
+ const bodies = [];
708
+ for (const member of open.members) {
709
+ const body = cleanText(member.message.content) || controlTextOf(member.message);
710
+ if (body && !bodies.includes(body)) bodies.push(body);
711
+ this.#acceptedMessageIds.delete(member.messageId);
712
+ if (!this.#state.hasSeen(member.messageId)) await this.#state.markSeen(member.messageId);
713
+ this.#status.messagesReceived += 1;
714
+ }
715
+ if (bodies.length === 0) return;
716
+ this.#status.lastMessageAt = new Date().toISOString();
717
+ const last = open.members[open.members.length - 1];
718
+ const merged = {
719
+ ...last.message,
720
+ content: bodies.join('\n\n'),
721
+ ...(open.members.length > 1
722
+ ? { coalescedEventIds: open.members.slice(0, -1).map((member) => member.messageId) }
723
+ : {}),
724
+ };
725
+ return this.#enqueueMessage(merged, last.messageId, open.senderId, key, { alreadyRecorded: true });
726
+ }
727
+
506
728
  #finishLocalMessage(message, messageId, reply, { recordReceived = true } = {}) {
507
729
  let task;
508
730
  task = (async () => {
@@ -538,9 +760,13 @@ export class TextHarnessBridge {
538
760
  releaseMessageId = true,
539
761
  alreadyRecorded = false,
540
762
  } = {}) {
763
+ // Persist before the message joins the in-memory chain: the chain may wait
764
+ // behind a long turn, and a restart in that window must not lose the input.
765
+ const pending = this.#recordPendingMessage(message, messageId, senderId, key);
541
766
  const previous = this.#queues.get(key) ?? Promise.resolve();
542
767
  const current = previous
543
768
  .catch(() => undefined)
769
+ .then(() => pending)
544
770
  .then(() => this.#process(
545
771
  message,
546
772
  messageId,
@@ -548,14 +774,147 @@ export class TextHarnessBridge {
548
774
  key,
549
775
  { alreadyRecorded },
550
776
  ))
551
- .finally(() => {
777
+ .finally(async () => {
552
778
  if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
553
779
  if (this.#queues.get(key) === current) this.#queues.delete(key);
780
+ await this.#removePendingMessage(pendingMessageId(key, messageId));
554
781
  });
555
782
  this.#queues.set(key, current);
556
783
  return current;
557
784
  }
558
785
 
786
+ /**
787
+ * Replay (submitted: false) or report (submitted: true) the messages this
788
+ * bridge persisted before a restart. Idempotent: each entry is removed as it
789
+ * is handled, and the returned promise is shared with waitForIdle().
790
+ */
791
+ recoverPendingMessages() {
792
+ this.#pendingRecovery ??= this.#recoverPendingMessages().catch((error) => {
793
+ this.#logger.warn?.(
794
+ `[dsh-im:${this.#descriptor.key}] queued-message recovery failed:`,
795
+ error?.message ?? error,
796
+ );
797
+ });
798
+ return this.#pendingRecovery;
799
+ }
800
+
801
+ async #recoverPendingMessages() {
802
+ if (typeof this.#state?.pendingMessages !== 'function') return;
803
+ const entries = this.#state.pendingMessages();
804
+ if (!Array.isArray(entries) || entries.length === 0) return;
805
+ for (const entry of entries) {
806
+ if (!entry || this.#signal?.aborted) return;
807
+ try {
808
+ if (entry.submitted === true) {
809
+ await this.#notifyInterruptedPending(entry);
810
+ await this.#removePendingMessage(entry.id);
811
+ continue;
812
+ }
813
+ this.#logger.warn?.(
814
+ `[dsh-im:${this.#descriptor.key}] replaying a queued message that a restart interrupted:`,
815
+ entry.messageId,
816
+ );
817
+ // The turn never reached Harness, so any earlier mark-seen is an
818
+ // attempt, not a completed delivery; clear it so the replay can run.
819
+ if (typeof this.#state.unmarkSeen === 'function') {
820
+ await this.#state.unmarkSeen(entry.messageId).catch(() => undefined);
821
+ }
822
+ await this.#replayPendingMessage(entry);
823
+ } catch (error) {
824
+ this.#logger.warn?.(
825
+ `[dsh-im:${this.#descriptor.key}] failed to recover a queued message:`,
826
+ entry?.messageId,
827
+ error?.message ?? error,
828
+ );
829
+ }
830
+ }
831
+ }
832
+
833
+ #recordPendingMessage(message, messageId, senderId, key) {
834
+ if (typeof this.#state?.putPendingMessage !== 'function') return Promise.resolve();
835
+ const text = controlTextOf(message);
836
+ if (!text) return Promise.resolve();
837
+ const entry = {
838
+ id: pendingMessageId(key, messageId),
839
+ key,
840
+ messageId,
841
+ kind: message.kind === 'group' ? 'group' : 'direct',
842
+ text,
843
+ submitted: false,
844
+ createdAt: new Date().toISOString(),
845
+ ...(senderId ? { senderId } : {}),
846
+ ...(message.replyTarget !== undefined ? { target: message.replyTarget } : {}),
847
+ };
848
+ return this.#state.putPendingMessage(entry).catch((error) => {
849
+ this.#logger.warn?.(
850
+ `[dsh-im:${this.#descriptor.key}] failed to persist a queued message:`,
851
+ error?.message ?? error,
852
+ );
853
+ });
854
+ }
855
+
856
+ async #markPendingSubmitted(key, messageId) {
857
+ if (typeof this.#state?.patchPendingMessage !== 'function') return;
858
+ await this.#state.patchPendingMessage(pendingMessageId(key, messageId), { submitted: true });
859
+ }
860
+
861
+ async #removePendingMessage(id) {
862
+ if (typeof this.#state?.removePendingMessage !== 'function') return;
863
+ try {
864
+ await this.#state.removePendingMessage(id);
865
+ } catch (error) {
866
+ this.#logger.warn?.(
867
+ `[dsh-im:${this.#descriptor.key}] failed to clear a queued-message entry:`,
868
+ error?.message ?? error,
869
+ );
870
+ }
871
+ }
872
+
873
+ #replayPendingMessage(entry) {
874
+ const message = this.#pendingReplayMessage(entry);
875
+ if (!message) return Promise.resolve();
876
+ return this.#enqueueMessage(message, entry.messageId, entry.senderId ?? '', entry.key);
877
+ }
878
+
879
+ #pendingReplayMessage(entry) {
880
+ const separator = String(entry.key).indexOf(':');
881
+ if (separator < 0) return null;
882
+ const kind = entry.key.slice(0, separator);
883
+ const conversationId = entry.key.slice(separator + 1);
884
+ if (!conversationId || !entry.messageId) return null;
885
+ // Rebuild exactly the turn fields the queue path reads, so the recovered
886
+ // text is dispatched as the user's own message with no added framing.
887
+ return {
888
+ messageId: entry.messageId,
889
+ senderId: entry.senderId ?? '',
890
+ kind: kind === 'group' ? 'group' : 'direct',
891
+ conversationId,
892
+ content: entry.text,
893
+ controlText: entry.text,
894
+ addressed: true,
895
+ plainText: true,
896
+ ...(entry.target !== undefined ? { replyTarget: entry.target } : {}),
897
+ };
898
+ }
899
+
900
+ async #notifyInterruptedPending(entry) {
901
+ if (entry.target === undefined || entry.target === null) {
902
+ this.#logger.warn?.(
903
+ `[dsh-im:${this.#descriptor.key}] a queued message was interrupted by a restart but has no delivery target:`,
904
+ entry.messageId,
905
+ );
906
+ return;
907
+ }
908
+ try {
909
+ await this.#bot.sendText(entry.target, t(PENDING_RESTART_NOTICE));
910
+ } catch (error) {
911
+ this.#logger.warn?.(
912
+ `[dsh-im:${this.#descriptor.key}] failed to report an interrupted queued message:`,
913
+ error?.message ?? error,
914
+ );
915
+ }
916
+ }
917
+
559
918
  async #deliverDeferredOutcome(entry, outcome) {
560
919
  const text = deferredOutcomeText(outcome);
561
920
  return typeof this.#bot.sendDelivery === 'function'
@@ -564,6 +923,7 @@ export class TextHarnessBridge {
564
923
  }
565
924
 
566
925
  async waitForIdle() {
926
+ await this.#pendingRecovery;
567
927
  await this.#busyMessages.whenIdle();
568
928
  await Promise.allSettled([
569
929
  ...this.#queues.values(),
@@ -572,6 +932,13 @@ export class TextHarnessBridge {
572
932
  )),
573
933
  ...this.#approvalTasks,
574
934
  ...this.#commandTasks,
935
+ // An unexpired coalescing window drains through its own timer: wait out
936
+ // its worst-case life so a shutdown never drops folded messages before
937
+ // the flush enqueues them for the queue wait below to cover.
938
+ ...this.#coalescing.values().map(() => new Promise((resolve) => {
939
+ const timer = setTimeout(resolve, this.#coalesceWindowMs + 25);
940
+ timer.unref?.();
941
+ })),
575
942
  ]);
576
943
  await this.#deferred.whenIdle();
577
944
  }
@@ -759,6 +1126,14 @@ export class TextHarnessBridge {
759
1126
  }
760
1127
  if (!hasImages && !hasFiles && command === '/new') {
761
1128
  await this.#state.clearSession(conversationKey);
1129
+ if (this.#contextHooks?.onSessionCleared) {
1130
+ try {
1131
+ await this.#contextHooks.onSessionCleared(conversationKey);
1132
+ } catch (error) {
1133
+ // The cleared session is already done; a failed context reset must not block the command.
1134
+ this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] failed to reset context anchors after /new:`, error?.message ?? error);
1135
+ }
1136
+ }
762
1137
  await this.#bot.sendText(target, t('已开启新会话。请发送你的问题。'));
763
1138
  return;
764
1139
  }
@@ -782,7 +1157,7 @@ export class TextHarnessBridge {
782
1157
  let streamFinished = false;
783
1158
  if (this.#thinkingTraces && typeof this.#bot.openThinkingStream === 'function') {
784
1159
  try {
785
- stream = await this.#bot.openThinkingStream(target);
1160
+ stream = await this.#bot.openThinkingStream(this.#turnDeliveryTarget(target, conversationKey));
786
1161
  thinkingStream = true;
787
1162
  } catch (error) {
788
1163
  stream = null;
@@ -795,7 +1170,7 @@ export class TextHarnessBridge {
795
1170
  if (!stream) {
796
1171
  if (typeof this.#bot.openDeliveryStream === 'function') {
797
1172
  try {
798
- stream = await this.#bot.openDeliveryStream(target);
1173
+ stream = await this.#bot.openDeliveryStream(this.#turnDeliveryTarget(target, conversationKey));
799
1174
  semanticStream = true;
800
1175
  } catch (error) {
801
1176
  this.#logger.warn?.(
@@ -805,7 +1180,7 @@ export class TextHarnessBridge {
805
1180
  }
806
1181
  } else if (typeof this.#bot.openStream === 'function') {
807
1182
  try {
808
- stream = await this.#bot.openStream(target);
1183
+ stream = await this.#bot.openStream(this.#turnDeliveryTarget(target, conversationKey));
809
1184
  } catch (error) {
810
1185
  this.#logger.warn?.(
811
1186
  `[dsh-im:${this.#descriptor.key}] unable to start a streamed reply; using text:`,
@@ -825,6 +1200,11 @@ export class TextHarnessBridge {
825
1200
  let content = hasImages || hasReply
826
1201
  ? await promptContentForInboundMessage(message, { signal: this.#signal, deferImages: true })
827
1202
  : cleanText(message.content) || undefined;
1203
+ // A room conversation is shared by everyone who addresses the bot in it, so
1204
+ // the delivered prompt says whose turn this is. Only the model-facing content
1205
+ // is labelled; the parsed control text, commands, and ledger keys keep the
1206
+ // unlabelled body they were read from.
1207
+ if (message.kind === 'group') content = prependSpeakerLabel(content, message.speakerName);
828
1208
  const snapshot = this.#acceptedMessageIds.get(messageId);
829
1209
  let contextEnhanced = false;
830
1210
  if (snapshot) {
@@ -840,6 +1220,28 @@ export class TextHarnessBridge {
840
1220
  }));
841
1221
  contextEnhanced = content !== originalContent;
842
1222
  }
1223
+ // Collected after command handling so control commands never pay for a
1224
+ // context lookup, and only for a plain-text prompt: a composed or media
1225
+ // payload already carries its own structure and stays untouched.
1226
+ let contextEntries = null;
1227
+ if (this.#contextHooks?.collect && this.#contextHooks.enabled?.() !== false && !batchSubmission
1228
+ && (content === undefined || typeof content === 'string') && !hasImages && !hasFiles) {
1229
+ try {
1230
+ const collected = await this.#contextHooks.collect({
1231
+ message,
1232
+ conversationKey,
1233
+ sessionIdHint: this.#state.sessionFor?.(conversationKey) ?? null,
1234
+ });
1235
+ if (Array.isArray(collected) && collected.length > 0) {
1236
+ contextEntries = collected;
1237
+ const block = this.#contextHooks.render?.(collected) ?? '';
1238
+ if (block) content = `${block}\n\n${content ?? ''}`;
1239
+ }
1240
+ } catch (error) {
1241
+ // Context is an enhancement: a collector failure must not lose the user's own turn.
1242
+ this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] context collection failed; prompting without context:`, error?.message ?? error);
1243
+ }
1244
+ }
843
1245
  // Start the keepalive only after the inbound payload is ready, so a
844
1246
  // pre-prompt failure (image parsing, context building) cannot leave the
845
1247
  // timer running; the outermost finally below clears it on every path.
@@ -863,7 +1265,15 @@ export class TextHarnessBridge {
863
1265
  }, this.#keepaliveIntervalMs);
864
1266
  keepaliveTimer.unref?.();
865
1267
  }
866
- const { answer, artifacts = [] } = await askInWorkspaceSession({
1268
+ // From here the conversation has a turn in flight that this sender
1269
+ // opened: the auto-steer lane keys its authorship decision off this
1270
+ // record, and the finally below retires it when the turn settles.
1271
+ this.#turnAuthors.set(conversationKey, { senderId, steered: 0, turnMessageId: messageId });
1272
+ // The prompt is about to enter the Harness inbox, which is itself durable.
1273
+ // Marking the entry submitted first means a crash after this point reports
1274
+ // the message instead of replaying a turn the Harness may already own.
1275
+ await this.#markPendingSubmitted(conversationKey, messageId);
1276
+ const { sessionId, answer, artifacts = [] } = await askInWorkspaceSession({
867
1277
  deferredDelivery: () => ({ coordinator: this.#deferred, target: this.#descriptor.key === 'whatsapp' ? { jid: target.jid, selfChat: target.selfChat } : target }),
868
1278
  harness: this.#harness,
869
1279
  state: this.#state,
@@ -927,6 +1337,16 @@ export class TextHarnessBridge {
927
1337
  if (batchSubmission) {
928
1338
  this.#batches.complete(conversationKey, batchSubmission.token);
929
1339
  }
1340
+ // The completed turn consumed its context: ambient records stop being offered
1341
+ // and a thread-root anchor is stamped for this session. A failed ask throws
1342
+ // past this point, so a failed turn re-offers its context on the next message.
1343
+ if (contextEntries && this.#contextHooks?.onConsumed) {
1344
+ try {
1345
+ await this.#contextHooks.onConsumed({ conversationKey, sessionId, entries: contextEntries });
1346
+ } catch (error) {
1347
+ this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] context consumption marking failed:`, error?.message ?? error);
1348
+ }
1349
+ }
930
1350
  const fileOnlyCompletion = !cleanText(answer) && artifacts.length > 0;
931
1351
  const visibleAnswer = fileOnlyCompletion
932
1352
  ? t(FILE_ONLY_COMPLETION_TEXT)
@@ -962,12 +1382,13 @@ export class TextHarnessBridge {
962
1382
  }
963
1383
  if (!streamFinished) {
964
1384
  try {
1385
+ const answerTarget = this.#turnDeliveryTarget(target, conversationKey);
965
1386
  const result = typeof this.#bot.sendDelivery === 'function'
966
1387
  ? await this.#bot.sendDelivery(
967
- target,
1388
+ answerTarget,
968
1389
  createTextDeliveryBlock(visibleAnswer, answerFormat),
969
1390
  )
970
- : await this.#bot.sendText(target, visibleAnswer);
1391
+ : await this.#bot.sendText(answerTarget, visibleAnswer);
971
1392
  textReceipt = createDeliveryReceipt({
972
1393
  deliveryId: messageId,
973
1394
  presentation: result?.presentation ?? `${this.#descriptor.key}-text`,
@@ -1010,6 +1431,22 @@ export class TextHarnessBridge {
1010
1431
  }
1011
1432
  // The turn produced an answer, so its retry budget is spent and reset.
1012
1433
  this.#deliveryAttempts.delete(messageId);
1434
+ if (this.#contextHooks?.onDelivered) {
1435
+ const deliveredEventIds = [
1436
+ ...new Set([
1437
+ ...(Array.isArray(textReceipt?.providerMessageIds) ? textReceipt.providerMessageIds : []),
1438
+ ...(Array.isArray(delivery.receipt?.providerMessageIds) ? delivery.receipt.providerMessageIds : []),
1439
+ ]),
1440
+ ];
1441
+ if (deliveredEventIds.length > 0) {
1442
+ try {
1443
+ await this.#contextHooks.onDelivered({ conversationKey, sessionId, providerMessageIds: deliveredEventIds });
1444
+ } catch (error) {
1445
+ // A missing binding only costs reply classification quality for these events; the answer itself reached the room.
1446
+ this.#logger.warn?.(`[dsh-im:${this.#descriptor.key}] bot event binding recording failed:`, error?.message ?? error);
1447
+ }
1448
+ }
1449
+ }
1013
1450
  return delivery.receipt;
1014
1451
  } catch (error) {
1015
1452
  stopKeepalive();
@@ -1088,6 +1525,8 @@ export class TextHarnessBridge {
1088
1525
  return error.deliveryReceipt;
1089
1526
  } finally {
1090
1527
  stopKeepalive();
1528
+ const inFlight = this.#turnAuthors.get(conversationKey);
1529
+ if (inFlight?.turnMessageId === messageId) this.#turnAuthors.delete(conversationKey);
1091
1530
  await Promise.allSettled([
1092
1531
  this.#cancelPendingInteraction(conversationKey),
1093
1532
  this.#approvals.closeRoute(conversationKey),
@@ -1672,4 +2111,36 @@ export class TextHarnessBridge {
1672
2111
  );
1673
2112
  }
1674
2113
  }
2114
+
2115
+ /**
2116
+ * Retire what waits on a human decision in this conversation: the pending
2117
+ * question loses its card and gets the same safe cancellation the recovered
2118
+ * path uses, and active tool approvals are rejected. The caller follows it
2119
+ * with the new request's dispatch, so the room hears the answer instead of
2120
+ * the waiting.
2121
+ */
2122
+ async #retireWaitingInteractions(key, pending) {
2123
+ if (pending) {
2124
+ this.#clearPendingInteraction(key, pending.interactionId);
2125
+ pending.claimedReplyMessageId = null;
2126
+ if (pending.cardMessageId) {
2127
+ await this.#retireInteractionCard(pending.target, pending.cardMessageId);
2128
+ pending.cardMessageId = null;
2129
+ }
2130
+ if (pending.kind === 'question') {
2131
+ try {
2132
+ await this.#respondCancellation(
2133
+ pending.interaction,
2134
+ `The ${this.#descriptor.label} sender moved on to a new request before answering.`,
2135
+ );
2136
+ } catch (error) {
2137
+ this.#logger.warn?.(
2138
+ `[dsh-im:${this.#descriptor.key}] failed to cancel an unanswered pending question:`,
2139
+ error?.message ?? error,
2140
+ );
2141
+ }
2142
+ }
2143
+ }
2144
+ await this.#approvals.rejectRoute(key).catch(() => 0);
2145
+ }
1675
2146
  }