@privateclaw/privateclaw 0.1.25 → 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/src/provider.ts CHANGED
@@ -14,6 +14,10 @@ import {
14
14
  type UserMessagePayload,
15
15
  } from "@privateclaw/protocol";
16
16
  import QRCode from "qrcode";
17
+ import {
18
+ BOT_MODE_IDLE_TOPICS,
19
+ pickBotModeIdleTopic,
20
+ } from "./bot-mode-topics.js";
17
21
  import {
18
22
  PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL,
19
23
  PRIVATECLAW_QR_IMAGE_MARGIN,
@@ -35,6 +39,7 @@ import type {
35
39
  BridgeMessage,
36
40
  BridgeResponse,
37
41
  PrivateClawConversationTurn,
42
+ PrivateClawAgentBridge,
38
43
  PrivateClawInviteBundle,
39
44
  PrivateClawProviderHandoffState,
40
45
  PrivateClawManagedSession,
@@ -49,6 +54,7 @@ const RENEW_SESSION_TTL_MS = DEFAULT_SESSION_TTL_MS;
49
54
  const SESSION_RENEWAL_REMINDER_WINDOW_MS = 30 * 60 * 1000;
50
55
  const BOT_MODE_SILENT_JOIN_DELAY_MS = 10 * 60 * 1000;
51
56
  const BOT_MODE_IDLE_DELAY_MS = 20 * 60 * 1000;
57
+ const BRIDGE_NO_REPLY_SENTINEL = "NO_REPLY";
52
58
  const PARTICIPANT_LABEL_MAX_CHARS = 12;
53
59
  const PARTICIPANT_FALLBACK_PREFIXES = [
54
60
  "流萤",
@@ -93,6 +99,25 @@ function normalizeBridgeMessages(
93
99
  );
94
100
  }
95
101
 
102
+ function isBridgeNoReplyMessage(message: {
103
+ text: string;
104
+ attachments?: ReadonlyArray<PrivateClawAttachment>;
105
+ }): boolean {
106
+ return (
107
+ (!message.attachments || message.attachments.length === 0) &&
108
+ message.text.trim() === BRIDGE_NO_REPLY_SENTINEL
109
+ );
110
+ }
111
+
112
+ function hasOnlyBridgeNoReplyMessages(
113
+ messages: ReadonlyArray<{
114
+ text: string;
115
+ attachments?: ReadonlyArray<PrivateClawAttachment>;
116
+ }>,
117
+ ): boolean {
118
+ return messages.length > 0 && messages.every((message) => isBridgeNoReplyMessage(message));
119
+ }
120
+
96
121
  function nowIso(): string {
97
122
  return new Date().toISOString();
98
123
  }
@@ -297,6 +322,9 @@ function toProviderSessionHandoff(
297
322
  ...(session.botModeLastIdlePromptAt
298
323
  ? { botModeLastIdlePromptAt: session.botModeLastIdlePromptAt }
299
324
  : {}),
325
+ ...(session.botModeLastIdleTopicId
326
+ ? { botModeLastIdleTopicId: session.botModeLastIdleTopicId }
327
+ : {}),
300
328
  };
301
329
  }
302
330
 
@@ -329,6 +357,9 @@ function fromProviderSessionHandoff(
329
357
  ...(snapshot.botModeLastIdlePromptAt
330
358
  ? { botModeLastIdlePromptAt: snapshot.botModeLastIdlePromptAt }
331
359
  : {}),
360
+ ...(snapshot.botModeLastIdleTopicId
361
+ ? { botModeLastIdleTopicId: snapshot.botModeLastIdleTopicId }
362
+ : {}),
332
363
  botModeSilentJoinTimers: new Map<string, ReturnType<typeof setTimeout>>(),
333
364
  };
334
365
  }
