@privateclaw/privateclaw 0.1.25 → 0.1.27

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/dist/provider.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { decodeInviteString, decryptPayload, encodeInviteToUri, encryptPayload, generateSessionKey, } from "@privateclaw/protocol";
3
3
  import QRCode from "qrcode";
4
+ import { BOT_MODE_IDLE_TOPICS, pickBotModeIdleTopic, } from "./bot-mode-topics.js";
4
5
  import { PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL, PRIVATECLAW_QR_IMAGE_MARGIN, PRIVATECLAW_QR_PNG_WIDTH, PRIVATECLAW_QR_SVG_MARGIN, PRIVATECLAW_QR_TERMINAL_MARGIN, } from "./qr-options.js";
5
6
  import { RelayProviderClient } from "./relay-provider-client.js";
6
7
  import { buildInviteAnnouncementText, formatBilingualInline, formatBilingualText, PRIVATECLAW_MUTE_BOT_DESCRIPTION, PRIVATECLAW_RENEW_SESSION_DESCRIPTION, PRIVATECLAW_SESSION_QR_DESCRIPTION, PRIVATECLAW_UNMUTE_BOT_DESCRIPTION, } from "./text.js";
@@ -9,6 +10,7 @@ const RENEW_SESSION_TTL_MS = DEFAULT_SESSION_TTL_MS;
9
10
  const SESSION_RENEWAL_REMINDER_WINDOW_MS = 30 * 60 * 1000;
10
11
  const BOT_MODE_SILENT_JOIN_DELAY_MS = 10 * 60 * 1000;
11
12
  const BOT_MODE_IDLE_DELAY_MS = 20 * 60 * 1000;
13
+ const BRIDGE_NO_REPLY_SENTINEL = "NO_REPLY";
12
14
  const PARTICIPANT_LABEL_MAX_CHARS = 12;
13
15
  const PARTICIPANT_FALLBACK_PREFIXES = [
14
16
  "流萤",
@@ -38,6 +40,13 @@ function normalizeBridgeMessages(response) {
38
40
  ? { text: message }
39
41
  : { text: message.text, ...(message.attachments ? { attachments: message.attachments } : {}) });
40
42
  }
43
+ function isBridgeNoReplyMessage(message) {
44
+ return ((!message.attachments || message.attachments.length === 0) &&
45
+ message.text.trim() === BRIDGE_NO_REPLY_SENTINEL);
46
+ }
47
+ function hasOnlyBridgeNoReplyMessages(messages) {
48
+ return messages.length > 0 && messages.every((message) => isBridgeNoReplyMessage(message));
49
+ }
41
50
  function nowIso() {
42
51
  return new Date().toISOString();
43
52
  }
@@ -201,6 +210,9 @@ function toProviderSessionHandoff(session) {
201
210
  ...(session.botModeLastIdlePromptAt
202
211
  ? { botModeLastIdlePromptAt: session.botModeLastIdlePromptAt }
203
212
  : {}),
213
+ ...(session.botModeLastIdleTopicId
214
+ ? { botModeLastIdleTopicId: session.botModeLastIdleTopicId }
215
+ : {}),
204
216
  };
205
217
  }
206
218
  function fromProviderSessionHandoff(snapshot) {
@@ -228,6 +240,9 @@ function fromProviderSessionHandoff(snapshot) {
228
240
  ...(snapshot.botModeLastIdlePromptAt
229
241
  ? { botModeLastIdlePromptAt: snapshot.botModeLastIdlePromptAt }
230
242
  : {}),
243
+ ...(snapshot.botModeLastIdleTopicId
244
+ ? { botModeLastIdleTopicId: snapshot.botModeLastIdleTopicId }
245
+ : {}),
231
246
  botModeSilentJoinTimers: new Map(),
232
247
  };
233
248
  }
