@privateclaw/privateclaw 0.1.13 → 0.1.15

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}`,
@@ -536,6 +613,36 @@ export class PrivateClawProvider {
536
613
  return [...this.sessions.values()].map(toManagedSessionSnapshot);
537
614
  }
538
615
 
616
+ async getSessionQrBundle(
617
+ sessionId: string,
618
+ params?: { notifyParticipants?: boolean },
619
+ ): Promise<PrivateClawInviteBundle> {
620
+ const session = this.requireSession(sessionId);
621
+ const bundle = await this.buildInviteBundleForInvite(session.invite);
622
+
623
+ if (params?.notifyParticipants) {
624
+ const qrAttachment = await this.buildSessionQrAttachmentFromBundle(bundle);
625
+ await this.sendAssistantMessage(sessionId, {
626
+ text: buildSessionQrMessage(session),
627
+ attachments: [qrAttachment],
628
+ storeHistory: false,
629
+ });
630
+ }
631
+
632
+ return bundle;
633
+ }
634
+
635
+ async closeManagedSession(
636
+ sessionId: string,
637
+ reason = "operator_terminated",
638
+ ): Promise<PrivateClawManagedSession> {
639
+ const session = this.requireSession(sessionId);
640
+ const snapshot = toManagedSessionSnapshot(session);
641
+ await this.relayClient.closeSession(sessionId, reason);
642
+ this.deleteSession(sessionId);
643
+ return snapshot;
644
+ }
645
+
539
646
  exportHandoffState(): PrivateClawProviderHandoffState {
540
647
  return {
541
648
  providerId: this.relayClient.getProviderId(),
@@ -636,6 +743,60 @@ export class PrivateClawProvider {
636
743
  return session.history.map(formatBridgeHistoryTurn);
637
744
  }
638
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
+
639
800
  private listParticipants(
640
801
  session: ProviderSessionState,
641
802
  ): PrivateClawParticipant[] {
@@ -780,6 +941,7 @@ export class PrivateClawProvider {
780
941
  params: {
781
942
  text: string;
782
943
  replyTo?: string;
944
+ pending?: boolean;
783
945
  attachments?: PrivateClawAttachment[];
784
946
  messageId?: string;
785
947
  sentAt?: string;
@@ -806,10 +968,30 @@ export class PrivateClawProvider {
806
968
  text: params.text,
807
969
  sentAt,
808
970
  ...(params.replyTo ? { replyTo: params.replyTo } : {}),
971
+ ...(params.pending ? { pending: true } : {}),
809
972
  ...(params.attachments ? { attachments: params.attachments } : {}),
810
973
  }, params.targetAppId);
811
974
  }
812
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
+
813
995
  async sendSystemMessage(
814
996
  sessionId: string,
815
997
  message: string,
@@ -901,6 +1083,7 @@ export class PrivateClawProvider {
901
1083
  clientMessageId: string;
902
1084
  sentAt?: string;
903
1085
  attachments?: PrivateClawAttachment[];
1086
+ bridgeText?: string;
904
1087
  targetAppId?: string;
905
1088
  storeHistory?: boolean;
906
1089
  },
@@ -908,14 +1091,14 @@ export class PrivateClawProvider {
908
1091
  const sentAt = params.sentAt ?? nowIso();
909
1092
  const session = this.requireSession(sessionId);
910
1093
  if (params.storeHistory !== false) {
911
- session.history.push({
1094
+ this.storeUserMessageTurn(session, {
912
1095
  messageId: params.clientMessageId,
913
- role: "user",
914
1096
  text: params.text,
915
1097
  sentAt,
916
1098
  appId: params.senderAppId,
917
1099
  participantLabel: params.senderDisplayName,
918
1100
  ...(params.attachments ? { attachments: params.attachments } : {}),
1101
+ ...(params.bridgeText ? { bridgeText: params.bridgeText } : {}),
919
1102
  });
920
1103
  }
921
1104
  await this.sendPayload(sessionId, {
@@ -930,6 +1113,97 @@ export class PrivateClawProvider {
930
1113
  }, params.targetAppId);
931
1114
  }
932
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
+
933
1207
  private async sendWelcomeMessage(
934
1208
  sessionId: string,
935
1209
  targetAppId?: string,
@@ -1419,48 +1693,160 @@ export class PrivateClawProvider {
1419
1693
  return;
1420
1694
  }
1421
1695
 
1422
- if (session.groupMode) {
1423
- if (!participant) {
1424
- await this.sendSystemMessage(
1425
- sessionId,
1426
- buildMissingParticipantIdentityMessage(),
1427
- "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,
1428
1803
  payload.clientMessageId,
1804
+ preparedMessage.historyBridgeText,
1429
1805
  );
1430
- return;
1431
1806
  }
1807
+ } else if (session.groupMode) {
1432
1808
  await this.sendParticipantMessage(sessionId, {
1433
- text: payload.text,
1434
- senderAppId: participant.appId,
1435
- senderDisplayName: participant.displayName,
1809
+ text: preparedMessage.text,
1810
+ senderAppId: participant!.appId,
1811
+ senderDisplayName: participant!.displayName,
1436
1812
  clientMessageId: payload.clientMessageId,
1437
1813
  sentAt: payload.sentAt,
1438
- ...(payload.attachments ? { attachments: payload.attachments } : {}),
1814
+ ...(preparedMessage.attachments
1815
+ ? { attachments: preparedMessage.attachments }
1816
+ : {}),
1817
+ ...(preparedMessage.historyBridgeText
1818
+ ? { bridgeText: preparedMessage.historyBridgeText }
1819
+ : {}),
1439
1820
  });
1440
1821
  } else {
1441
- session.history.push({
1822
+ this.storeUserMessageTurn(session, {
1442
1823
  messageId: payload.clientMessageId,
1443
- role: "user",
1444
- text: payload.text,
1824
+ text: preparedMessage.text,
1445
1825
  sentAt: payload.sentAt,
1446
- ...(payload.attachments ? { attachments: payload.attachments } : {}),
1826
+ ...(preparedMessage.historyBridgeText
1827
+ ? { bridgeText: preparedMessage.historyBridgeText }
1828
+ : {}),
1829
+ ...(preparedMessage.attachments
1830
+ ? { attachments: preparedMessage.attachments }
1831
+ : {}),
1447
1832
  });
1448
1833
  }
1449
1834
 
1450
- if (session.groupMode && session.botMuted) {
1451
- return;
1452
- }
1453
-
1454
1835
  try {
1455
1836
  const bridgeMessage =
1456
- session.groupMode && participant
1457
- ? `${participant.displayName}: ${payload.text}`
1458
- : payload.text;
1837
+ preparedMessage.bridgeText ??
1838
+ (session.groupMode && participant
1839
+ ? `${participant.displayName}: ${preparedMessage.text}`
1840
+ : preparedMessage.text);
1459
1841
  const bridgeResponse = await this.options.bridge.handleUserMessage({
1460
1842
  sessionId,
1461
1843
  invite: session.invite,
1462
1844
  message: bridgeMessage,
1463
- ...(payload.attachments ? { attachments: payload.attachments } : {}),
1845
+ ...(preparedMessage.bridgeAttachments
1846
+ ? { attachments: preparedMessage.bridgeAttachments }
1847
+ : preparedMessage.attachments
1848
+ ? { attachments: preparedMessage.attachments }
1849
+ : {}),
1464
1850
  history: this.buildBridgeHistory(session),
1465
1851
  });
1466
1852
 
@@ -1487,6 +1873,7 @@ export class PrivateClawProvider {
1487
1873
  ),
1488
1874
  "error",
1489
1875
  payload.clientMessageId,
1876
+ voiceFeedbackParams,
1490
1877
  );
1491
1878
  }
1492
1879
  return;
@@ -1612,8 +1999,13 @@ export class PrivateClawProvider {
1612
1999
  }
1613
2000
 
1614
2001
  private async buildSessionQrAttachment(sessionId: string): Promise<PrivateClawAttachment> {
1615
- const session = this.requireSession(sessionId);
1616
- const bundle = await this.buildInviteBundleForInvite(session.invite);
2002
+ const bundle = await this.getSessionQrBundle(sessionId);
2003
+ return this.buildSessionQrAttachmentFromBundle(bundle);
2004
+ }
2005
+
2006
+ private async buildSessionQrAttachmentFromBundle(
2007
+ bundle: PrivateClawInviteBundle,
2008
+ ): Promise<PrivateClawAttachment> {
1617
2009
  const pngBuffer = await QRCode.toBuffer(bundle.inviteUri, {
1618
2010
  type: "png",
1619
2011
  errorCorrectionLevel: PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL,