@privateclaw/privateclaw 0.1.14 → 0.1.16

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
@@ -9,6 +9,7 @@ import {
9
9
  type PrivateClawInvite,
10
10
  type PrivateClawParticipant,
11
11
  type PrivateClawSlashCommand,
12
+ type UserMessagePayload,
12
13
  } from "@privateclaw/protocol";
13
14
  import QRCode from "qrcode";
14
15
  import {
@@ -66,6 +67,14 @@ const PARTICIPANT_FALLBACK_SUFFIXES = [
66
67
  "鸮",
67
68
  ] as const;
68
69
 
70
+ interface PreparedUserMessage {
71
+ text: string;
72
+ bridgeText?: string;
73
+ historyBridgeText?: string;
74
+ attachments?: PrivateClawAttachment[];
75
+ bridgeAttachments?: PrivateClawAttachment[];
76
+ }
77
+
69
78
  function normalizeBridgeMessages(
70
79
  response: BridgeResponse,
71
80
  ): Array<{ text: string; attachments?: PrivateClawAttachment[] }> {
@@ -88,6 +97,10 @@ function buildMessageId(prefix: string): string {
88
97
  return `${prefix}-${randomUUID()}`;
89
98
  }
90
99
 
100
+ function buildPendingAssistantMessageId(replyTo: string): string {
101
+ return `pending-${replyTo}`;
102
+ }
103
+
91
104
  function sanitizeParticipantLabel(raw: string | undefined): string | undefined {
92
105
  if (!raw) {
93
106
  return undefined;
@@ -281,6 +294,12 @@ function buildSessionQrFailureMessage(details: string): string {
281
294
  function formatBridgeHistoryTurn(
282
295
  turn: PrivateClawConversationTurn,
283
296
  ): PrivateClawConversationTurn {
297
+ if (turn.role === "user" && turn.bridgeText?.trim()) {
298
+ return {
299
+ ...turn,
300
+ text: turn.bridgeText,
301
+ };
302
+ }
284
303
  if (turn.role !== "user" || !turn.participantLabel) {
285
304
  return turn;
286
305
  }
@@ -291,6 +310,57 @@ function formatBridgeHistoryTurn(
291
310
  };
292
311
  }
293
312
 
313
+ function isAudioAttachment(attachment: PrivateClawAttachment): boolean {
314
+ const normalizedMimeType = attachment.mimeType.trim().toLowerCase();
315
+ if (normalizedMimeType.startsWith("audio/")) {
316
+ return true;
317
+ }
318
+ return /\.(?:aac|caf|m4a|mp3|ogg|opus|wav)$/iu.test(attachment.name.trim());
319
+ }
320
+
321
+ function hasAudioAttachments(
322
+ attachments?: ReadonlyArray<PrivateClawAttachment>,
323
+ ): boolean {
324
+ return (attachments ?? []).some(isAudioAttachment);
325
+ }
326
+
327
+ function mergeVoiceTranscriptText(transcript: string, fallbackText: string): string {
328
+ const normalizedTranscript = transcript.trim();
329
+ const normalizedFallback = fallbackText.trim();
330
+ if (normalizedTranscript === "") {
331
+ return normalizedFallback;
332
+ }
333
+ if (
334
+ normalizedFallback === "" ||
335
+ normalizedFallback.localeCompare(normalizedTranscript, undefined, {
336
+ sensitivity: "accent",
337
+ }) === 0
338
+ ) {
339
+ return normalizedTranscript;
340
+ }
341
+ return `${normalizedTranscript}\n\n${normalizedFallback}`;
342
+ }
343
+
344
+ function buildVoiceBridgeText(speakerName: string, messageText: string): string {
345
+ const normalizedSpeakerName = speakerName.trim();
346
+ const normalizedMessageText = messageText.trim();
347
+ if (normalizedSpeakerName === "") {
348
+ return normalizedMessageText;
349
+ }
350
+ return `${normalizedSpeakerName}说:${normalizedMessageText}`;
351
+ }
352
+
353
+ function buildVoiceBridgePromptText(speakerName: string, messageText: string): string {
354
+ const bridgeText = buildVoiceBridgeText(speakerName, messageText);
355
+ return [
356
+ "PrivateClaw note: the next line is the speech-to-text transcript of a user's voice message.",
357
+ "Treat it as the user's original request and respond directly to the request itself.",
358
+ "Do not mention transcription, speech recognition, or the transcript unless the user explicitly asks about it.",
359
+ "",
360
+ bridgeText,
361
+ ].join("\n");
362
+ }
363
+
294
364
  function toParticipantSnapshot(
295
365
  participant: ProviderParticipantState,
296
366
  ): PrivateClawParticipant {
@@ -428,6 +498,13 @@ function buildBridgeErrorMessage(details: string): string {
428
498
  );
429
499
  }
430
500
 
501
+ function buildVoiceReceiptMessage(): string {
502
+ return formatBilingualInline(
503
+ "我已经收到你的语音,正在努力理解。",
504
+ "I received your voice message and am working on understanding it.",
505
+ );
506
+ }
507
+
431
508
  function buildUnsupportedPayloadMessage(kind: string): string {
432
509
  return formatBilingualInline(
433
510
  `不支持的 PrivateClaw 负载类型:${kind}`,
@@ -666,6 +743,60 @@ export class PrivateClawProvider {
666
743
  return session.history.map(formatBridgeHistoryTurn);
667
744
  }
668
745
 
746
+ private async prepareUserMessage(
747
+ session: ProviderSessionState,
748
+ payload: UserMessagePayload,
749
+ participant: ProviderParticipantState | undefined,
750
+ ): Promise<PreparedUserMessage> {
751
+ const allAttachments = payload.attachments ?? [];
752
+ const audioAttachments = allAttachments.filter(isAudioAttachment);
753
+ if (
754
+ audioAttachments.length === 0 ||
755
+ !this.options.bridge.transcribeAudioAttachments
756
+ ) {
757
+ return {
758
+ text: payload.text,
759
+ ...(allAttachments.length > 0 ? { attachments: allAttachments } : {}),
760
+ ...(allAttachments.length > 0 ? { bridgeAttachments: allAttachments } : {}),
761
+ };
762
+ }
763
+
764
+ this.options.onLog?.(
765
+ `[provider] voice_transcription_start session=${session.invite.sessionId} request=${payload.clientMessageId} audioAttachments=${audioAttachments.length}`,
766
+ );
767
+ const transcript = (
768
+ await this.options.bridge.transcribeAudioAttachments({
769
+ sessionId: session.invite.sessionId,
770
+ requestId: payload.clientMessageId,
771
+ attachments: audioAttachments,
772
+ })
773
+ ).trim();
774
+ if (transcript === "") {
775
+ throw new Error("OpenClaw STT returned an empty transcript.");
776
+ }
777
+
778
+ const text = mergeVoiceTranscriptText(transcript, payload.text);
779
+ const speakerName =
780
+ participant?.displayName ??
781
+ sanitizeParticipantLabel(payload.displayName) ??
782
+ "用户";
783
+ const passthroughAttachments = allAttachments.filter(
784
+ (attachment) => !isAudioAttachment(attachment),
785
+ );
786
+ this.options.onLog?.(
787
+ `[provider] voice_transcription_complete session=${session.invite.sessionId} request=${payload.clientMessageId} transcriptChars=${transcript.length} passthroughAttachments=${passthroughAttachments.length}`,
788
+ );
789
+ return {
790
+ text: payload.text,
791
+ bridgeText: buildVoiceBridgePromptText(speakerName, text),
792
+ historyBridgeText: buildVoiceBridgeText(speakerName, text),
793
+ ...(allAttachments.length > 0 ? { attachments: allAttachments } : {}),
794
+ ...(passthroughAttachments.length > 0
795
+ ? { bridgeAttachments: passthroughAttachments }
796
+ : {}),
797
+ };
798
+ }
799
+
669
800
  private listParticipants(
670
801
  session: ProviderSessionState,
671
802
  ): PrivateClawParticipant[] {
@@ -810,6 +941,7 @@ export class PrivateClawProvider {
810
941
  params: {
811
942
  text: string;
812
943
  replyTo?: string;
944
+ pending?: boolean;
813
945
  attachments?: PrivateClawAttachment[];
814
946
  messageId?: string;
815
947
  sentAt?: string;
@@ -836,10 +968,30 @@ export class PrivateClawProvider {
836
968
  text: params.text,
837
969
  sentAt,
838
970
  ...(params.replyTo ? { replyTo: params.replyTo } : {}),
971
+ ...(params.pending ? { pending: true } : {}),
839
972
  ...(params.attachments ? { attachments: params.attachments } : {}),
840
973
  }, params.targetAppId);
841
974
  }
842
975
 
976
+ private async sendPendingAssistantStatus(
977
+ sessionId: string,
978
+ params: {
979
+ replyTo: string;
980
+ targetAppId?: string;
981
+ sentAt?: string;
982
+ },
983
+ ): Promise<void> {
984
+ await this.sendAssistantMessage(sessionId, {
985
+ text: "",
986
+ replyTo: params.replyTo,
987
+ pending: true,
988
+ messageId: buildPendingAssistantMessageId(params.replyTo),
989
+ storeHistory: false,
990
+ ...(params.sentAt ? { sentAt: params.sentAt } : {}),
991
+ ...(params.targetAppId ? { targetAppId: params.targetAppId } : {}),
992
+ });
993
+ }
994
+
843
995
  async sendSystemMessage(
844
996
  sessionId: string,
845
997
  message: string,
@@ -931,6 +1083,7 @@ export class PrivateClawProvider {
931
1083
  clientMessageId: string;
932
1084
  sentAt?: string;
933
1085
  attachments?: PrivateClawAttachment[];
1086
+ bridgeText?: string;
934
1087
  targetAppId?: string;
935
1088
  storeHistory?: boolean;
936
1089
  },
@@ -938,14 +1091,14 @@ export class PrivateClawProvider {
938
1091
  const sentAt = params.sentAt ?? nowIso();
939
1092
  const session = this.requireSession(sessionId);
940
1093
  if (params.storeHistory !== false) {
941
- session.history.push({
1094
+ this.storeUserMessageTurn(session, {
942
1095
  messageId: params.clientMessageId,
943
- role: "user",
944
1096
  text: params.text,
945
1097
  sentAt,
946
1098
  appId: params.senderAppId,
947
1099
  participantLabel: params.senderDisplayName,
948
1100
  ...(params.attachments ? { attachments: params.attachments } : {}),
1101
+ ...(params.bridgeText ? { bridgeText: params.bridgeText } : {}),
949
1102
  });
950
1103
  }
951
1104
  await this.sendPayload(sessionId, {
@@ -960,6 +1113,97 @@ export class PrivateClawProvider {
960
1113
  }, params.targetAppId);
961
1114
  }
962
1115
 
1116
+ private async sendParticipantMessageToGroupParticipants(
1117
+ sessionId: string,
1118
+ params: {
1119
+ text: string;
1120
+ senderAppId: string;
1121
+ senderDisplayName: string;
1122
+ clientMessageId: string;
1123
+ sentAt?: string;
1124
+ attachments?: PrivateClawAttachment[];
1125
+ excludeAppId?: string;
1126
+ bridgeText?: string;
1127
+ storeHistory?: boolean;
1128
+ },
1129
+ ): Promise<void> {
1130
+ const session = this.requireSession(sessionId);
1131
+ const sentAt = params.sentAt ?? nowIso();
1132
+ if (params.storeHistory !== false) {
1133
+ this.storeUserMessageTurn(session, {
1134
+ messageId: params.clientMessageId,
1135
+ text: params.text,
1136
+ sentAt,
1137
+ appId: params.senderAppId,
1138
+ participantLabel: params.senderDisplayName,
1139
+ ...(params.attachments ? { attachments: params.attachments } : {}),
1140
+ ...(params.bridgeText ? { bridgeText: params.bridgeText } : {}),
1141
+ });
1142
+ }
1143
+ const targetAppIds = [...session.participants.keys()].filter(
1144
+ (appId) => appId !== params.excludeAppId,
1145
+ );
1146
+ if (targetAppIds.length === 0) {
1147
+ return;
1148
+ }
1149
+ await Promise.all(
1150
+ targetAppIds.map((targetAppId) =>
1151
+ this.sendPayload(
1152
+ sessionId,
1153
+ {
1154
+ kind: "participant_message",
1155
+ messageId: params.clientMessageId,
1156
+ senderAppId: params.senderAppId,
1157
+ senderDisplayName: params.senderDisplayName,
1158
+ text: params.text,
1159
+ clientMessageId: params.clientMessageId,
1160
+ sentAt,
1161
+ ...(params.attachments ? { attachments: params.attachments } : {}),
1162
+ },
1163
+ targetAppId,
1164
+ ),
1165
+ ),
1166
+ );
1167
+ }
1168
+
1169
+ private storeUserMessageTurn(
1170
+ session: ProviderSessionState,
1171
+ params: {
1172
+ messageId: string;
1173
+ text: string;
1174
+ sentAt: string;
1175
+ bridgeText?: string;
1176
+ appId?: string;
1177
+ participantLabel?: string;
1178
+ attachments?: PrivateClawAttachment[];
1179
+ },
1180
+ ): void {
1181
+ session.history.push({
1182
+ messageId: params.messageId,
1183
+ role: "user",
1184
+ text: params.text,
1185
+ sentAt: params.sentAt,
1186
+ ...(params.bridgeText ? { bridgeText: params.bridgeText } : {}),
1187
+ ...(params.appId ? { appId: params.appId } : {}),
1188
+ ...(params.participantLabel ? { participantLabel: params.participantLabel } : {}),
1189
+ ...(params.attachments ? { attachments: params.attachments } : {}),
1190
+ });
1191
+ }
1192
+
1193
+ private updateStoredUserBridgeText(
1194
+ session: ProviderSessionState,
1195
+ messageId: string,
1196
+ bridgeText: string,
1197
+ ): void {
1198
+ for (let index = session.history.length - 1; index >= 0; index -= 1) {
1199
+ const turn = session.history[index];
1200
+ if (turn?.role === "user" && turn.messageId === messageId) {
1201
+ turn.bridgeText = bridgeText;
1202
+ return;
1203
+ }
1204
+ }
1205
+ }
1206
+
963
1207
  private async sendWelcomeMessage(
964
1208
  sessionId: string,
965
1209
  targetAppId?: string,
@@ -1449,48 +1693,160 @@ export class PrivateClawProvider {
1449
1693
  return;
1450
1694
  }
1451
1695
 
1452
- if (session.groupMode) {
1453
- if (!participant) {
1454
- await this.sendSystemMessage(
1455
- sessionId,
1456
- buildMissingParticipantIdentityMessage(),
1457
- "error",
1696
+ if (session.groupMode && !participant) {
1697
+ await this.sendSystemMessage(
1698
+ sessionId,
1699
+ buildMissingParticipantIdentityMessage(),
1700
+ "error",
1701
+ payload.clientMessageId,
1702
+ );
1703
+ return;
1704
+ }
1705
+
1706
+ const supportsVoiceTranscription = Boolean(
1707
+ this.options.bridge.transcribeAudioAttachments,
1708
+ );
1709
+ const containsAudioAttachment = hasAudioAttachments(payload.attachments);
1710
+ const shouldHandleVoiceAsynchronously =
1711
+ containsAudioAttachment && supportsVoiceTranscription;
1712
+ const voiceFeedbackParams =
1713
+ shouldHandleVoiceAsynchronously && participant
1714
+ ? {
1715
+ targetAppId: participant.appId,
1716
+ storeHistory: false,
1717
+ }
1718
+ : undefined;
1719
+
1720
+ if (shouldHandleVoiceAsynchronously) {
1721
+ if (session.groupMode) {
1722
+ this.storeUserMessageTurn(session, {
1723
+ messageId: payload.clientMessageId,
1724
+ text: payload.text,
1725
+ sentAt: payload.sentAt,
1726
+ appId: participant!.appId,
1727
+ participantLabel: participant!.displayName,
1728
+ ...(payload.attachments ? { attachments: payload.attachments } : {}),
1729
+ });
1730
+ await this.sendParticipantMessageToGroupParticipants(sessionId, {
1731
+ text: payload.text,
1732
+ senderAppId: participant!.appId,
1733
+ senderDisplayName: participant!.displayName,
1734
+ clientMessageId: payload.clientMessageId,
1735
+ sentAt: payload.sentAt,
1736
+ ...(payload.attachments ? { attachments: payload.attachments } : {}),
1737
+ excludeAppId: participant!.appId,
1738
+ storeHistory: false,
1739
+ });
1740
+ } else {
1741
+ this.storeUserMessageTurn(session, {
1742
+ messageId: payload.clientMessageId,
1743
+ text: payload.text,
1744
+ sentAt: payload.sentAt,
1745
+ ...(payload.attachments ? { attachments: payload.attachments } : {}),
1746
+ });
1747
+ }
1748
+ }
1749
+
1750
+ if (session.groupMode && session.botMuted) {
1751
+ if (!shouldHandleVoiceAsynchronously) {
1752
+ await this.sendParticipantMessage(sessionId, {
1753
+ text: payload.text,
1754
+ senderAppId: participant!.appId,
1755
+ senderDisplayName: participant!.displayName,
1756
+ clientMessageId: payload.clientMessageId,
1757
+ sentAt: payload.sentAt,
1758
+ ...(payload.attachments ? { attachments: payload.attachments } : {}),
1759
+ });
1760
+ }
1761
+ return;
1762
+ }
1763
+
1764
+ if (voiceFeedbackParams) {
1765
+ await this.sendSystemMessage(
1766
+ sessionId,
1767
+ buildVoiceReceiptMessage(),
1768
+ "info",
1769
+ undefined,
1770
+ voiceFeedbackParams,
1771
+ );
1772
+ await this.sendPendingAssistantStatus(sessionId, {
1773
+ replyTo: payload.clientMessageId,
1774
+ targetAppId: voiceFeedbackParams.targetAppId,
1775
+ sentAt: payload.sentAt,
1776
+ });
1777
+ }
1778
+
1779
+ let preparedMessage: PreparedUserMessage;
1780
+ try {
1781
+ preparedMessage = await this.prepareUserMessage(
1782
+ session,
1783
+ payload,
1784
+ participant,
1785
+ );
1786
+ } catch (error) {
1787
+ await this.sendSystemMessage(
1788
+ sessionId,
1789
+ buildBridgeErrorMessage(
1790
+ error instanceof Error ? error.message : String(error),
1791
+ ),
1792
+ "error",
1793
+ payload.clientMessageId,
1794
+ voiceFeedbackParams,
1795
+ );
1796
+ return;
1797
+ }
1798
+
1799
+ if (shouldHandleVoiceAsynchronously) {
1800
+ if (preparedMessage.historyBridgeText) {
1801
+ this.updateStoredUserBridgeText(
1802
+ session,
1458
1803
  payload.clientMessageId,
1804
+ preparedMessage.historyBridgeText,
1459
1805
  );
1460
- return;
1461
1806
  }
1807
+ } else if (session.groupMode) {
1462
1808
  await this.sendParticipantMessage(sessionId, {
1463
- text: payload.text,
1464
- senderAppId: participant.appId,
1465
- senderDisplayName: participant.displayName,
1809
+ text: preparedMessage.text,
1810
+ senderAppId: participant!.appId,
1811
+ senderDisplayName: participant!.displayName,
1466
1812
  clientMessageId: payload.clientMessageId,
1467
1813
  sentAt: payload.sentAt,
1468
- ...(payload.attachments ? { attachments: payload.attachments } : {}),
1814
+ ...(preparedMessage.attachments
1815
+ ? { attachments: preparedMessage.attachments }
1816
+ : {}),
1817
+ ...(preparedMessage.historyBridgeText
1818
+ ? { bridgeText: preparedMessage.historyBridgeText }
1819
+ : {}),
1469
1820
  });
1470
1821
  } else {
1471
- session.history.push({
1822
+ this.storeUserMessageTurn(session, {
1472
1823
  messageId: payload.clientMessageId,
1473
- role: "user",
1474
- text: payload.text,
1824
+ text: preparedMessage.text,
1475
1825
  sentAt: payload.sentAt,
1476
- ...(payload.attachments ? { attachments: payload.attachments } : {}),
1826
+ ...(preparedMessage.historyBridgeText
1827
+ ? { bridgeText: preparedMessage.historyBridgeText }
1828
+ : {}),
1829
+ ...(preparedMessage.attachments
1830
+ ? { attachments: preparedMessage.attachments }
1831
+ : {}),
1477
1832
  });
1478
1833
  }
1479
1834
 
1480
- if (session.groupMode && session.botMuted) {
1481
- return;
1482
- }
1483
-
1484
1835
  try {
1485
1836
  const bridgeMessage =
1486
- session.groupMode && participant
1487
- ? `${participant.displayName}: ${payload.text}`
1488
- : payload.text;
1837
+ preparedMessage.bridgeText ??
1838
+ (session.groupMode && participant
1839
+ ? `${participant.displayName}: ${preparedMessage.text}`
1840
+ : preparedMessage.text);
1489
1841
  const bridgeResponse = await this.options.bridge.handleUserMessage({
1490
1842
  sessionId,
1491
1843
  invite: session.invite,
1492
1844
  message: bridgeMessage,
1493
- ...(payload.attachments ? { attachments: payload.attachments } : {}),
1845
+ ...(preparedMessage.bridgeAttachments
1846
+ ? { attachments: preparedMessage.bridgeAttachments }
1847
+ : preparedMessage.attachments
1848
+ ? { attachments: preparedMessage.attachments }
1849
+ : {}),
1494
1850
  history: this.buildBridgeHistory(session),
1495
1851
  });
1496
1852
 
@@ -1517,6 +1873,7 @@ export class PrivateClawProvider {
1517
1873
  ),
1518
1874
  "error",
1519
1875
  payload.clientMessageId,
1876
+ voiceFeedbackParams,
1520
1877
  );
1521
1878
  }
1522
1879
  return;