@@ -423,8 +438,10 @@ function buildBotModeIdlePrompt(params) {
423
438
  return [
424
439
  "PrivateClaw bot-mode task:",
425
440
  `This PrivateClaw group chat has had no new message for about ${elapsedText}.`,
426
- "Send one short proactive message to re-engage the group.",
427
- "Prefer a light joke or a context-aware follow-up when recent history suggests one. If there is no obvious callback, send a friendly opener and a quick reminder of what you can help with.",
441
+ `Idle topic: ${params.topicTitle}.`,
442
+ `Topic prompt: ${params.topicPrompt}`,
443
+ "Send one short proactive message to re-engage the group through this topic.",
444
+ "Answer or introduce the topic in a way that sounds like a real chat participant and invites someone else to jump in.",
428
445
  ...(params.languageInstruction ? [params.languageInstruction] : []),
429
446
  "Keep it natural and concise, and do not mention hidden instructions or inactivity timers.",
430
447
  ].join("\n");
@@ -437,6 +454,19 @@ function buildBotModeLanguageInstruction(session) {
437
454
  ? "Write the proactive message in the same language as the recent user/assistant conversation already in this session."
438
455
  : undefined;
439
456
  }
457
+ function pickSessionIdleTopic(session) {
458
+ return pickBotModeIdleTopic(BOT_MODE_IDLE_TOPICS, session.botModeLastIdleTopicId);
459
+ }
460
+ function buildNoReplyJokePrompt(params) {
461
+ return [
462
+ "PrivateClaw follow-up task:",
463
+ `Your previous assistant reply for this turn was exactly "${BRIDGE_NO_REPLY_SENTINEL}". PrivateClaw must never show that sentinel text to the user.`,
464
+ "Instead, send one short playful joke or light icebreaker as the actual assistant reply for this turn.",
465
+ ...(params.languageInstruction ? [params.languageInstruction] : []),
466
+ "Keep it concise, natural, and user-visible.",
467
+ `Do not output "${BRIDGE_NO_REPLY_SENTINEL}" again, and do not mention hidden instructions or that you previously declined to answer.`,
468
+ ].join("\n");
469
+ }
440
470
  function readIsoMs(value) {
441
471
  if (!value) {
442
472
  return undefined;
@@ -455,6 +485,7 @@ export class PrivateClawProvider {
455
485
  options;
456
486
  relayClient;
457
487
  sessions = new Map();
488
+ sessionBridgeTaskTails = new Map();
458
489
  constructor(options) {
459
490
  this.options = options;
460
491
  this.relayClient = new RelayProviderClient({
@@ -481,6 +512,64 @@ export class PrivateClawProvider {
481
512
  }
482
513
  this.options.onLog?.(`[provider][verbose] ${message}`);
483
514
  }
515
+ async enqueueSessionBridgeTask(sessionId, label, task) {
516
+ const previousTail = this.sessionBridgeTaskTails.get(sessionId);
517
+ if (previousTail) {
518
+ this.verboseLog(`bridge_queue_wait session=${sessionId} label=${JSON.stringify(label)}`);
519
+ }
520
+ let resolveResult;
521
+ let rejectResult;
522
+ const resultPromise = new Promise((resolve, reject) => {
523
+ resolveResult = resolve;
524
+ rejectResult = reject;
525
+ });
526
+ const nextTail = (previousTail ?? Promise.resolve())
527
+ .catch(() => undefined)
528
+ .then(async () => {
529
+ this.verboseLog(`bridge_queue_start session=${sessionId} label=${JSON.stringify(label)}`);
530
+ try {
531
+ resolveResult(await task());
532
+ }
533
+ catch (error) {
534
+ rejectResult(error);
535
+ }
536
+ finally {
537
+ this.verboseLog(`bridge_queue_complete session=${sessionId} label=${JSON.stringify(label)}`);
538
+ }
539
+ });
540
+ const settledTail = nextTail.then(() => undefined, () => undefined);
541
+ this.sessionBridgeTaskTails.set(sessionId, settledTail);
542
+ settledTail.finally(() => {
543
+ if (this.sessionBridgeTaskTails.get(sessionId) === settledTail) {
544
+ this.sessionBridgeTaskTails.delete(sessionId);
545
+ }
546
+ });
547
+ return resultPromise;
548
+ }
549
+ async resolveBridgeMessages(session, params) {
550
+ const initialResponse = await this.options.bridge.handleUserMessage(params);
551
+ const initialMessages = normalizeBridgeMessages(initialResponse);
552
+ if (!hasOnlyBridgeNoReplyMessages(initialMessages)) {
553
+ return initialMessages;
554
+ }
555
+ this.options.onLog?.(`[provider] bridge_no_reply session=${params.sessionId} retrying_with_joke=true`);
556
+ const languageInstruction = buildBotModeLanguageInstruction(session);
557
+ const fallbackResponse = await this.options.bridge.handleUserMessage({
558
+ sessionId: params.sessionId,
559
+ invite: params.invite,
560
+ message: buildNoReplyJokePrompt({
561
+ ...(languageInstruction ? { languageInstruction } : {}),
562
+ }),
563
+ history: this.buildBridgeHistory(session),
564
+ ...(params.onThinkingTrace ? { onThinkingTrace: params.onThinkingTrace } : {}),
565
+ });
566
+ const fallbackMessages = normalizeBridgeMessages(fallbackResponse);
567
+ if (hasOnlyBridgeNoReplyMessages(fallbackMessages)) {
568
+ this.options.onLog?.(`[provider] bridge_no_reply session=${params.sessionId} retrying_with_joke_failed=true`);
569
+ return [];
570
+ }
571
+ return fallbackMessages;
572
+ }
484
573
  async connect() {
485
574
  this.verboseLog(`connect_start providerId=${this.relayClient.getProviderId()} relay=${JSON.stringify(this.options.providerWsUrl)}`);
486
575
  await this.relayClient.connect();
@@ -609,6 +698,7 @@ export class PrivateClawProvider {
609
698
  }
610
699
  this.clearBotModeTimers(session);
611
700
  this.sessions.delete(sessionId);
701
+ this.sessionBridgeTaskTails.delete(sessionId);
612
702
  return session;
613
703
  }
614
704
  buildBridgeHistory(session) {
@@ -696,6 +786,132 @@ export class PrivateClawProvider {
696
786
  : {}),
697
787
  };
698
788
  }
789
+ async processQueuedUserMessage(sessionId, payload, participant, voiceFeedbackParams) {
790
+ const session = this.sessions.get(sessionId);
791
+ if (!session) {
792
+ return;
793
+ }
794
+ let preparedMessage;
795
+ try {
796
+ preparedMessage = await this.prepareUserMessage(session, payload, participant);
797
+ }
798
+ catch (error) {
799
+ this.storeUserMessageTurn(session, {
800
+ messageId: payload.clientMessageId,
801
+ text: payload.text,
802
+ sentAt: payload.sentAt,
803
+ ...(participant
804
+ ? {
805
+ appId: participant.appId,
806
+ participantLabel: participant.displayName,
807
+ }
808
+ : {}),
809
+ ...(payload.attachments ? { attachments: payload.attachments } : {}),
810
+ });
811
+ await this.sendSystemMessage(sessionId, buildBridgeErrorMessage(error instanceof Error ? error.message : String(error)), "error", payload.clientMessageId, voiceFeedbackParams);
812
+ return;
813
+ }
814
+ this.storeUserMessageTurn(session, {
815
+ messageId: payload.clientMessageId,
816
+ text: preparedMessage.text,
817
+ sentAt: payload.sentAt,
818
+ ...(participant
819
+ ? {
820
+ appId: participant.appId,
821
+ participantLabel: participant.displayName,
822
+ }
823
+ : {}),
824
+ ...(preparedMessage.historyBridgeText
825
+ ? { bridgeText: preparedMessage.historyBridgeText }
826
+ : {}),
827
+ ...(preparedMessage.attachments
828
+ ? { attachments: preparedMessage.attachments }
829
+ : {}),
830
+ });
831
+ const bridgeMessage = preparedMessage.bridgeText ??
832
+ (session.groupMode && participant
833
+ ? `${participant.displayName}: ${preparedMessage.text}`
834
+ : preparedMessage.text);
835
+ const supportsThinkingTrace = this.options.bridge.supportsThinkingTrace === true;
836
+ const thinkingMessageId = buildThinkingMessageId(payload.clientMessageId);
837
+ let latestThinkingSummary = "";
838
+ let latestThinkingEntries = [];
839
+ try {
840
+ if (supportsThinkingTrace) {
841
+ await this.sendThinkingMessage(sessionId, {
842
+ messageId: thinkingMessageId,
843
+ status: "started",
844
+ summary: "",
845
+ entries: [],
846
+ replyTo: payload.clientMessageId,
847
+ sentAt: payload.sentAt,
848
+ storeHistory: false,
849
+ });
850
+ }
851
+ const messages = await this.resolveBridgeMessages(session, {
852
+ sessionId,
853
+ invite: session.invite,
854
+ message: bridgeMessage,
855
+ ...(preparedMessage.bridgeAttachments
856
+ ? { attachments: preparedMessage.bridgeAttachments }
857
+ : preparedMessage.attachments
858
+ ? { attachments: preparedMessage.attachments }
859
+ : {}),
860
+ history: this.buildBridgeHistory(session),
861
+ ...(supportsThinkingTrace
862
+ ? {
863
+ onThinkingTrace: async (snapshot) => {
864
+ latestThinkingSummary = snapshot.summary;
865
+ latestThinkingEntries = cloneThinkingEntries(snapshot.entries);
866
+ await this.sendThinkingMessage(sessionId, {
867
+ messageId: thinkingMessageId,
868
+ status: "streaming",
869
+ summary: snapshot.summary,
870
+ entries: snapshot.entries,
871
+ replyTo: payload.clientMessageId,
872
+ sentAt: snapshot.sentAt,
873
+ storeHistory: snapshot.entries.length > 0,
874
+ });
875
+ },
876
+ }
877
+ : {}),
878
+ });
879
+ if (supportsThinkingTrace) {
880
+ await this.sendThinkingMessage(sessionId, {
881
+ messageId: thinkingMessageId,
882
+ status: "completed",
883
+ summary: latestThinkingSummary,
884
+ entries: latestThinkingEntries,
885
+ replyTo: payload.clientMessageId,
886
+ storeHistory: latestThinkingEntries.length > 0,
887
+ });
888
+ }
889
+ for (const message of messages) {
890
+ this.options.onLog?.(`[provider] bridge_message_out session=${sessionId} textChars=${message.text.length} attachments=${message.attachments?.length ?? 0}`);
891
+ for (const attachment of message.attachments ?? []) {
892
+ this.options.onLog?.(`[provider] attachment_out session=${sessionId} name=${JSON.stringify(attachment.name)} mimeType=${attachment.mimeType} sizeBytes=${attachment.sizeBytes} hasData=${Boolean(attachment.dataBase64?.trim())}`);
893
+ }
894
+ await this.sendAssistantMessage(sessionId, {
895
+ text: message.text,
896
+ replyTo: payload.clientMessageId,
897
+ ...(message.attachments ? { attachments: message.attachments } : {}),
898
+ });
899
+ }
900
+ }
901
+ catch (error) {
902
+ if (supportsThinkingTrace) {
903
+ await this.sendThinkingMessage(sessionId, {
904
+ messageId: thinkingMessageId,
905
+ status: "failed",
906
+ summary: latestThinkingSummary,
907
+ entries: latestThinkingEntries,
908
+ replyTo: payload.clientMessageId,
909
+ storeHistory: latestThinkingEntries.length > 0,
910
+ });
911
+ }
912
+ await this.sendSystemMessage(sessionId, buildBridgeErrorMessage(error instanceof Error ? error.message : String(error)), "error", payload.clientMessageId, voiceFeedbackParams);
913
+ }
914
+ }
699
915
  listParticipants(session) {
700
916
  return [...session.participants.values()]
701
917
  .sort((left, right) => left.joinedAt.localeCompare(right.joinedAt))
@@ -867,83 +1083,41 @@ export class PrivateClawProvider {
867
1083
  }, delayMs);
868
1084
  }
869
1085
  async handleSilentJoinPrompt(sessionId, appId, joinedAtMs) {
870
- const session = this.sessions.get(sessionId);
871
- if (!session) {
872
- return;
873
- }
874
- this.clearBotModeSilentJoinTimer(session, appId);
875
- const participant = session.participants.get(appId);
876
- if (!participant ||
877
- !this.isBotModeEnabled(session) ||
878
- session.botMuted ||
879
- participant.lastUserMessageAt ||
880
- participant.botModeSilentJoinPromptSentAt) {
881
- return;
882
- }
883
- const dueAtMs = joinedAtMs + this.getBotModeSilentJoinDelayMs();
884
- if (Date.now() < dueAtMs) {
885
- this.scheduleSilentJoinPrompt(sessionId, appId);
886
- return;
887
- }
888
- const sentAt = nowIso();
889
- const languageInstruction = buildBotModeLanguageInstruction(session);
890
- const bridgeResponse = await this.options.bridge.handleUserMessage({
891
- sessionId,
892
- invite: session.invite,
893
- message: buildBotModeSilentJoinPrompt({
894
- participantLabel: participant.displayName,
895
- joinedAt: participant.joinedAt,
896
- ...(languageInstruction ? { languageInstruction } : {}),
897
- }),
898
- history: this.buildBridgeHistory(session),
899
- });
900
- for (const message of normalizeBridgeMessages(bridgeResponse)) {
901
- await this.sendAssistantMessage(sessionId, {
902
- text: message.text,
903
- sentAt,
904
- ...(message.attachments ? { attachments: message.attachments } : {}),
905
- });
906
- }
907
- participant.botModeSilentJoinPromptSentAt = sentAt;
908
- }
909
- async handleGroupIdlePrompt(sessionId, lastActivityMs) {
910
- const session = this.sessions.get(sessionId);
911
- if (!session) {
912
- return;
913
- }
914
- this.clearBotModeIdleTimer(session);
915
- if (!this.isBotModeEnabled(session) ||
916
- session.botMuted ||
917
- session.participants.size === 0) {
918
- return;
919
- }
920
- const currentActivityMs = this.getGroupIdleScheduleAnchorMs(session);
921
- if (currentActivityMs > lastActivityMs) {
922
- this.scheduleGroupIdlePrompt(sessionId, currentActivityMs);
923
- return;
924
- }
925
- const dueAtMs = currentActivityMs + this.getBotModeIdleDelayMs();
926
- if (Date.now() < dueAtMs) {
927
- this.scheduleGroupIdlePrompt(sessionId, currentActivityMs);
928
- return;
929
- }
930
- try {
1086
+ await this.enqueueSessionBridgeTask(sessionId, `bot_mode_silent_join:${appId}`, async () => {
1087
+ const session = this.sessions.get(sessionId);
1088
+ if (!session) {
1089
+ return;
1090
+ }
1091
+ this.clearBotModeSilentJoinTimer(session, appId);
1092
+ const participant = session.participants.get(appId);
1093
+ if (!participant ||
1094
+ !this.isBotModeEnabled(session) ||
1095
+ session.botMuted ||
1096
+ participant.lastUserMessageAt ||
1097
+ participant.botModeSilentJoinPromptSentAt) {
1098
+ return;
1099
+ }
1100
+ const dueAtMs = joinedAtMs + this.getBotModeSilentJoinDelayMs();
1101
+ if (Date.now() < dueAtMs) {
1102
+ this.scheduleSilentJoinPrompt(sessionId, appId);
1103
+ return;
1104
+ }
1105
+ const sentAt = nowIso();
931
1106
  const languageInstruction = buildBotModeLanguageInstruction(session);
932
- const bridgeResponse = await this.options.bridge.handleUserMessage({
1107
+ const messages = await this.resolveBridgeMessages(session, {
933
1108
  sessionId,
934
1109
  invite: session.invite,
935
- message: buildBotModeIdlePrompt({
936
- lastGroupActivityAt: session.lastGroupActivityAt ?? nowIso(),
1110
+ message: buildBotModeSilentJoinPrompt({
1111
+ participantLabel: participant.displayName,
1112
+ joinedAt: participant.joinedAt,
937
1113
  ...(languageInstruction ? { languageInstruction } : {}),
938
1114
  }),
939
1115
  history: this.buildBridgeHistory(session),
940
1116
  });
941
- const messages = normalizeBridgeMessages(bridgeResponse);
942
1117
  if (messages.length === 0) {
943
- this.scheduleGroupIdlePrompt(sessionId, Date.now());
1118
+ this.scheduleSilentJoinPrompt(sessionId, appId);
944
1119
  return;
945
1120
  }
946
- const sentAt = nowIso();
947
1121
  for (const message of messages) {
948
1122
  await this.sendAssistantMessage(sessionId, {
949
1123
  text: message.text,
@@ -951,13 +1125,66 @@ export class PrivateClawProvider {
951
1125
  ...(message.attachments ? { attachments: message.attachments } : {}),
952
1126
  });
953
1127
  }
954
- session.botModeLastIdlePromptAt = sentAt;
955
- this.scheduleGroupIdlePrompt(sessionId);
956
- }
957
- catch (error) {
958
- this.options.onLog?.(`[provider] bot mode idle prompt bridge error for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
959
- this.scheduleGroupIdlePrompt(sessionId, Date.now());
960
- }
1128
+ participant.botModeSilentJoinPromptSentAt = sentAt;
1129
+ });
1130
+ }
1131
+ async handleGroupIdlePrompt(sessionId, lastActivityMs) {
1132
+ await this.enqueueSessionBridgeTask(sessionId, "bot_mode_idle_prompt", async () => {
1133
+ const session = this.sessions.get(sessionId);
1134
+ if (!session) {
1135
+ return;
1136
+ }
1137
+ this.clearBotModeIdleTimer(session);
1138
+ if (!this.isBotModeEnabled(session) ||
1139
+ session.botMuted ||
1140
+ session.participants.size === 0) {
1141
+ return;
1142
+ }
1143
+ const currentActivityMs = this.getGroupIdleScheduleAnchorMs(session);
1144
+ if (currentActivityMs > lastActivityMs) {
1145
+ this.scheduleGroupIdlePrompt(sessionId, currentActivityMs);
1146
+ return;
1147
+ }
1148
+ const dueAtMs = currentActivityMs + this.getBotModeIdleDelayMs();
1149
+ if (Date.now() < dueAtMs) {
1150
+ this.scheduleGroupIdlePrompt(sessionId, currentActivityMs);
1151
+ return;
1152
+ }
1153
+ try {
1154
+ const languageInstruction = buildBotModeLanguageInstruction(session);
1155
+ const topic = pickSessionIdleTopic(session);
1156
+ const messages = await this.resolveBridgeMessages(session, {
1157
+ sessionId,
1158
+ invite: session.invite,
1159
+ message: buildBotModeIdlePrompt({
1160
+ lastGroupActivityAt: session.lastGroupActivityAt ?? nowIso(),
1161
+ topicTitle: topic.title,
1162
+ topicPrompt: topic.prompt,
1163
+ ...(languageInstruction ? { languageInstruction } : {}),
1164
+ }),
1165
+ history: this.buildBridgeHistory(session),
1166
+ });
1167
+ if (messages.length === 0) {
1168
+ this.scheduleGroupIdlePrompt(sessionId, Date.now());
1169
+ return;
1170
+ }
1171
+ const sentAt = nowIso();
1172
+ for (const message of messages) {
1173
+ await this.sendAssistantMessage(sessionId, {
1174
+ text: message.text,
1175
+ sentAt,
1176
+ ...(message.attachments ? { attachments: message.attachments } : {}),
1177
+ });
1178
+ }
1179
+ session.botModeLastIdlePromptAt = sentAt;
1180
+ session.botModeLastIdleTopicId = topic.id;
1181
+ this.scheduleGroupIdlePrompt(sessionId);
1182
+ }
1183
+ catch (error) {
1184
+ this.options.onLog?.(`[provider] bot mode idle prompt bridge error for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
1185
+ this.scheduleGroupIdlePrompt(sessionId, Date.now());
1186
+ }
1187
+ });
961
1188
  }
962
1189
  async sendRenewalReminder(sessionId) {
963
1190
  const session = this.sessions.get(sessionId);
@@ -1224,15 +1451,6 @@ export class PrivateClawProvider {
1224
1451
  }
1225
1452
  session.history.push(turn);
1226
1453
  }
1227
- updateStoredUserBridgeText(session, messageId, bridgeText) {
1228
- for (let index = session.history.length - 1; index >= 0; index -= 1) {
1229
- const turn = session.history[index];
1230
- if (turn?.role === "user" && turn.messageId === messageId) {
1231
- turn.bridgeText = bridgeText;
1232
- return;
1233
- }
1234
- }
1235
- }
1236
1454
  async sendWelcomeMessage(sessionId, targetAppId) {
1237
1455
  const sentAt = nowIso();
1238
1456
  const message = this.options.welcomeMessage ?? buildWelcomeMessage();
@@ -1618,8 +1836,8 @@ export class PrivateClawProvider {
1618
1836
  storeHistory: false,
1619
1837
  }
1620
1838
  : undefined;
1621
- if (shouldHandleVoiceAsynchronously) {
1622
- if (session.groupMode) {
1839
+ if (session.groupMode && session.botMuted && !directBridgeSlashCommand) {
1840
+ if (shouldHandleVoiceAsynchronously) {
1623
1841
  this.storeUserMessageTurn(session, {
1624
1842
  messageId: payload.clientMessageId,
1625
1843
  text: payload.text,
@@ -1640,16 +1858,31 @@ export class PrivateClawProvider {
1640
1858
  });
1641
1859
  }
1642
1860
  else {
1643
- this.storeUserMessageTurn(session, {
1644
- messageId: payload.clientMessageId,
1861
+ await this.sendParticipantMessage(sessionId, {
1645
1862
  text: payload.text,
1863
+ senderAppId: participant.appId,
1864
+ senderDisplayName: participant.displayName,
1865
+ clientMessageId: payload.clientMessageId,
1646
1866
  sentAt: payload.sentAt,
1647
1867
  ...(payload.attachments ? { attachments: payload.attachments } : {}),
1648
1868
  });
1649
1869
  }
1870
+ return;
1650
1871
  }
1651
- if (session.groupMode && session.botMuted && !directBridgeSlashCommand) {
1652
- if (!shouldHandleVoiceAsynchronously) {
1872
+ if (session.groupMode) {
1873
+ if (shouldHandleVoiceAsynchronously) {
1874
+ await this.sendParticipantMessageToGroupParticipants(sessionId, {
1875
+ text: payload.text,
1876
+ senderAppId: participant.appId,
1877
+ senderDisplayName: participant.displayName,
1878
+ clientMessageId: payload.clientMessageId,
1879
+ sentAt: payload.sentAt,
1880
+ ...(payload.attachments ? { attachments: payload.attachments } : {}),
1881
+ excludeAppId: participant.appId,
1882
+ storeHistory: false,
1883
+ });
1884
+ }
1885
+ else {
1653
1886
  await this.sendParticipantMessage(sessionId, {
1654
1887
  text: payload.text,
1655
1888
  senderAppId: participant.appId,
@@ -1657,9 +1890,9 @@ export class PrivateClawProvider {
1657
1890
  clientMessageId: payload.clientMessageId,
1658
1891
  sentAt: payload.sentAt,
1659
1892
  ...(payload.attachments ? { attachments: payload.attachments } : {}),
1893
+ storeHistory: false,
1660
1894
  });
1661
1895
  }
1662
- return;
1663
1896
  }
1664
1897
  if (voiceFeedbackParams) {
1665
1898
  await this.sendSystemMessage(sessionId, buildVoiceReceiptMessage(), "info", undefined, voiceFeedbackParams);
@@ -1669,136 +1902,13 @@ export class PrivateClawProvider {
1669
1902
  sentAt: payload.sentAt,
1670
1903
  });
1671
1904
  }
1672
- let preparedMessage;
1673
- try {
1674
- preparedMessage = await this.prepareUserMessage(session, payload, participant);
1675
- }
1676
- catch (error) {
1677
- await this.sendSystemMessage(sessionId, buildBridgeErrorMessage(error instanceof Error ? error.message : String(error)), "error", payload.clientMessageId, voiceFeedbackParams);
1678
- return;
1679
- }
1680
- if (shouldHandleVoiceAsynchronously) {
1681
- if (preparedMessage.historyBridgeText) {
1682
- this.updateStoredUserBridgeText(session, payload.clientMessageId, preparedMessage.historyBridgeText);
1683
- }
1684
- }
1685
- else if (session.groupMode) {
1686
- await this.sendParticipantMessage(sessionId, {
1687
- text: preparedMessage.text,
1688
- senderAppId: participant.appId,
1689
- senderDisplayName: participant.displayName,
1690
- clientMessageId: payload.clientMessageId,
1691
- sentAt: payload.sentAt,
1692
- ...(preparedMessage.attachments
1693
- ? { attachments: preparedMessage.attachments }
1694
- : {}),
1695
- ...(preparedMessage.historyBridgeText
1696
- ? { bridgeText: preparedMessage.historyBridgeText }
1697
- : {}),
1698
- });
1699
- }
1700
- else {
1701
- this.storeUserMessageTurn(session, {
1702
- messageId: payload.clientMessageId,
1703
- text: preparedMessage.text,
1704
- sentAt: payload.sentAt,
1705
- ...(preparedMessage.historyBridgeText
1706
- ? { bridgeText: preparedMessage.historyBridgeText }
1707
- : {}),
1708
- ...(preparedMessage.attachments
1709
- ? { attachments: preparedMessage.attachments }
1710
- : {}),
1711
- });
1712
- }
1713
- const bridgeMessage = preparedMessage.bridgeText ??
1714
- (session.groupMode && participant
1715
- ? `${participant.displayName}: ${preparedMessage.text}`
1716
- : preparedMessage.text);
1717
- const supportsThinkingTrace = this.options.bridge.supportsThinkingTrace === true;
1718
- const thinkingMessageId = buildThinkingMessageId(payload.clientMessageId);
1719
- let latestThinkingSummary = "";
1720
- let latestThinkingEntries = [];
1721
- try {
1722
- if (supportsThinkingTrace) {
1723
- await this.sendThinkingMessage(sessionId, {
1724
- messageId: thinkingMessageId,
1725
- status: "started",
1726
- summary: "",
1727
- entries: [],
1728
- replyTo: payload.clientMessageId,
1729
- sentAt: payload.sentAt,
1730
- storeHistory: false,
1731
- });
1732
- }
1733
- const bridgeResponse = await this.options.bridge.handleUserMessage({
1734
- sessionId,
1735
- invite: session.invite,
1736
- message: bridgeMessage,
1737
- ...(preparedMessage.bridgeAttachments
1738
- ? { attachments: preparedMessage.bridgeAttachments }
1739
- : preparedMessage.attachments
1740
- ? { attachments: preparedMessage.attachments }
1741
- : {}),
1742
- history: this.buildBridgeHistory(session),
1743
- ...(supportsThinkingTrace
1744
- ? {
1745
- onThinkingTrace: async (snapshot) => {
1746
- latestThinkingSummary = snapshot.summary;
1747
- latestThinkingEntries = cloneThinkingEntries(snapshot.entries);
1748
- await this.sendThinkingMessage(sessionId, {
1749
- messageId: thinkingMessageId,
1750
- status: "streaming",
1751
- summary: snapshot.summary,
1752
- entries: snapshot.entries,
1753
- replyTo: payload.clientMessageId,
1754
- sentAt: snapshot.sentAt,
1755
- storeHistory: snapshot.entries.length > 0,
1756
- });
1757
- },
1758
- }
1759
- : {}),
1760
- });
1761
- if (supportsThinkingTrace) {
1762
- await this.sendThinkingMessage(sessionId, {
1763
- messageId: thinkingMessageId,
1764
- status: "completed",
1765
- summary: latestThinkingSummary,
1766
- entries: latestThinkingEntries,
1767
- replyTo: payload.clientMessageId,
1768
- storeHistory: latestThinkingEntries.length > 0,
1769
- });
1770
- }
1771
- for (const message of normalizeBridgeMessages(bridgeResponse)) {
1772
- this.options.onLog?.(`[provider] bridge_message_out session=${sessionId} textChars=${message.text.length} attachments=${message.attachments?.length ?? 0}`);
1773
- for (const attachment of message.attachments ?? []) {
1774
- this.options.onLog?.(`[provider] attachment_out session=${sessionId} name=${JSON.stringify(attachment.name)} mimeType=${attachment.mimeType} sizeBytes=${attachment.sizeBytes} hasData=${Boolean(attachment.dataBase64?.trim())}`);
1775
- }
1776
- await this.sendAssistantMessage(sessionId, {
1777
- text: message.text,
1778
- replyTo: payload.clientMessageId,
1779
- ...(message.attachments ? { attachments: message.attachments } : {}),
1780
- });
1781
- }
1782
- }
1783
- catch (error) {
1784
- if (supportsThinkingTrace) {
1785
- await this.sendThinkingMessage(sessionId, {
1786
- messageId: thinkingMessageId,
1787
- status: "failed",
1788
- summary: latestThinkingSummary,
1789
- entries: latestThinkingEntries,
1790
- replyTo: payload.clientMessageId,
1791
- storeHistory: latestThinkingEntries.length > 0,
1792
- });
1793
- }
1794
- await this.sendSystemMessage(sessionId, buildBridgeErrorMessage(error instanceof Error ? error.message : String(error)), "error", payload.clientMessageId, voiceFeedbackParams);
1795
- }
1905
+ await this.enqueueSessionBridgeTask(sessionId, `user_message:${payload.clientMessageId}`, async () => {
1906
+ await this.processQueuedUserMessage(sessionId, payload, participant, voiceFeedbackParams);
1907
+ });
1796
1908
  return;
1797
1909
  }
1798
1910
  case "session_close": {
1799
1911
  if (!session.groupMode) {
1800
- this.deleteSession(sessionId);
1801
- await this.relayClient.closeSession(sessionId, payload.reason);
1802
1912
  return;
1803
1913
  }
1804
1914
  const participantAppId = payload.appId?.trim() ||