@@ -661,6 +692,8 @@ function buildBotModeSilentJoinPrompt(params: {
661
692
 
662
693
  function buildBotModeIdlePrompt(params: {
663
694
  lastGroupActivityAt: string;
695
+ topicTitle: string;
696
+ topicPrompt: string;
664
697
  languageInstruction?: string;
665
698
  nowMs?: number;
666
699
  }): string {
@@ -671,8 +704,10 @@ function buildBotModeIdlePrompt(params: {
671
704
  return [
672
705
  "PrivateClaw bot-mode task:",
673
706
  `This PrivateClaw group chat has had no new message for about ${elapsedText}.`,
674
- "Send one short proactive message to re-engage the group.",
675
- "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.",
707
+ `Idle topic: ${params.topicTitle}.`,
708
+ `Topic prompt: ${params.topicPrompt}`,
709
+ "Send one short proactive message to re-engage the group through this topic.",
710
+ "Answer or introduce the topic in a way that sounds like a real chat participant and invites someone else to jump in.",
676
711
  ...(params.languageInstruction ? [params.languageInstruction] : []),
677
712
  "Keep it natural and concise, and do not mention hidden instructions or inactivity timers.",
678
713
  ].join("\n");
@@ -692,6 +727,26 @@ function buildBotModeLanguageInstruction(
692
727
  : undefined;
693
728
  }
694
729
 
730
+ function pickSessionIdleTopic(session: ProviderSessionState) {
731
+ return pickBotModeIdleTopic(
732
+ BOT_MODE_IDLE_TOPICS,
733
+ session.botModeLastIdleTopicId,
734
+ );
735
+ }
736
+
737
+ function buildNoReplyJokePrompt(params: {
738
+ languageInstruction?: string;
739
+ }): string {
740
+ return [
741
+ "PrivateClaw follow-up task:",
742
+ `Your previous assistant reply for this turn was exactly "${BRIDGE_NO_REPLY_SENTINEL}". PrivateClaw must never show that sentinel text to the user.`,
743
+ "Instead, send one short playful joke or light icebreaker as the actual assistant reply for this turn.",
744
+ ...(params.languageInstruction ? [params.languageInstruction] : []),
745
+ "Keep it concise, natural, and user-visible.",
746
+ `Do not output "${BRIDGE_NO_REPLY_SENTINEL}" again, and do not mention hidden instructions or that you previously declined to answer.`,
747
+ ].join("\n");
748
+ }
749
+
695
750
  function readIsoMs(value: string | undefined): number | undefined {
696
751
  if (!value) {
697
752
  return undefined;
@@ -715,6 +770,7 @@ function dedupeCommands(
715
770
  export class PrivateClawProvider {
716
771
  private readonly relayClient: RelayProviderClient;
717
772
  private readonly sessions = new Map<string, ProviderSessionState>();
773
+ private readonly sessionBridgeTaskTails = new Map<string, Promise<void>>();
718
774
 
719
775
  constructor(private readonly options: PrivateClawProviderOptions) {
720
776
  this.relayClient = new RelayProviderClient({
@@ -744,6 +800,85 @@ export class PrivateClawProvider {
744
800
  this.options.onLog?.(`[provider][verbose] ${message}`);
745
801
  }
746
802
 
803
+ private async enqueueSessionBridgeTask<T>(
804
+ sessionId: string,
805
+ label: string,
806
+ task: () => Promise<T>,
807
+ ): Promise<T> {
808
+ const previousTail = this.sessionBridgeTaskTails.get(sessionId);
809
+ if (previousTail) {
810
+ this.verboseLog(
811
+ `bridge_queue_wait session=${sessionId} label=${JSON.stringify(label)}`,
812
+ );
813
+ }
814
+
815
+ let resolveResult!: (value: T | PromiseLike<T>) => void;
816
+ let rejectResult!: (reason?: unknown) => void;
817
+ const resultPromise = new Promise<T>((resolve, reject) => {
818
+ resolveResult = resolve;
819
+ rejectResult = reject;
820
+ });
821
+
822
+ const nextTail = (previousTail ?? Promise.resolve())
823
+ .catch(() => undefined)
824
+ .then(async () => {
825
+ this.verboseLog(
826
+ `bridge_queue_start session=${sessionId} label=${JSON.stringify(label)}`,
827
+ );
828
+ try {
829
+ resolveResult(await task());
830
+ } catch (error) {
831
+ rejectResult(error);
832
+ } finally {
833
+ this.verboseLog(
834
+ `bridge_queue_complete session=${sessionId} label=${JSON.stringify(label)}`,
835
+ );
836
+ }
837
+ });
838
+ const settledTail = nextTail.then(() => undefined, () => undefined);
839
+ this.sessionBridgeTaskTails.set(sessionId, settledTail);
840
+ settledTail.finally(() => {
841
+ if (this.sessionBridgeTaskTails.get(sessionId) === settledTail) {
842
+ this.sessionBridgeTaskTails.delete(sessionId);
843
+ }
844
+ });
845
+
846
+ return resultPromise;
847
+ }
848
+
849
+ private async resolveBridgeMessages(
850
+ session: ProviderSessionState,
851
+ params: Parameters<PrivateClawAgentBridge["handleUserMessage"]>[0],
852
+ ): Promise<Array<{ text: string; attachments?: PrivateClawAttachment[] }>> {
853
+ const initialResponse = await this.options.bridge.handleUserMessage(params);
854
+ const initialMessages = normalizeBridgeMessages(initialResponse);
855
+ if (!hasOnlyBridgeNoReplyMessages(initialMessages)) {
856
+ return initialMessages;
857
+ }
858
+
859
+ this.options.onLog?.(
860
+ `[provider] bridge_no_reply session=${params.sessionId} retrying_with_joke=true`,
861
+ );
862
+ const languageInstruction = buildBotModeLanguageInstruction(session);
863
+ const fallbackResponse = await this.options.bridge.handleUserMessage({
864
+ sessionId: params.sessionId,
865
+ invite: params.invite,
866
+ message: buildNoReplyJokePrompt({
867
+ ...(languageInstruction ? { languageInstruction } : {}),
868
+ }),
869
+ history: this.buildBridgeHistory(session),
870
+ ...(params.onThinkingTrace ? { onThinkingTrace: params.onThinkingTrace } : {}),
871
+ });
872
+ const fallbackMessages = normalizeBridgeMessages(fallbackResponse);
873
+ if (hasOnlyBridgeNoReplyMessages(fallbackMessages)) {
874
+ this.options.onLog?.(
875
+ `[provider] bridge_no_reply session=${params.sessionId} retrying_with_joke_failed=true`,
876
+ );
877
+ return [];
878
+ }
879
+ return fallbackMessages;
880
+ }
881
+
747
882
  async connect(): Promise<void> {
748
883
  this.verboseLog(
749
884
  `connect_start providerId=${this.relayClient.getProviderId()} relay=${JSON.stringify(this.options.providerWsUrl)}`,
@@ -911,6 +1046,7 @@ export class PrivateClawProvider {
911
1046
  }
912
1047
  this.clearBotModeTimers(session);
913
1048
  this.sessions.delete(sessionId);
1049
+ this.sessionBridgeTaskTails.delete(sessionId);
914
1050
  return session;
915
1051
  }
916
1052
 
@@ -1029,6 +1165,169 @@ export class PrivateClawProvider {
1029
1165
  };
1030
1166
  }
1031
1167
 
1168
+ private async processQueuedUserMessage(
1169
+ sessionId: string,
1170
+ payload: UserMessagePayload,
1171
+ participant: ProviderParticipantState | undefined,
1172
+ voiceFeedbackParams?: {
1173
+ targetAppId: string;
1174
+ storeHistory: false;
1175
+ },
1176
+ ): Promise<void> {
1177
+ const session = this.sessions.get(sessionId);
1178
+ if (!session) {
1179
+ return;
1180
+ }
1181
+
1182
+ let preparedMessage: PreparedUserMessage;
1183
+ try {
1184
+ preparedMessage = await this.prepareUserMessage(
1185
+ session,
1186
+ payload,
1187
+ participant,
1188
+ );
1189
+ } catch (error) {
1190
+ this.storeUserMessageTurn(session, {
1191
+ messageId: payload.clientMessageId,
1192
+ text: payload.text,
1193
+ sentAt: payload.sentAt,
1194
+ ...(participant
1195
+ ? {
1196
+ appId: participant.appId,
1197
+ participantLabel: participant.displayName,
1198
+ }
1199
+ : {}),
1200
+ ...(payload.attachments ? { attachments: payload.attachments } : {}),
1201
+ });
1202
+ await this.sendSystemMessage(
1203
+ sessionId,
1204
+ buildBridgeErrorMessage(
1205
+ error instanceof Error ? error.message : String(error),
1206
+ ),
1207
+ "error",
1208
+ payload.clientMessageId,
1209
+ voiceFeedbackParams,
1210
+ );
1211
+ return;
1212
+ }
1213
+
1214
+ this.storeUserMessageTurn(session, {
1215
+ messageId: payload.clientMessageId,
1216
+ text: preparedMessage.text,
1217
+ sentAt: payload.sentAt,
1218
+ ...(participant
1219
+ ? {
1220
+ appId: participant.appId,
1221
+ participantLabel: participant.displayName,
1222
+ }
1223
+ : {}),
1224
+ ...(preparedMessage.historyBridgeText
1225
+ ? { bridgeText: preparedMessage.historyBridgeText }
1226
+ : {}),
1227
+ ...(preparedMessage.attachments
1228
+ ? { attachments: preparedMessage.attachments }
1229
+ : {}),
1230
+ });
1231
+
1232
+ const bridgeMessage =
1233
+ preparedMessage.bridgeText ??
1234
+ (session.groupMode && participant
1235
+ ? `${participant.displayName}: ${preparedMessage.text}`
1236
+ : preparedMessage.text);
1237
+ const supportsThinkingTrace =
1238
+ this.options.bridge.supportsThinkingTrace === true;
1239
+ const thinkingMessageId = buildThinkingMessageId(payload.clientMessageId);
1240
+ let latestThinkingSummary = "";
1241
+ let latestThinkingEntries: PrivateClawThinkingEntry[] = [];
1242
+ try {
1243
+ if (supportsThinkingTrace) {
1244
+ await this.sendThinkingMessage(sessionId, {
1245
+ messageId: thinkingMessageId,
1246
+ status: "started",
1247
+ summary: "",
1248
+ entries: [],
1249
+ replyTo: payload.clientMessageId,
1250
+ sentAt: payload.sentAt,
1251
+ storeHistory: false,
1252
+ });
1253
+ }
1254
+ const messages = await this.resolveBridgeMessages(session, {
1255
+ sessionId,
1256
+ invite: session.invite,
1257
+ message: bridgeMessage,
1258
+ ...(preparedMessage.bridgeAttachments
1259
+ ? { attachments: preparedMessage.bridgeAttachments }
1260
+ : preparedMessage.attachments
1261
+ ? { attachments: preparedMessage.attachments }
1262
+ : {}),
1263
+ history: this.buildBridgeHistory(session),
1264
+ ...(supportsThinkingTrace
1265
+ ? {
1266
+ onThinkingTrace: async (snapshot) => {
1267
+ latestThinkingSummary = snapshot.summary;
1268
+ latestThinkingEntries = cloneThinkingEntries(snapshot.entries);
1269
+ await this.sendThinkingMessage(sessionId, {
1270
+ messageId: thinkingMessageId,
1271
+ status: "streaming",
1272
+ summary: snapshot.summary,
1273
+ entries: snapshot.entries,
1274
+ replyTo: payload.clientMessageId,
1275
+ sentAt: snapshot.sentAt,
1276
+ storeHistory: snapshot.entries.length > 0,
1277
+ });
1278
+ },
1279
+ }
1280
+ : {}),
1281
+ });
1282
+ if (supportsThinkingTrace) {
1283
+ await this.sendThinkingMessage(sessionId, {
1284
+ messageId: thinkingMessageId,
1285
+ status: "completed",
1286
+ summary: latestThinkingSummary,
1287
+ entries: latestThinkingEntries,
1288
+ replyTo: payload.clientMessageId,
1289
+ storeHistory: latestThinkingEntries.length > 0,
1290
+ });
1291
+ }
1292
+
1293
+ for (const message of messages) {
1294
+ this.options.onLog?.(
1295
+ `[provider] bridge_message_out session=${sessionId} textChars=${message.text.length} attachments=${message.attachments?.length ?? 0}`,
1296
+ );
1297
+ for (const attachment of message.attachments ?? []) {
1298
+ this.options.onLog?.(
1299
+ `[provider] attachment_out session=${sessionId} name=${JSON.stringify(attachment.name)} mimeType=${attachment.mimeType} sizeBytes=${attachment.sizeBytes} hasData=${Boolean(attachment.dataBase64?.trim())}`,
1300
+ );
1301
+ }
1302
+ await this.sendAssistantMessage(sessionId, {
1303
+ text: message.text,
1304
+ replyTo: payload.clientMessageId,
1305
+ ...(message.attachments ? { attachments: message.attachments } : {}),
1306
+ });
1307
+ }
1308
+ } catch (error) {
1309
+ if (supportsThinkingTrace) {
1310
+ await this.sendThinkingMessage(sessionId, {
1311
+ messageId: thinkingMessageId,
1312
+ status: "failed",
1313
+ summary: latestThinkingSummary,
1314
+ entries: latestThinkingEntries,
1315
+ replyTo: payload.clientMessageId,
1316
+ storeHistory: latestThinkingEntries.length > 0,
1317
+ });
1318
+ }
1319
+ await this.sendSystemMessage(
1320
+ sessionId,
1321
+ buildBridgeErrorMessage(
1322
+ error instanceof Error ? error.message : String(error),
1323
+ ),
1324
+ "error",
1325
+ payload.clientMessageId,
1326
+ voiceFeedbackParams,
1327
+ );
1328
+ }
1329
+ }
1330
+
1032
1331
  private listParticipants(
1033
1332
  session: ProviderSessionState,
1034
1333
  ): PrivateClawParticipant[] {
@@ -1270,106 +1569,125 @@ export class PrivateClawProvider {
1270
1569
  appId: string,
1271
1570
  joinedAtMs: number,
1272
1571
  ): Promise<void> {
1273
- const session = this.sessions.get(sessionId);
1274
- if (!session) {
1275
- return;
1276
- }
1277
- this.clearBotModeSilentJoinTimer(session, appId);
1278
- const participant = session.participants.get(appId);
1279
- if (
1280
- !participant ||
1281
- !this.isBotModeEnabled(session) ||
1282
- session.botMuted ||
1283
- participant.lastUserMessageAt ||
1284
- participant.botModeSilentJoinPromptSentAt
1285
- ) {
1286
- return;
1287
- }
1288
- const dueAtMs = joinedAtMs + this.getBotModeSilentJoinDelayMs();
1289
- if (Date.now() < dueAtMs) {
1290
- this.scheduleSilentJoinPrompt(sessionId, appId);
1291
- return;
1292
- }
1293
- const sentAt = nowIso();
1294
- const languageInstruction = buildBotModeLanguageInstruction(session);
1295
- const bridgeResponse = await this.options.bridge.handleUserMessage({
1572
+ await this.enqueueSessionBridgeTask(
1296
1573
  sessionId,
1297
- invite: session.invite,
1298
- message: buildBotModeSilentJoinPrompt({
1299
- participantLabel: participant.displayName,
1300
- joinedAt: participant.joinedAt,
1301
- ...(languageInstruction ? { languageInstruction } : {}),
1302
- }),
1303
- history: this.buildBridgeHistory(session),
1304
- });
1305
- for (const message of normalizeBridgeMessages(bridgeResponse)) {
1306
- await this.sendAssistantMessage(sessionId, {
1307
- text: message.text,
1308
- sentAt,
1309
- ...(message.attachments ? { attachments: message.attachments } : {}),
1310
- });
1311
- }
1312
- participant.botModeSilentJoinPromptSentAt = sentAt;
1574
+ `bot_mode_silent_join:${appId}`,
1575
+ async () => {
1576
+ const session = this.sessions.get(sessionId);
1577
+ if (!session) {
1578
+ return;
1579
+ }
1580
+ this.clearBotModeSilentJoinTimer(session, appId);
1581
+ const participant = session.participants.get(appId);
1582
+ if (
1583
+ !participant ||
1584
+ !this.isBotModeEnabled(session) ||
1585
+ session.botMuted ||
1586
+ participant.lastUserMessageAt ||
1587
+ participant.botModeSilentJoinPromptSentAt
1588
+ ) {
1589
+ return;
1590
+ }
1591
+ const dueAtMs = joinedAtMs + this.getBotModeSilentJoinDelayMs();
1592
+ if (Date.now() < dueAtMs) {
1593
+ this.scheduleSilentJoinPrompt(sessionId, appId);
1594
+ return;
1595
+ }
1596
+ const sentAt = nowIso();
1597
+ const languageInstruction = buildBotModeLanguageInstruction(session);
1598
+ const messages = await this.resolveBridgeMessages(session, {
1599
+ sessionId,
1600
+ invite: session.invite,
1601
+ message: buildBotModeSilentJoinPrompt({
1602
+ participantLabel: participant.displayName,
1603
+ joinedAt: participant.joinedAt,
1604
+ ...(languageInstruction ? { languageInstruction } : {}),
1605
+ }),
1606
+ history: this.buildBridgeHistory(session),
1607
+ });
1608
+ if (messages.length === 0) {
1609
+ this.scheduleSilentJoinPrompt(sessionId, appId);
1610
+ return;
1611
+ }
1612
+ for (const message of messages) {
1613
+ await this.sendAssistantMessage(sessionId, {
1614
+ text: message.text,
1615
+ sentAt,
1616
+ ...(message.attachments ? { attachments: message.attachments } : {}),
1617
+ });
1618
+ }
1619
+ participant.botModeSilentJoinPromptSentAt = sentAt;
1620
+ },
1621
+ );
1313
1622
  }
1314
1623
 
1315
1624
  private async handleGroupIdlePrompt(
1316
1625
  sessionId: string,
1317
1626
  lastActivityMs: number,
1318
1627
  ): Promise<void> {
1319
- const session = this.sessions.get(sessionId);
1320
- if (!session) {
1321
- return;
1322
- }
1323
- this.clearBotModeIdleTimer(session);
1324
- if (
1325
- !this.isBotModeEnabled(session) ||
1326
- session.botMuted ||
1327
- session.participants.size === 0
1328
- ) {
1329
- return;
1330
- }
1331
- const currentActivityMs = this.getGroupIdleScheduleAnchorMs(session);
1332
- if (currentActivityMs > lastActivityMs) {
1333
- this.scheduleGroupIdlePrompt(sessionId, currentActivityMs);
1334
- return;
1335
- }
1336
- const dueAtMs = currentActivityMs + this.getBotModeIdleDelayMs();
1337
- if (Date.now() < dueAtMs) {
1338
- this.scheduleGroupIdlePrompt(sessionId, currentActivityMs);
1339
- return;
1340
- }
1341
- try {
1342
- const languageInstruction = buildBotModeLanguageInstruction(session);
1343
- const bridgeResponse = await this.options.bridge.handleUserMessage({
1344
- sessionId,
1345
- invite: session.invite,
1346
- message: buildBotModeIdlePrompt({
1347
- lastGroupActivityAt: session.lastGroupActivityAt ?? nowIso(),
1348
- ...(languageInstruction ? { languageInstruction } : {}),
1349
- }),
1350
- history: this.buildBridgeHistory(session),
1351
- });
1352
- const messages = normalizeBridgeMessages(bridgeResponse);
1353
- if (messages.length === 0) {
1354
- this.scheduleGroupIdlePrompt(sessionId, Date.now());
1355
- return;
1356
- }
1357
- const sentAt = nowIso();
1358
- for (const message of messages) {
1359
- await this.sendAssistantMessage(sessionId, {
1360
- text: message.text,
1361
- sentAt,
1362
- ...(message.attachments ? { attachments: message.attachments } : {}),
1363
- });
1364
- }
1365
- session.botModeLastIdlePromptAt = sentAt;
1366
- this.scheduleGroupIdlePrompt(sessionId);
1367
- } catch (error) {
1368
- this.options.onLog?.(
1369
- `[provider] bot mode idle prompt bridge error for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,
1370
- );
1371
- this.scheduleGroupIdlePrompt(sessionId, Date.now());
1372
- }
1628
+ await this.enqueueSessionBridgeTask(
1629
+ sessionId,
1630
+ "bot_mode_idle_prompt",
1631
+ async () => {
1632
+ const session = this.sessions.get(sessionId);
1633
+ if (!session) {
1634
+ return;
1635
+ }
1636
+ this.clearBotModeIdleTimer(session);
1637
+ if (
1638
+ !this.isBotModeEnabled(session) ||
1639
+ session.botMuted ||
1640
+ session.participants.size === 0
1641
+ ) {
1642
+ return;
1643
+ }
1644
+ const currentActivityMs = this.getGroupIdleScheduleAnchorMs(session);
1645
+ if (currentActivityMs > lastActivityMs) {
1646
+ this.scheduleGroupIdlePrompt(sessionId, currentActivityMs);
1647
+ return;
1648
+ }
1649
+ const dueAtMs = currentActivityMs + this.getBotModeIdleDelayMs();
1650
+ if (Date.now() < dueAtMs) {
1651
+ this.scheduleGroupIdlePrompt(sessionId, currentActivityMs);
1652
+ return;
1653
+ }
1654
+ try {
1655
+ const languageInstruction = buildBotModeLanguageInstruction(session);
1656
+ const topic = pickSessionIdleTopic(session);
1657
+ const messages = await this.resolveBridgeMessages(session, {
1658
+ sessionId,
1659
+ invite: session.invite,
1660
+ message: buildBotModeIdlePrompt({
1661
+ lastGroupActivityAt: session.lastGroupActivityAt ?? nowIso(),
1662
+ topicTitle: topic.title,
1663
+ topicPrompt: topic.prompt,
1664
+ ...(languageInstruction ? { languageInstruction } : {}),
1665
+ }),
1666
+ history: this.buildBridgeHistory(session),
1667
+ });
1668
+ if (messages.length === 0) {
1669
+ this.scheduleGroupIdlePrompt(sessionId, Date.now());
1670
+ return;
1671
+ }
1672
+ const sentAt = nowIso();
1673
+ for (const message of messages) {
1674
+ await this.sendAssistantMessage(sessionId, {
1675
+ text: message.text,
1676
+ sentAt,
1677
+ ...(message.attachments ? { attachments: message.attachments } : {}),
1678
+ });
1679
+ }
1680
+ session.botModeLastIdlePromptAt = sentAt;
1681
+ session.botModeLastIdleTopicId = topic.id;
1682
+ this.scheduleGroupIdlePrompt(sessionId);
1683
+ } catch (error) {
1684
+ this.options.onLog?.(
1685
+ `[provider] bot mode idle prompt bridge error for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,
1686
+ );
1687
+ this.scheduleGroupIdlePrompt(sessionId, Date.now());
1688
+ }
1689
+ },
1690
+ );
1373
1691
  }
1374
1692
 
1375
1693
  private async sendRenewalReminder(sessionId: string): Promise<void> {
@@ -1829,20 +2147,6 @@ export class PrivateClawProvider {
1829
2147
  session.history.push(turn);
1830
2148
  }
1831
2149
 
1832
- private updateStoredUserBridgeText(
1833
- session: ProviderSessionState,
1834
- messageId: string,
1835
- bridgeText: string,
1836
- ): void {
1837
- for (let index = session.history.length - 1; index >= 0; index -= 1) {
1838
- const turn = session.history[index];
1839
- if (turn?.role === "user" && turn.messageId === messageId) {
1840
- turn.bridgeText = bridgeText;
1841
- return;
1842
- }
1843
- }
1844
- }
1845
-
1846
2150
  private async sendWelcomeMessage(
1847
2151
  sessionId: string,
1848
2152
  targetAppId?: string,
@@ -2387,7 +2691,12 @@ export class PrivateClawProvider {
2387
2691
  const containsAudioAttachment = hasAudioAttachments(payload.attachments);
2388
2692
  const shouldHandleVoiceAsynchronously =
2389
2693
  containsAudioAttachment && supportsVoiceTranscription;
2390
- const voiceFeedbackParams =
2694
+ const voiceFeedbackParams:
2695
+ | {
2696
+ targetAppId: string;
2697
+ storeHistory: false;
2698
+ }
2699
+ | undefined =
2391
2700
  shouldHandleVoiceAsynchronously && participant
2392
2701
  ? {
2393
2702
  targetAppId: participant.appId,
@@ -2395,8 +2704,8 @@ export class PrivateClawProvider {
2395
2704
  }
2396
2705
  : undefined;
2397
2706
 
2398
- if (shouldHandleVoiceAsynchronously) {
2399
- if (session.groupMode) {
2707
+ if (session.groupMode && session.botMuted && !directBridgeSlashCommand) {
2708
+ if (shouldHandleVoiceAsynchronously) {
2400
2709
  this.storeUserMessageTurn(session, {
2401
2710
  messageId: payload.clientMessageId,
2402
2711
  text: payload.text,
@@ -2416,17 +2725,31 @@ export class PrivateClawProvider {
2416
2725
  storeHistory: false,
2417
2726
  });
2418
2727
  } else {
2419
- this.storeUserMessageTurn(session, {
2420
- messageId: payload.clientMessageId,
2728
+ await this.sendParticipantMessage(sessionId, {
2421
2729
  text: payload.text,
2730
+ senderAppId: participant!.appId,
2731
+ senderDisplayName: participant!.displayName,
2732
+ clientMessageId: payload.clientMessageId,
2422
2733
  sentAt: payload.sentAt,
2423
2734
  ...(payload.attachments ? { attachments: payload.attachments } : {}),
2424
2735
  });
2425
2736
  }
2737
+ return;
2426
2738
  }
2427
2739
 
2428
- if (session.groupMode && session.botMuted && !directBridgeSlashCommand) {
2429
- if (!shouldHandleVoiceAsynchronously) {
2740
+ if (session.groupMode) {
2741
+ if (shouldHandleVoiceAsynchronously) {
2742
+ await this.sendParticipantMessageToGroupParticipants(sessionId, {
2743
+ text: payload.text,
2744
+ senderAppId: participant!.appId,
2745
+ senderDisplayName: participant!.displayName,
2746
+ clientMessageId: payload.clientMessageId,
2747
+ sentAt: payload.sentAt,
2748
+ ...(payload.attachments ? { attachments: payload.attachments } : {}),
2749
+ excludeAppId: participant!.appId,
2750
+ storeHistory: false,
2751
+ });
2752
+ } else {
2430
2753
  await this.sendParticipantMessage(sessionId, {
2431
2754
  text: payload.text,
2432
2755
  senderAppId: participant!.appId,
@@ -2434,9 +2757,9 @@ export class PrivateClawProvider {
2434
2757
  clientMessageId: payload.clientMessageId,
2435
2758
  sentAt: payload.sentAt,
2436
2759
  ...(payload.attachments ? { attachments: payload.attachments } : {}),
2760
+ storeHistory: false,
2437
2761
  });
2438
2762
  }
2439
- return;
2440
2763
  }
2441
2764
 
2442
2765
  if (voiceFeedbackParams) {
@@ -2454,159 +2777,18 @@ export class PrivateClawProvider {
2454
2777
  });
2455
2778
  }
2456
2779
 
2457
- let preparedMessage: PreparedUserMessage;
2458
- try {
2459
- preparedMessage = await this.prepareUserMessage(
2460
- session,
2461
- payload,
2462
- participant,
2463
- );
2464
- } catch (error) {
2465
- await this.sendSystemMessage(
2466
- sessionId,
2467
- buildBridgeErrorMessage(
2468
- error instanceof Error ? error.message : String(error),
2469
- ),
2470
- "error",
2471
- payload.clientMessageId,
2472
- voiceFeedbackParams,
2473
- );
2474
- return;
2475
- }
2476
-
2477
- if (shouldHandleVoiceAsynchronously) {
2478
- if (preparedMessage.historyBridgeText) {
2479
- this.updateStoredUserBridgeText(
2480
- session,
2481
- payload.clientMessageId,
2482
- preparedMessage.historyBridgeText,
2483
- );
2484
- }
2485
- } else if (session.groupMode) {
2486
- await this.sendParticipantMessage(sessionId, {
2487
- text: preparedMessage.text,
2488
- senderAppId: participant!.appId,
2489
- senderDisplayName: participant!.displayName,
2490
- clientMessageId: payload.clientMessageId,
2491
- sentAt: payload.sentAt,
2492
- ...(preparedMessage.attachments
2493
- ? { attachments: preparedMessage.attachments }
2494
- : {}),
2495
- ...(preparedMessage.historyBridgeText
2496
- ? { bridgeText: preparedMessage.historyBridgeText }
2497
- : {}),
2498
- });
2499
- } else {
2500
- this.storeUserMessageTurn(session, {
2501
- messageId: payload.clientMessageId,
2502
- text: preparedMessage.text,
2503
- sentAt: payload.sentAt,
2504
- ...(preparedMessage.historyBridgeText
2505
- ? { bridgeText: preparedMessage.historyBridgeText }
2506
- : {}),
2507
- ...(preparedMessage.attachments
2508
- ? { attachments: preparedMessage.attachments }
2509
- : {}),
2510
- });
2511
- }
2512
-
2513
- const bridgeMessage =
2514
- preparedMessage.bridgeText ??
2515
- (session.groupMode && participant
2516
- ? `${participant.displayName}: ${preparedMessage.text}`
2517
- : preparedMessage.text);
2518
- const supportsThinkingTrace =
2519
- this.options.bridge.supportsThinkingTrace === true;
2520
- const thinkingMessageId = buildThinkingMessageId(payload.clientMessageId);
2521
- let latestThinkingSummary = "";
2522
- let latestThinkingEntries: PrivateClawThinkingEntry[] = [];
2523
- try {
2524
- if (supportsThinkingTrace) {
2525
- await this.sendThinkingMessage(sessionId, {
2526
- messageId: thinkingMessageId,
2527
- status: "started",
2528
- summary: "",
2529
- entries: [],
2530
- replyTo: payload.clientMessageId,
2531
- sentAt: payload.sentAt,
2532
- storeHistory: false,
2533
- });
2534
- }
2535
- const bridgeResponse = await this.options.bridge.handleUserMessage({
2536
- sessionId,
2537
- invite: session.invite,
2538
- message: bridgeMessage,
2539
- ...(preparedMessage.bridgeAttachments
2540
- ? { attachments: preparedMessage.bridgeAttachments }
2541
- : preparedMessage.attachments
2542
- ? { attachments: preparedMessage.attachments }
2543
- : {}),
2544
- history: this.buildBridgeHistory(session),
2545
- ...(supportsThinkingTrace
2546
- ? {
2547
- onThinkingTrace: async (snapshot) => {
2548
- latestThinkingSummary = snapshot.summary;
2549
- latestThinkingEntries = cloneThinkingEntries(snapshot.entries);
2550
- await this.sendThinkingMessage(sessionId, {
2551
- messageId: thinkingMessageId,
2552
- status: "streaming",
2553
- summary: snapshot.summary,
2554
- entries: snapshot.entries,
2555
- replyTo: payload.clientMessageId,
2556
- sentAt: snapshot.sentAt,
2557
- storeHistory: snapshot.entries.length > 0,
2558
- });
2559
- },
2560
- }
2561
- : {}),
2562
- });
2563
- if (supportsThinkingTrace) {
2564
- await this.sendThinkingMessage(sessionId, {
2565
- messageId: thinkingMessageId,
2566
- status: "completed",
2567
- summary: latestThinkingSummary,
2568
- entries: latestThinkingEntries,
2569
- replyTo: payload.clientMessageId,
2570
- storeHistory: latestThinkingEntries.length > 0,
2571
- });
2572
- }
2573
-
2574
- for (const message of normalizeBridgeMessages(bridgeResponse)) {
2575
- this.options.onLog?.(
2576
- `[provider] bridge_message_out session=${sessionId} textChars=${message.text.length} attachments=${message.attachments?.length ?? 0}`,
2780
+ await this.enqueueSessionBridgeTask(
2781
+ sessionId,
2782
+ `user_message:${payload.clientMessageId}`,
2783
+ async () => {
2784
+ await this.processQueuedUserMessage(
2785
+ sessionId,
2786
+ payload,
2787
+ participant,
2788
+ voiceFeedbackParams,
2577
2789
  );
2578
- for (const attachment of message.attachments ?? []) {
2579
- this.options.onLog?.(
2580
- `[provider] attachment_out session=${sessionId} name=${JSON.stringify(attachment.name)} mimeType=${attachment.mimeType} sizeBytes=${attachment.sizeBytes} hasData=${Boolean(attachment.dataBase64?.trim())}`,
2581
- );
2582
- }
2583
- await this.sendAssistantMessage(sessionId, {
2584
- text: message.text,
2585
- replyTo: payload.clientMessageId,
2586
- ...(message.attachments ? { attachments: message.attachments } : {}),
2587
- });
2588
- }
2589
- } catch (error) {
2590
- if (supportsThinkingTrace) {
2591
- await this.sendThinkingMessage(sessionId, {
2592
- messageId: thinkingMessageId,
2593
- status: "failed",
2594
- summary: latestThinkingSummary,
2595
- entries: latestThinkingEntries,
2596
- replyTo: payload.clientMessageId,
2597
- storeHistory: latestThinkingEntries.length > 0,
2598
- });
2599
- }
2600
- await this.sendSystemMessage(
2601
- sessionId,
2602
- buildBridgeErrorMessage(
2603
- error instanceof Error ? error.message : String(error),
2604
- ),
2605
- "error",
2606
- payload.clientMessageId,
2607
- voiceFeedbackParams,
2608
- );
2609
- }
2790
+ },
2791
+ );
2610
2792
  return;
2611
2793
  }
2612
2794
  case "session_close": {