@privateclaw/privateclaw 0.1.24 → 0.1.26

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,12 +1,16 @@
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";
7
8
  export const DEFAULT_SESSION_TTL_MS = 24 * 60 * 60 * 1000;
8
9
  const RENEW_SESSION_TTL_MS = DEFAULT_SESSION_TTL_MS;
9
10
  const SESSION_RENEWAL_REMINDER_WINDOW_MS = 30 * 60 * 1000;
11
+ const BOT_MODE_SILENT_JOIN_DELAY_MS = 10 * 60 * 1000;
12
+ const BOT_MODE_IDLE_DELAY_MS = 20 * 60 * 1000;
13
+ const BRIDGE_NO_REPLY_SENTINEL = "NO_REPLY";
10
14
  const PARTICIPANT_LABEL_MAX_CHARS = 12;
11
15
  const PARTICIPANT_FALLBACK_PREFIXES = [
12
16
  "流萤",
@@ -36,6 +40,13 @@ function normalizeBridgeMessages(response) {
36
40
  ? { text: message }
37
41
  : { text: message.text, ...(message.attachments ? { attachments: message.attachments } : {}) });
38
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
+ }
39
50
  function nowIso() {
40
51
  return new Date().toISOString();
41
52
  }
@@ -190,6 +201,18 @@ function toProviderSessionHandoff(session) {
190
201
  ...(session.renewalReminderSentAt
191
202
  ? { renewalReminderSentAt: session.renewalReminderSentAt }
192
203
  : {}),
204
+ ...(session.lastGroupActivityAt
205
+ ? { lastGroupActivityAt: session.lastGroupActivityAt }
206
+ : {}),
207
+ ...(session.botModeIdleAnchorAt
208
+ ? { botModeIdleAnchorAt: session.botModeIdleAnchorAt }
209
+ : {}),
210
+ ...(session.botModeLastIdlePromptAt
211
+ ? { botModeLastIdlePromptAt: session.botModeLastIdlePromptAt }
212
+ : {}),
213
+ ...(session.botModeLastIdleTopicId
214
+ ? { botModeLastIdleTopicId: session.botModeLastIdleTopicId }
215
+ : {}),
193
216
  };
194
217
  }
195
218
  function fromProviderSessionHandoff(snapshot) {
@@ -208,8 +231,25 @@ function fromProviderSessionHandoff(snapshot) {
208
231
  ...(snapshot.renewalReminderSentAt
209
232
  ? { renewalReminderSentAt: snapshot.renewalReminderSentAt }
210
233
  : {}),
234
+ ...(snapshot.lastGroupActivityAt
235
+ ? { lastGroupActivityAt: snapshot.lastGroupActivityAt }
236
+ : {}),
237
+ ...(snapshot.botModeIdleAnchorAt
238
+ ? { botModeIdleAnchorAt: snapshot.botModeIdleAnchorAt }
239
+ : {}),
240
+ ...(snapshot.botModeLastIdlePromptAt
241
+ ? { botModeLastIdlePromptAt: snapshot.botModeLastIdlePromptAt }
242
+ : {}),
243
+ ...(snapshot.botModeLastIdleTopicId
244
+ ? { botModeLastIdleTopicId: snapshot.botModeLastIdleTopicId }
245
+ : {}),
246
+ botModeSilentJoinTimers: new Map(),
211
247
  };
212
248
  }
