@privateclaw/privateclaw 0.1.24 → 0.1.25

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
@@ -7,6 +7,8 @@ import { buildInviteAnnouncementText, formatBilingualInline, formatBilingualText
7
7
  export const DEFAULT_SESSION_TTL_MS = 24 * 60 * 60 * 1000;
8
8
  const RENEW_SESSION_TTL_MS = DEFAULT_SESSION_TTL_MS;
9
9
  const SESSION_RENEWAL_REMINDER_WINDOW_MS = 30 * 60 * 1000;
10
+ const BOT_MODE_SILENT_JOIN_DELAY_MS = 10 * 60 * 1000;
11
+ const BOT_MODE_IDLE_DELAY_MS = 20 * 60 * 1000;
10
12
  const PARTICIPANT_LABEL_MAX_CHARS = 12;
11
13
  const PARTICIPANT_FALLBACK_PREFIXES = [
12
14
  "流萤",
@@ -190,6 +192,15 @@ function toProviderSessionHandoff(session) {
190
192
  ...(session.renewalReminderSentAt
191
193
  ? { renewalReminderSentAt: session.renewalReminderSentAt }
192
194
  : {}),
195
+ ...(session.lastGroupActivityAt
196
+ ? { lastGroupActivityAt: session.lastGroupActivityAt }
197
+ : {}),
198
+ ...(session.botModeIdleAnchorAt
199
+ ? { botModeIdleAnchorAt: session.botModeIdleAnchorAt }
200
+ : {}),
201
+ ...(session.botModeLastIdlePromptAt
202
+ ? { botModeLastIdlePromptAt: session.botModeLastIdlePromptAt }
203
+ : {}),
193
204
  };
194
205
  }
195
206
  function fromProviderSessionHandoff(snapshot) {
@@ -208,8 +219,22 @@ function fromProviderSessionHandoff(snapshot) {
208
219
  ...(snapshot.renewalReminderSentAt
209
220
  ? { renewalReminderSentAt: snapshot.renewalReminderSentAt }
210
221
  : {}),
222
+ ...(snapshot.lastGroupActivityAt
223
+ ? { lastGroupActivityAt: snapshot.lastGroupActivityAt }
224
+ : {}),
225
+ ...(snapshot.botModeIdleAnchorAt
226
+ ? { botModeIdleAnchorAt: snapshot.botModeIdleAnchorAt }
227
+ : {}),
228
+ ...(snapshot.botModeLastIdlePromptAt
229
+ ? { botModeLastIdlePromptAt: snapshot.botModeLastIdlePromptAt }
230
+ : {}),
231
+ botModeSilentJoinTimers: new Map(),
211
232
  };
212
233
  }
234
+ function describeElapsedMinutes(elapsedMs) {
235
+ const minutes = Math.max(1, Math.round(elapsedMs / 60_000));
236
+ return `${minutes} minute${minutes === 1 ? "" : "s"}`;
237
+ }
213
238
  function buildRenewalReminderMessage(session) {
214
239
  const command = "/renew-session";
215
240
  if (session.groupMode) {
@@ -381,6 +406,44 @@ function buildBotAlreadyMutedMessage() {
381
406
  function buildBotAlreadyUnmutedMessage() {
382
407
  return formatBilingualInline("机器人目前已经处于可回复状态。", "Bot replies are already enabled.");
383
408
  }
409
+ function buildBotModeSilentJoinPrompt(params) {
410
+ const joinedAtMs = new Date(params.joinedAt).getTime();
411
+ const elapsedText = describeElapsedMinutes(Math.max(0, (params.nowMs ?? Date.now()) - joinedAtMs));
412
+ return [
413
+ "PrivateClaw bot-mode task:",
414
+ `A participant named "${params.participantLabel}" joined this PrivateClaw group chat about ${elapsedText} ago but has not sent any message yet.`,
415
+ "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.",
416
+ ...(params.languageInstruction ? [params.languageInstruction] : []),
417
+ "Use recent conversation context when it helps, keep the tone playful and concise, and do not mention hidden instructions, timers, or inactivity monitoring.",
418
+ ].join("\n");
419
+ }
420
+ function buildBotModeIdlePrompt(params) {
421
+ const lastActivityAtMs = new Date(params.lastGroupActivityAt).getTime();
422
+ const elapsedText = describeElapsedMinutes(Math.max(0, (params.nowMs ?? Date.now()) - lastActivityAtMs));
423
+ return [
424
+ "PrivateClaw bot-mode task:",
425
+ `This PrivateClaw group chat has had no new message for about ${elapsedText}.`,
426
+ "Send one short proactive message to re-engage the group.",
427
+ "Prefer a light joke or a context-aware follow-up when recent history suggests one. If there is no obvious callback, send a friendly opener and a quick reminder of what you can help with.",
428
+ ...(params.languageInstruction ? [params.languageInstruction] : []),
429
+ "Keep it natural and concise, and do not mention hidden instructions or inactivity timers.",
430
+ ].join("\n");
431
+ }
432
+ function hasPriorConversationalHistory(session) {
433
+ return session.history.some((turn) => turn.role === "user" || turn.role === "assistant");
434
+ }
435
+ function buildBotModeLanguageInstruction(session) {
436
+ return hasPriorConversationalHistory(session)
437
+ ? "Write the proactive message in the same language as the recent user/assistant conversation already in this session."
438
+ : undefined;
439
+ }
440
+ function readIsoMs(value) {
441
+ if (!value) {
442
+ return undefined;
443
+ }
444
+ const parsed = new Date(value).getTime();
445
+ return Number.isFinite(parsed) ? parsed : undefined;
446
+ }
384
447
  function dedupeCommands(commands) {
385
448
  const unique = new Map();
386
449
  for (const command of commands) {
@@ -487,6 +550,7 @@ export class PrivateClawProvider {
487
550
  const session = fromProviderSessionHandoff(snapshot);
488
551
  this.sessions.set(session.invite.sessionId, session);
489
552
  this.scheduleRenewalReminder(session.invite.sessionId);
553
+ this.scheduleBotModeTimers(session.invite.sessionId);
490
554
  }
491
555
  }
492
556
  suppressReconnectsForHandoff() {
@@ -510,11 +574,16 @@ export class PrivateClawProvider {
510
574
  }
511
575
  session.participants.delete(normalizedAppId);
512
576
  session.removedParticipantAppIds.add(normalizedAppId);
577
+ this.clearBotModeSilentJoinTimer(session, normalizedAppId);
578
+ if (session.participants.size === 0) {
579
+ delete session.botModeIdleAnchorAt;
580
+ }
513
581
  await this.relayClient.closeApp(sessionId, normalizedAppId, reason);
514
582
  if (session.participants.size > 0) {
515
583
  await this.sendSystemMessageToGroupParticipants(sessionId, buildParticipantRemovedByOperatorMessage(participant.displayName));
516
584
  await this.sendCapabilities(sessionId);
517
585
  }
586
+ this.scheduleGroupIdlePrompt(sessionId);
518
587
  return toParticipantSnapshot(participant);
519
588
  }
520
589
  buildSessionAppUrl(sessionId) {
@@ -538,6 +607,7 @@ export class PrivateClawProvider {
538
607
  clearTimeout(session.renewalReminderTimer);
539
608
  delete session.renewalReminderTimer;
540
609
  }
610
+ this.clearBotModeTimers(session);
541
611
  this.sessions.delete(sessionId);
542
612
  return session;
543
613
  }
@@ -650,6 +720,245 @@ export class PrivateClawProvider {
650
720
  });
651
721
  }, delayMs);
652
722
  }
723
+ isBotModeEnabled(session) {
724
+ return this.options.botMode === true && session.groupMode;
725
+ }
726
+ getBotModeSilentJoinDelayMs() {
727
+ return this.options.botModeSilentJoinDelayMs ?? BOT_MODE_SILENT_JOIN_DELAY_MS;
728
+ }
729
+ getBotModeIdleDelayMs() {
730
+ return this.options.botModeIdleDelayMs ?? BOT_MODE_IDLE_DELAY_MS;
731
+ }
732
+ clearBotModeSilentJoinTimer(session, appId) {
733
+ const timer = session.botModeSilentJoinTimers?.get(appId);
734
+ if (timer) {
735
+ clearTimeout(timer);
736
+ }
737
+ session.botModeSilentJoinTimers?.delete(appId);
738
+ }
739
+ clearBotModeIdleTimer(session) {
740
+ if (session.botModeIdleTimer) {
741
+ clearTimeout(session.botModeIdleTimer);
742
+ delete session.botModeIdleTimer;
743
+ }
744
+ }
745
+ clearBotModeTimers(session) {
746
+ this.clearBotModeIdleTimer(session);
747
+ for (const appId of session.botModeSilentJoinTimers?.keys() ?? []) {
748
+ this.clearBotModeSilentJoinTimer(session, appId);
749
+ }
750
+ delete session.botModeSilentJoinTimers;
751
+ }
752
+ ensureGroupIdleAnchor(session, fallbackSentAt) {
753
+ if (!session.groupMode || session.botModeIdleAnchorAt || session.lastGroupActivityAt) {
754
+ return;
755
+ }
756
+ const participantJoinedAtMs = [...session.participants.values()]
757
+ .map((participant) => ({
758
+ joinedAt: participant.joinedAt,
759
+ joinedAtMs: readIsoMs(participant.joinedAt),
760
+ }))
761
+ .filter((item) => typeof item.joinedAtMs === "number")
762
+ .sort((left, right) => left.joinedAtMs - right.joinedAtMs)[0]?.joinedAt;
763
+ const nextAnchor = participantJoinedAtMs ?? fallbackSentAt;
764
+ if (nextAnchor) {
765
+ session.botModeIdleAnchorAt = nextAnchor;
766
+ }
767
+ }
768
+ getGroupIdleScheduleAnchorMs(session, lastActivityMsOverride) {
769
+ this.ensureGroupIdleAnchor(session);
770
+ const anchorMsCandidates = [
771
+ typeof lastActivityMsOverride === "number" ? lastActivityMsOverride : undefined,
772
+ readIsoMs(session.lastGroupActivityAt),
773
+ readIsoMs(session.botModeLastIdlePromptAt),
774
+ readIsoMs(session.botModeIdleAnchorAt),
775
+ ].filter((value) => typeof value === "number");
776
+ return anchorMsCandidates.length > 0 ? Math.max(...anchorMsCandidates) : Date.now();
777
+ }
778
+ noteGroupActivity(sessionId, sentAt) {
779
+ const session = this.sessions.get(sessionId);
780
+ if (!session || !session.groupMode) {
781
+ return;
782
+ }
783
+ delete session.botModeLastIdlePromptAt;
784
+ session.lastGroupActivityAt = sentAt;
785
+ if (this.isBotModeEnabled(session) && !session.botMuted) {
786
+ this.scheduleGroupIdlePrompt(sessionId);
787
+ return;
788
+ }
789
+ this.clearBotModeIdleTimer(session);
790
+ }
791
+ markParticipantSpoke(sessionId, appId, sentAt) {
792
+ const session = this.sessions.get(sessionId);
793
+ if (!session) {
794
+ return;
795
+ }
796
+ const participant = session.participants.get(appId);
797
+ if (!participant) {
798
+ return;
799
+ }
800
+ participant.lastSeenAt = sentAt;
801
+ participant.lastUserMessageAt = sentAt;
802
+ this.clearBotModeSilentJoinTimer(session, appId);
803
+ this.noteGroupActivity(sessionId, sentAt);
804
+ }
805
+ scheduleBotModeTimers(sessionId) {
806
+ const session = this.sessions.get(sessionId);
807
+ if (!session) {
808
+ return;
809
+ }
810
+ if (!session.botModeSilentJoinTimers) {
811
+ session.botModeSilentJoinTimers = new Map();
812
+ }
813
+ if (!this.isBotModeEnabled(session) || session.botMuted) {
814
+ this.clearBotModeTimers(session);
815
+ return;
816
+ }
817
+ this.ensureGroupIdleAnchor(session);
818
+ this.scheduleGroupIdlePrompt(sessionId);
819
+ for (const appId of session.participants.keys()) {
820
+ this.scheduleSilentJoinPrompt(sessionId, appId);
821
+ }
822
+ }
823
+ scheduleSilentJoinPrompt(sessionId, appId) {
824
+ const session = this.sessions.get(sessionId);
825
+ if (!session) {
826
+ return;
827
+ }
828
+ if (!session.botModeSilentJoinTimers) {
829
+ session.botModeSilentJoinTimers = new Map();
830
+ }
831
+ this.clearBotModeSilentJoinTimer(session, appId);
832
+ if (!this.isBotModeEnabled(session) || session.botMuted) {
833
+ return;
834
+ }
835
+ const participant = session.participants.get(appId);
836
+ if (!participant ||
837
+ participant.lastUserMessageAt ||
838
+ participant.botModeSilentJoinPromptSentAt) {
839
+ return;
840
+ }
841
+ const joinedAtMsRaw = new Date(participant.joinedAt).getTime();
842
+ const joinedAtMs = Number.isFinite(joinedAtMsRaw) ? joinedAtMsRaw : Date.now();
843
+ const delayMs = Math.max(0, joinedAtMs + this.getBotModeSilentJoinDelayMs() - Date.now());
844
+ session.botModeSilentJoinTimers.set(appId, setTimeout(() => {
845
+ void this.handleSilentJoinPrompt(sessionId, appId, joinedAtMs).catch((error) => {
846
+ this.options.onLog?.(`[provider] bot mode silent join prompt failed for ${sessionId}/${appId}: ${error instanceof Error ? error.message : String(error)}`);
847
+ });
848
+ }, delayMs));
849
+ }
850
+ scheduleGroupIdlePrompt(sessionId, lastActivityMsOverride) {
851
+ const session = this.sessions.get(sessionId);
852
+ if (!session) {
853
+ return;
854
+ }
855
+ this.clearBotModeIdleTimer(session);
856
+ if (!this.isBotModeEnabled(session) ||
857
+ session.botMuted ||
858
+ session.participants.size === 0) {
859
+ return;
860
+ }
861
+ const lastActivityMs = this.getGroupIdleScheduleAnchorMs(session, lastActivityMsOverride);
862
+ const delayMs = Math.max(0, lastActivityMs + this.getBotModeIdleDelayMs() - Date.now());
863
+ session.botModeIdleTimer = setTimeout(() => {
864
+ void this.handleGroupIdlePrompt(sessionId, lastActivityMs).catch((error) => {
865
+ this.options.onLog?.(`[provider] bot mode idle prompt failed for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
866
+ });
867
+ }, delayMs);
868
+ }
869
+ async handleSilentJoinPrompt(sessionId, appId, joinedAtMs) {
870
+ const session = this.sessions.get(sessionId);
871
+ if (!session) {
872
+ return;
873
+ }
874
+ this.clearBotModeSilentJoinTimer(session, appId);
875
+ const participant = session.participants.get(appId);
876
+ if (!participant ||
877
+ !this.isBotModeEnabled(session) ||
878
+ session.botMuted ||
879
+ participant.lastUserMessageAt ||
880
+ participant.botModeSilentJoinPromptSentAt) {
881
+ return;
882
+ }
883
+ const dueAtMs = joinedAtMs + this.getBotModeSilentJoinDelayMs();
884
+ if (Date.now() < dueAtMs) {
885
+ this.scheduleSilentJoinPrompt(sessionId, appId);
886
+ return;
887
+ }
888
+ const sentAt = nowIso();
889
+ const languageInstruction = buildBotModeLanguageInstruction(session);
890
+ const bridgeResponse = await this.options.bridge.handleUserMessage({
891
+ sessionId,
892
+ invite: session.invite,
893
+ message: buildBotModeSilentJoinPrompt({
894
+ participantLabel: participant.displayName,
895
+ joinedAt: participant.joinedAt,
896
+ ...(languageInstruction ? { languageInstruction } : {}),
897
+ }),
898
+ history: this.buildBridgeHistory(session),
899
+ });
900
+ for (const message of normalizeBridgeMessages(bridgeResponse)) {
901
+ await this.sendAssistantMessage(sessionId, {
902
+ text: message.text,
903
+ sentAt,
904
+ ...(message.attachments ? { attachments: message.attachments } : {}),
905
+ });
906
+ }
907
+ participant.botModeSilentJoinPromptSentAt = sentAt;
908
+ }
909
+ async handleGroupIdlePrompt(sessionId, lastActivityMs) {
910
+ const session = this.sessions.get(sessionId);
911
+ if (!session) {
912
+ return;
913
+ }
914
+ this.clearBotModeIdleTimer(session);
915
+ if (!this.isBotModeEnabled(session) ||
916
+ session.botMuted ||
917
+ session.participants.size === 0) {
918
+ return;
919
+ }
920
+ const currentActivityMs = this.getGroupIdleScheduleAnchorMs(session);
921
+ if (currentActivityMs > lastActivityMs) {
922
+ this.scheduleGroupIdlePrompt(sessionId, currentActivityMs);
923
+ return;
924
+ }
925
+ const dueAtMs = currentActivityMs + this.getBotModeIdleDelayMs();
926
+ if (Date.now() < dueAtMs) {
927
+ this.scheduleGroupIdlePrompt(sessionId, currentActivityMs);
928
+ return;
929
+ }
930
+ try {
931
+ const languageInstruction = buildBotModeLanguageInstruction(session);
932
+ const bridgeResponse = await this.options.bridge.handleUserMessage({
933
+ sessionId,
934
+ invite: session.invite,
935
+ message: buildBotModeIdlePrompt({
936
+ lastGroupActivityAt: session.lastGroupActivityAt ?? nowIso(),
937
+ ...(languageInstruction ? { languageInstruction } : {}),
938
+ }),
939
+ history: this.buildBridgeHistory(session),
940
+ });
941
+ const messages = normalizeBridgeMessages(bridgeResponse);
942
+ if (messages.length === 0) {
943
+ this.scheduleGroupIdlePrompt(sessionId, Date.now());
944
+ return;
945
+ }
946
+ const sentAt = nowIso();
947
+ for (const message of messages) {
948
+ await this.sendAssistantMessage(sessionId, {
949
+ text: message.text,
950
+ sentAt,
951
+ ...(message.attachments ? { attachments: message.attachments } : {}),
952
+ });
953
+ }
954
+ session.botModeLastIdlePromptAt = sentAt;
955
+ this.scheduleGroupIdlePrompt(sessionId);
956
+ }
957
+ catch (error) {
958
+ this.options.onLog?.(`[provider] bot mode idle prompt bridge error for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
959
+ this.scheduleGroupIdlePrompt(sessionId, Date.now());
960
+ }
961
+ }
653
962
  async sendRenewalReminder(sessionId) {
654
963
  const session = this.sessions.get(sessionId);
655
964
  if (!session) {
@@ -1110,6 +1419,9 @@ export class PrivateClawProvider {
1110
1419
  const wasRenewing = Boolean(session.pendingRenewal);
1111
1420
  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
1421
  session.state = "active";
1422
+ this.ensureGroupIdleAnchor(session, payload.sentAt);
1423
+ this.scheduleGroupIdlePrompt(sessionId);
1424
+ this.scheduleSilentJoinPrompt(sessionId, participant.appId);
1113
1425
  if (wasRenewing) {
1114
1426
  session.history.push({
1115
1427
  messageId: buildMessageId("system"),
@@ -1167,6 +1479,9 @@ export class PrivateClawProvider {
1167
1479
  (session.participants.size === 1
1168
1480
  ? [...session.participants.values()][0]
1169
1481
  : undefined);
1482
+ if (session.groupMode && participant) {
1483
+ this.markParticipantSpoke(sessionId, participant.appId, payload.sentAt);
1484
+ }
1170
1485
  const normalizedCommand = payload.text.trim().toLowerCase();
1171
1486
  const directBridgeSlashCommand = normalizeBridgeSlashCommandText(payload.text);
1172
1487
  const isRenewCommand = normalizedCommand === "/renew-session" ||
@@ -1276,6 +1591,12 @@ export class PrivateClawProvider {
1276
1591
  sentAt: payload.sentAt,
1277
1592
  messageId,
1278
1593
  });
1594
+ if (shouldMute) {
1595
+ this.clearBotModeTimers(session);
1596
+ }
1597
+ else {
1598
+ this.scheduleBotModeTimers(sessionId);
1599
+ }
1279
1600
  await this.sendCapabilities(sessionId);
1280
1601
  return;
1281
1602
  }
@@ -1489,12 +1810,17 @@ export class PrivateClawProvider {
1489
1810
  }
1490
1811
  const participant = session.participants.get(participantAppId);
1491
1812
  session.participants.delete(participantAppId);
1813
+ this.clearBotModeSilentJoinTimer(session, participantAppId);
1814
+ if (session.participants.size === 0) {
1815
+ delete session.botModeIdleAnchorAt;
1816
+ }
1492
1817
  if (participant && session.participants.size > 0) {
1493
1818
  await this.sendSystemMessageToGroupParticipants(sessionId, buildParticipantLeftMessage(participant.displayName), { sentAt: payload.sentAt });
1494
1819
  }
1495
1820
  if (session.participants.size > 0) {
1496
1821
  await this.sendCapabilities(sessionId);
1497
1822
  }
1823
+ this.scheduleGroupIdlePrompt(sessionId);
1498
1824
  return;
1499
1825
  }
1500
1826
  case "assistant_message":
@@ -1532,6 +1858,7 @@ export class PrivateClawProvider {
1532
1858
  participants: new Map(),
1533
1859
  removedParticipantAppIds: new Set(),
1534
1860
  state: "awaiting_hello",
1861
+ botModeSilentJoinTimers: new Map(),
1535
1862
  });
1536
1863
  this.scheduleRenewalReminder(sessionId);
1537
1864
  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}`);