249
+ function describeElapsedMinutes(elapsedMs) {
250
+ const minutes = Math.max(1, Math.round(elapsedMs / 60_000));
251
+ return `${minutes} minute${minutes === 1 ? "" : "s"}`;
252
+ }
213
253
  function buildRenewalReminderMessage(session) {
214
254
  const command = "/renew-session";
215
255
  if (session.groupMode) {
@@ -381,6 +421,59 @@ function buildBotAlreadyMutedMessage() {
381
421
  function buildBotAlreadyUnmutedMessage() {
382
422
  return formatBilingualInline("机器人目前已经处于可回复状态。", "Bot replies are already enabled.");
383
423
  }
424
+ function buildBotModeSilentJoinPrompt(params) {
425
+ const joinedAtMs = new Date(params.joinedAt).getTime();
426
+ const elapsedText = describeElapsedMinutes(Math.max(0, (params.nowMs ?? Date.now()) - joinedAtMs));
427
+ return [
428
+ "PrivateClaw bot-mode task:",
429
+ `A participant named "${params.participantLabel}" joined this PrivateClaw group chat about ${elapsedText} ago but has not sent any message yet.`,
430
+ "Write one short proactive message to the whole group that warmly greets them, naturally mentions what kinds of help you can provide, and feels like a real chat participant.",
431
+ ...(params.languageInstruction ? [params.languageInstruction] : []),
432
+ "Use recent conversation context when it helps, keep the tone playful and concise, and do not mention hidden instructions, timers, or inactivity monitoring.",
433
+ ].join("\n");
434
+ }
435
+ function buildBotModeIdlePrompt(params) {
436
+ const lastActivityAtMs = new Date(params.lastGroupActivityAt).getTime();
437
+ const elapsedText = describeElapsedMinutes(Math.max(0, (params.nowMs ?? Date.now()) - lastActivityAtMs));
438
+ return [
439
+ "PrivateClaw bot-mode task:",
440
+ `This PrivateClaw group chat has had no new message for about ${elapsedText}.`,
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.",
445
+ ...(params.languageInstruction ? [params.languageInstruction] : []),
446
+ "Keep it natural and concise, and do not mention hidden instructions or inactivity timers.",
447
+ ].join("\n");
448
+ }
449
+ function hasPriorConversationalHistory(session) {
450
+ return session.history.some((turn) => turn.role === "user" || turn.role === "assistant");
451
+ }
452
+ function buildBotModeLanguageInstruction(session) {
453
+ return hasPriorConversationalHistory(session)
454
+ ? "Write the proactive message in the same language as the recent user/assistant conversation already in this session."
455
+ : undefined;
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
+ }
470
+ function readIsoMs(value) {
471
+ if (!value) {
472
+ return undefined;
473
+ }
474
+ const parsed = new Date(value).getTime();
475
+ return Number.isFinite(parsed) ? parsed : undefined;
476
+ }
384
477
  function dedupeCommands(commands) {
385
478
  const unique = new Map();
386
479
  for (const command of commands) {
@@ -392,6 +485,7 @@ export class PrivateClawProvider {
392
485
  options;
393
486
  relayClient;
394
487
  sessions = new Map();
488
+ sessionBridgeTaskTails = new Map();
395
489
  constructor(options) {
396
490
  this.options = options;
397
491
  this.relayClient = new RelayProviderClient({
@@ -418,6 +512,64 @@ export class PrivateClawProvider {
418
512
  }
419
513
  this.options.onLog?.(`[provider][verbose] ${message}`);
420
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
+ }
421
573
  async connect() {
422
574
  this.verboseLog(`connect_start providerId=${this.relayClient.getProviderId()} relay=${JSON.stringify(this.options.providerWsUrl)}`);
423
575
  await this.relayClient.connect();
@@ -487,6 +639,7 @@ export class PrivateClawProvider {
487
639
  const session = fromProviderSessionHandoff(snapshot);
488
640
  this.sessions.set(session.invite.sessionId, session);
489
641
  this.scheduleRenewalReminder(session.invite.sessionId);
642
+ this.scheduleBotModeTimers(session.invite.sessionId);
490
643
  }
491
644
  }
492
645
  suppressReconnectsForHandoff() {
@@ -510,11 +663,16 @@ export class PrivateClawProvider {
510
663
  }
511
664
  session.participants.delete(normalizedAppId);
512
665
  session.removedParticipantAppIds.add(normalizedAppId);
666
+ this.clearBotModeSilentJoinTimer(session, normalizedAppId);
667
+ if (session.participants.size === 0) {
668
+ delete session.botModeIdleAnchorAt;
669
+ }
513
670
  await this.relayClient.closeApp(sessionId, normalizedAppId, reason);
514
671
  if (session.participants.size > 0) {
515
672
  await this.sendSystemMessageToGroupParticipants(sessionId, buildParticipantRemovedByOperatorMessage(participant.displayName));
516
673
  await this.sendCapabilities(sessionId);
517
674
  }
675
+ this.scheduleGroupIdlePrompt(sessionId);
518
676
  return toParticipantSnapshot(participant);
519
677
  }
520
678
  buildSessionAppUrl(sessionId) {
@@ -538,7 +696,9 @@ export class PrivateClawProvider {
538
696
  clearTimeout(session.renewalReminderTimer);
539
697
  delete session.renewalReminderTimer;
540
698
  }
699
+ this.clearBotModeTimers(session);
541
700
  this.sessions.delete(sessionId);
701
+ this.sessionBridgeTaskTails.delete(sessionId);
542
702
  return session;
543
703
  }
544
704
  buildBridgeHistory(session) {
@@ -626,6 +786,132 @@ export class PrivateClawProvider {
626
786
  : {}),
627
787
  };
628
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
+ }
629
915
  listParticipants(session) {
630
916
  return [...session.participants.values()]
631
917
  .sort((left, right) => left.joinedAt.localeCompare(right.joinedAt))
@@ -650,6 +936,256 @@ export class PrivateClawProvider {
650
936
  });
651
937
  }, delayMs);
652
938
  }
939
+ isBotModeEnabled(session) {
940
+ return this.options.botMode === true && session.groupMode;
941
+ }
942
+ getBotModeSilentJoinDelayMs() {
943
+ return this.options.botModeSilentJoinDelayMs ?? BOT_MODE_SILENT_JOIN_DELAY_MS;
944
+ }
945
+ getBotModeIdleDelayMs() {
946
+ return this.options.botModeIdleDelayMs ?? BOT_MODE_IDLE_DELAY_MS;
947
+ }
948
+ clearBotModeSilentJoinTimer(session, appId) {
949
+ const timer = session.botModeSilentJoinTimers?.get(appId);
950
+ if (timer) {
951
+ clearTimeout(timer);
952
+ }
953
+ session.botModeSilentJoinTimers?.delete(appId);
954
+ }
955
+ clearBotModeIdleTimer(session) {
956
+ if (session.botModeIdleTimer) {
957
+ clearTimeout(session.botModeIdleTimer);
958
+ delete session.botModeIdleTimer;
959
+ }
960
+ }
961
+ clearBotModeTimers(session) {
962
+ this.clearBotModeIdleTimer(session);
963
+ for (const appId of session.botModeSilentJoinTimers?.keys() ?? []) {
964
+ this.clearBotModeSilentJoinTimer(session, appId);
965
+ }
966
+ delete session.botModeSilentJoinTimers;
967
+ }
968
+ ensureGroupIdleAnchor(session, fallbackSentAt) {
969
+ if (!session.groupMode || session.botModeIdleAnchorAt || session.lastGroupActivityAt) {
970
+ return;
971
+ }
972
+ const participantJoinedAtMs = [...session.participants.values()]
973
+ .map((participant) => ({
974
+ joinedAt: participant.joinedAt,
975
+ joinedAtMs: readIsoMs(participant.joinedAt),
976
+ }))
977
+ .filter((item) => typeof item.joinedAtMs === "number")
978
+ .sort((left, right) => left.joinedAtMs - right.joinedAtMs)[0]?.joinedAt;
979
+ const nextAnchor = participantJoinedAtMs ?? fallbackSentAt;
980
+ if (nextAnchor) {
981
+ session.botModeIdleAnchorAt = nextAnchor;
982
+ }
983
+ }
984
+ getGroupIdleScheduleAnchorMs(session, lastActivityMsOverride) {
985
+ this.ensureGroupIdleAnchor(session);
986
+ const anchorMsCandidates = [
987
+ typeof lastActivityMsOverride === "number" ? lastActivityMsOverride : undefined,
988
+ readIsoMs(session.lastGroupActivityAt),
989
+ readIsoMs(session.botModeLastIdlePromptAt),
990
+ readIsoMs(session.botModeIdleAnchorAt),
991
+ ].filter((value) => typeof value === "number");
992
+ return anchorMsCandidates.length > 0 ? Math.max(...anchorMsCandidates) : Date.now();
993
+ }
994
+ noteGroupActivity(sessionId, sentAt) {
995
+ const session = this.sessions.get(sessionId);
996
+ if (!session || !session.groupMode) {
997
+ return;
998
+ }
999
+ delete session.botModeLastIdlePromptAt;
1000
+ session.lastGroupActivityAt = sentAt;
1001
+ if (this.isBotModeEnabled(session) && !session.botMuted) {
1002
+ this.scheduleGroupIdlePrompt(sessionId);
1003
+ return;
1004
+ }
1005
+ this.clearBotModeIdleTimer(session);
1006
+ }
1007
+ markParticipantSpoke(sessionId, appId, sentAt) {
1008
+ const session = this.sessions.get(sessionId);
1009
+ if (!session) {
1010
+ return;
1011
+ }
1012
+ const participant = session.participants.get(appId);
1013
+ if (!participant) {
1014
+ return;
1015
+ }
1016
+ participant.lastSeenAt = sentAt;
1017
+ participant.lastUserMessageAt = sentAt;
1018
+ this.clearBotModeSilentJoinTimer(session, appId);
1019
+ this.noteGroupActivity(sessionId, sentAt);
1020
+ }
1021
+ scheduleBotModeTimers(sessionId) {
1022
+ const session = this.sessions.get(sessionId);
1023
+ if (!session) {
1024
+ return;
1025
+ }
1026
+ if (!session.botModeSilentJoinTimers) {
1027
+ session.botModeSilentJoinTimers = new Map();
1028
+ }
1029
+ if (!this.isBotModeEnabled(session) || session.botMuted) {
1030
+ this.clearBotModeTimers(session);
1031
+ return;
1032
+ }
1033
+ this.ensureGroupIdleAnchor(session);
1034
+ this.scheduleGroupIdlePrompt(sessionId);
1035
+ for (const appId of session.participants.keys()) {
1036
+ this.scheduleSilentJoinPrompt(sessionId, appId);
1037
+ }
1038
+ }
1039
+ scheduleSilentJoinPrompt(sessionId, appId) {
1040
+ const session = this.sessions.get(sessionId);
1041
+ if (!session) {
1042
+ return;
1043
+ }
1044
+ if (!session.botModeSilentJoinTimers) {
1045
+ session.botModeSilentJoinTimers = new Map();
1046
+ }
1047
+ this.clearBotModeSilentJoinTimer(session, appId);
1048
+ if (!this.isBotModeEnabled(session) || session.botMuted) {
1049
+ return;
1050
+ }
1051
+ const participant = session.participants.get(appId);
1052
+ if (!participant ||
1053
+ participant.lastUserMessageAt ||
1054
+ participant.botModeSilentJoinPromptSentAt) {
1055
+ return;
1056
+ }
1057
+ const joinedAtMsRaw = new Date(participant.joinedAt).getTime();
1058
+ const joinedAtMs = Number.isFinite(joinedAtMsRaw) ? joinedAtMsRaw : Date.now();
1059
+ const delayMs = Math.max(0, joinedAtMs + this.getBotModeSilentJoinDelayMs() - Date.now());
1060
+ session.botModeSilentJoinTimers.set(appId, setTimeout(() => {
1061
+ void this.handleSilentJoinPrompt(sessionId, appId, joinedAtMs).catch((error) => {
1062
+ this.options.onLog?.(`[provider] bot mode silent join prompt failed for ${sessionId}/${appId}: ${error instanceof Error ? error.message : String(error)}`);
1063
+ });
1064
+ }, delayMs));
1065
+ }
1066
+ scheduleGroupIdlePrompt(sessionId, lastActivityMsOverride) {
1067
+ const session = this.sessions.get(sessionId);
1068
+ if (!session) {
1069
+ return;
1070
+ }
1071
+ this.clearBotModeIdleTimer(session);
1072
+ if (!this.isBotModeEnabled(session) ||
1073
+ session.botMuted ||
1074
+ session.participants.size === 0) {
1075
+ return;
1076
+ }
1077
+ const lastActivityMs = this.getGroupIdleScheduleAnchorMs(session, lastActivityMsOverride);
1078
+ const delayMs = Math.max(0, lastActivityMs + this.getBotModeIdleDelayMs() - Date.now());
1079
+ session.botModeIdleTimer = setTimeout(() => {
1080
+ void this.handleGroupIdlePrompt(sessionId, lastActivityMs).catch((error) => {
1081
+ this.options.onLog?.(`[provider] bot mode idle prompt failed for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
1082
+ });
1083
+ }, delayMs);
1084
+ }
1085
+ async handleSilentJoinPrompt(sessionId, appId, joinedAtMs) {
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();
1106
+ const languageInstruction = buildBotModeLanguageInstruction(session);
1107
+ const messages = await this.resolveBridgeMessages(session, {
1108
+ sessionId,
1109
+ invite: session.invite,
1110
+ message: buildBotModeSilentJoinPrompt({
1111
+ participantLabel: participant.displayName,
1112
+ joinedAt: participant.joinedAt,
1113
+ ...(languageInstruction ? { languageInstruction } : {}),
1114
+ }),
1115
+ history: this.buildBridgeHistory(session),
1116
+ });
1117
+ if (messages.length === 0) {
1118
+ this.scheduleSilentJoinPrompt(sessionId, appId);
1119
+ return;
1120
+ }
1121
+ for (const message of messages) {
1122
+ await this.sendAssistantMessage(sessionId, {
1123
+ text: message.text,
1124
+ sentAt,
1125
+ ...(message.attachments ? { attachments: message.attachments } : {}),
1126
+ });
1127
+ }
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
+ });
1188
+ }
653
1189
  async sendRenewalReminder(sessionId) {
654
1190
  const session = this.sessions.get(sessionId);
655
1191
  if (!session) {
@@ -915,15 +1451,6 @@ export class PrivateClawProvider {
915
1451
  }
916
1452
  session.history.push(turn);
917
1453
  }
918
- updateStoredUserBridgeText(session, messageId, bridgeText) {
919
- for (let index = session.history.length - 1; index >= 0; index -= 1) {
920
- const turn = session.history[index];
921
- if (turn?.role === "user" && turn.messageId === messageId) {
922
- turn.bridgeText = bridgeText;
923
- return;
924
- }
925
- }
926
- }
927
1454
  async sendWelcomeMessage(sessionId, targetAppId) {
928
1455
  const sentAt = nowIso();
929
1456
  const message = this.options.welcomeMessage ?? buildWelcomeMessage();
@@ -1110,6 +1637,9 @@ export class PrivateClawProvider {
1110
1637
  const wasRenewing = Boolean(session.pendingRenewal);
1111
1638
  this.verboseLog(`client_hello_processed session=${sessionId} appId=${JSON.stringify(participant.appId)} isNew=${participantState.isNew} participants=${session.participants.size} awaitingHello=${wasAwaitingHello} renewing=${wasRenewing} groupMode=${session.groupMode}`);
1112
1639
  session.state = "active";
1640
+ this.ensureGroupIdleAnchor(session, payload.sentAt);
1641
+ this.scheduleGroupIdlePrompt(sessionId);
1642
+ this.scheduleSilentJoinPrompt(sessionId, participant.appId);
1113
1643
  if (wasRenewing) {
1114
1644
  session.history.push({
1115
1645
  messageId: buildMessageId("system"),
@@ -1167,6 +1697,9 @@ export class PrivateClawProvider {
1167
1697
  (session.participants.size === 1
1168
1698
  ? [...session.participants.values()][0]
1169
1699
  : undefined);
1700
+ if (session.groupMode && participant) {
1701
+ this.markParticipantSpoke(sessionId, participant.appId, payload.sentAt);
1702
+ }
1170
1703
  const normalizedCommand = payload.text.trim().toLowerCase();
1171
1704
  const directBridgeSlashCommand = normalizeBridgeSlashCommandText(payload.text);
1172
1705
  const isRenewCommand = normalizedCommand === "/renew-session" ||
@@ -1276,6 +1809,12 @@ export class PrivateClawProvider {
1276
1809
  sentAt: payload.sentAt,
1277
1810
  messageId,
1278
1811
  });
1812
+ if (shouldMute) {
1813
+ this.clearBotModeTimers(session);
1814
+ }
1815
+ else {
1816
+ this.scheduleBotModeTimers(sessionId);
1817
+ }
1279
1818
  await this.sendCapabilities(sessionId);
1280
1819
  return;
1281
1820
  }
@@ -1297,8 +1836,8 @@ export class PrivateClawProvider {
1297
1836
  storeHistory: false,
1298
1837
  }
1299
1838
  : undefined;
1300
- if (shouldHandleVoiceAsynchronously) {
1301
- if (session.groupMode) {
1839
+ if (session.groupMode && session.botMuted && !directBridgeSlashCommand) {
1840
+ if (shouldHandleVoiceAsynchronously) {
1302
1841
  this.storeUserMessageTurn(session, {
1303
1842
  messageId: payload.clientMessageId,
1304
1843
  text: payload.text,
@@ -1319,16 +1858,31 @@ export class PrivateClawProvider {
1319
1858
  });
1320
1859
  }
1321
1860
  else {
1322
- this.storeUserMessageTurn(session, {
1323
- messageId: payload.clientMessageId,
1861
+ await this.sendParticipantMessage(sessionId, {
1324
1862
  text: payload.text,
1863
+ senderAppId: participant.appId,
1864
+ senderDisplayName: participant.displayName,
1865
+ clientMessageId: payload.clientMessageId,
1325
1866
  sentAt: payload.sentAt,
1326
1867
  ...(payload.attachments ? { attachments: payload.attachments } : {}),
1327
1868
  });
1328
1869
  }
1870
+ return;
1329
1871
  }
1330
- if (session.groupMode && session.botMuted && !directBridgeSlashCommand) {
1331
- 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 {
1332
1886
  await this.sendParticipantMessage(sessionId, {
1333
1887
  text: payload.text,
1334
1888
  senderAppId: participant.appId,
@@ -1336,9 +1890,9 @@ export class PrivateClawProvider {
1336
1890
  clientMessageId: payload.clientMessageId,
1337
1891
  sentAt: payload.sentAt,
1338
1892
  ...(payload.attachments ? { attachments: payload.attachments } : {}),
1893
+ storeHistory: false,
1339
1894
  });
1340
1895
  }
1341
- return;
1342
1896
  }
1343
1897
  if (voiceFeedbackParams) {
1344
1898
  await this.sendSystemMessage(sessionId, buildVoiceReceiptMessage(), "info", undefined, voiceFeedbackParams);
@@ -1348,130 +1902,9 @@ export class PrivateClawProvider {
1348
1902
  sentAt: payload.sentAt,
1349
1903
  });
1350
1904
  }
1351
- let preparedMessage;
1352
- try {
1353
- preparedMessage = await this.prepareUserMessage(session, payload, participant);
1354
- }
1355
- catch (error) {
1356
- await this.sendSystemMessage(sessionId, buildBridgeErrorMessage(error instanceof Error ? error.message : String(error)), "error", payload.clientMessageId, voiceFeedbackParams);
1357
- return;
1358
- }
1359
- if (shouldHandleVoiceAsynchronously) {
1360
- if (preparedMessage.historyBridgeText) {
1361
- this.updateStoredUserBridgeText(session, payload.clientMessageId, preparedMessage.historyBridgeText);
1362
- }
1363
- }
1364
- else if (session.groupMode) {
1365
- await this.sendParticipantMessage(sessionId, {
1366
- text: preparedMessage.text,
1367
- senderAppId: participant.appId,
1368
- senderDisplayName: participant.displayName,
1369
- clientMessageId: payload.clientMessageId,
1370
- sentAt: payload.sentAt,
1371
- ...(preparedMessage.attachments
1372
- ? { attachments: preparedMessage.attachments }
1373
- : {}),
1374
- ...(preparedMessage.historyBridgeText
1375
- ? { bridgeText: preparedMessage.historyBridgeText }
1376
- : {}),
1377
- });
1378
- }
1379
- else {
1380
- this.storeUserMessageTurn(session, {
1381
- messageId: payload.clientMessageId,
1382
- text: preparedMessage.text,
1383
- sentAt: payload.sentAt,
1384
- ...(preparedMessage.historyBridgeText
1385
- ? { bridgeText: preparedMessage.historyBridgeText }
1386
- : {}),
1387
- ...(preparedMessage.attachments
1388
- ? { attachments: preparedMessage.attachments }
1389
- : {}),
1390
- });
1391
- }
1392
- const bridgeMessage = preparedMessage.bridgeText ??
1393
- (session.groupMode && participant
1394
- ? `${participant.displayName}: ${preparedMessage.text}`
1395
- : preparedMessage.text);
1396
- const supportsThinkingTrace = this.options.bridge.supportsThinkingTrace === true;
1397
- const thinkingMessageId = buildThinkingMessageId(payload.clientMessageId);
1398
- let latestThinkingSummary = "";
1399
- let latestThinkingEntries = [];
1400
- try {
1401
- if (supportsThinkingTrace) {
1402
- await this.sendThinkingMessage(sessionId, {
1403
- messageId: thinkingMessageId,
1404
- status: "started",
1405
- summary: "",
1406
- entries: [],
1407
- replyTo: payload.clientMessageId,
1408
- sentAt: payload.sentAt,
1409
- storeHistory: false,
1410
- });
1411
- }
1412
- const bridgeResponse = await this.options.bridge.handleUserMessage({
1413
- sessionId,
1414
- invite: session.invite,
1415
- message: bridgeMessage,
1416
- ...(preparedMessage.bridgeAttachments
1417
- ? { attachments: preparedMessage.bridgeAttachments }
1418
- : preparedMessage.attachments
1419
- ? { attachments: preparedMessage.attachments }
1420
- : {}),
1421
- history: this.buildBridgeHistory(session),
1422
- ...(supportsThinkingTrace
1423
- ? {
1424
- onThinkingTrace: async (snapshot) => {
1425
- latestThinkingSummary = snapshot.summary;
1426
- latestThinkingEntries = cloneThinkingEntries(snapshot.entries);
1427
- await this.sendThinkingMessage(sessionId, {
1428
- messageId: thinkingMessageId,
1429
- status: "streaming",
1430
- summary: snapshot.summary,
1431
- entries: snapshot.entries,
1432
- replyTo: payload.clientMessageId,
1433
- sentAt: snapshot.sentAt,
1434
- storeHistory: snapshot.entries.length > 0,
1435
- });
1436
- },
1437
- }
1438
- : {}),
1439
- });
1440
- if (supportsThinkingTrace) {
1441
- await this.sendThinkingMessage(sessionId, {
1442
- messageId: thinkingMessageId,
1443
- status: "completed",
1444
- summary: latestThinkingSummary,
1445
- entries: latestThinkingEntries,
1446
- replyTo: payload.clientMessageId,
1447
- storeHistory: latestThinkingEntries.length > 0,
1448
- });
1449
- }
1450
- for (const message of normalizeBridgeMessages(bridgeResponse)) {
1451
- this.options.onLog?.(`[provider] bridge_message_out session=${sessionId} textChars=${message.text.length} attachments=${message.attachments?.length ?? 0}`);
1452
- for (const attachment of message.attachments ?? []) {
1453
- this.options.onLog?.(`[provider] attachment_out session=${sessionId} name=${JSON.stringify(attachment.name)} mimeType=${attachment.mimeType} sizeBytes=${attachment.sizeBytes} hasData=${Boolean(attachment.dataBase64?.trim())}`);
1454
- }
1455
- await this.sendAssistantMessage(sessionId, {
1456
- text: message.text,
1457
- replyTo: payload.clientMessageId,
1458
- ...(message.attachments ? { attachments: message.attachments } : {}),
1459
- });
1460
- }
1461
- }
1462
- catch (error) {
1463
- if (supportsThinkingTrace) {
1464
- await this.sendThinkingMessage(sessionId, {
1465
- messageId: thinkingMessageId,
1466
- status: "failed",
1467
- summary: latestThinkingSummary,
1468
- entries: latestThinkingEntries,
1469
- replyTo: payload.clientMessageId,
1470
- storeHistory: latestThinkingEntries.length > 0,
1471
- });
1472
- }
1473
- await this.sendSystemMessage(sessionId, buildBridgeErrorMessage(error instanceof Error ? error.message : String(error)), "error", payload.clientMessageId, voiceFeedbackParams);
1474
- }
1905
+ await this.enqueueSessionBridgeTask(sessionId, `user_message:${payload.clientMessageId}`, async () => {
1906
+ await this.processQueuedUserMessage(sessionId, payload, participant, voiceFeedbackParams);
1907
+ });
1475
1908
  return;
1476
1909
  }
1477
1910
  case "session_close": {
@@ -1489,12 +1922,17 @@ export class PrivateClawProvider {
1489
1922
  }
1490
1923
  const participant = session.participants.get(participantAppId);
1491
1924
  session.participants.delete(participantAppId);
1925
+ this.clearBotModeSilentJoinTimer(session, participantAppId);
1926
+ if (session.participants.size === 0) {
1927
+ delete session.botModeIdleAnchorAt;
1928
+ }
1492
1929
  if (participant && session.participants.size > 0) {
1493
1930
  await this.sendSystemMessageToGroupParticipants(sessionId, buildParticipantLeftMessage(participant.displayName), { sentAt: payload.sentAt });
1494
1931
  }
1495
1932
  if (session.participants.size > 0) {
1496
1933
  await this.sendCapabilities(sessionId);
1497
1934
  }
1935
+ this.scheduleGroupIdlePrompt(sessionId);
1498
1936
  return;
1499
1937
  }
1500
1938
  case "assistant_message":
@@ -1532,6 +1970,7 @@ export class PrivateClawProvider {
1532
1970
  participants: new Map(),
1533
1971
  removedParticipantAppIds: new Set(),
1534
1972
  state: "awaiting_hello",
1973
+ botModeSilentJoinTimers: new Map(),
1535
1974
  });
1536
1975
  this.scheduleRenewalReminder(sessionId);
1537
1976
  this.verboseLog(`session_created session=${sessionId} groupMode=${groupMode} label=${JSON.stringify(params?.label ?? "")} expiresAt=${JSON.stringify(expiresAt)} relayLabel=${JSON.stringify(relayLabel ?? "")} ttlMs=${params?.ttlMs ?? this.options.defaultTtlMs ?? DEFAULT_SESSION_TTL_MS}`);