@privateclaw/privateclaw 0.1.25 → 0.1.27

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.
@@ -8,11 +8,35 @@ import {
8
8
  } from "@privateclaw/protocol";
9
9
  import WebSocket from "ws";
10
10
  import { createRelayServer } from "../../../services/relay-server/src/relay-server.js";
11
+ import { BOT_MODE_IDLE_TOPICS } from "./bot-mode-topics.js";
11
12
  import { EchoBridge } from "./bridges/echo-bridge.js";
12
13
  import { DEFAULT_SESSION_TTL_MS, PrivateClawProvider } from "./provider.js";
13
14
 
14
15
  const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
15
16
 
17
+ function createDeferred<T>() {
18
+ let resolve!: (value: T | PromiseLike<T>) => void;
19
+ let reject!: (reason?: unknown) => void;
20
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
21
+ resolve = resolvePromise;
22
+ reject = rejectPromise;
23
+ });
24
+ return { promise, resolve, reject };
25
+ }
26
+
27
+ async function waitForCondition(
28
+ predicate: () => boolean,
29
+ timeoutMs = 500,
30
+ ): Promise<void> {
31
+ const startedAt = Date.now();
32
+ while (!predicate()) {
33
+ if (Date.now() - startedAt > timeoutMs) {
34
+ throw new Error(`condition not met within ${timeoutMs}ms`);
35
+ }
36
+ await new Promise((resolve) => setTimeout(resolve, 5));
37
+ }
38
+ }
39
+
16
40
  function waitForOpen(socket: WebSocket): Promise<void> {
17
41
  return new Promise((resolve, reject) => {
18
42
  socket.once("open", () => resolve());
@@ -248,6 +272,52 @@ class BotModeBridge {
248
272
  }
249
273
  }
250
274
 
275
+ class NoReplyThenJokeBridge {
276
+ readonly prompts: string[] = [];
277
+
278
+ async handleUserMessage(params: {
279
+ message: string;
280
+ }): Promise<string> {
281
+ this.prompts.push(params.message);
282
+ return params.message.includes("\"NO_REPLY\"") ? "Fallback joke" : "NO_REPLY";
283
+ }
284
+ }
285
+
286
+ class ControlledQueueBridge {
287
+ readonly calls: Array<{
288
+ message: string;
289
+ deferred: ReturnType<typeof createDeferred<string>>;
290
+ }> = [];
291
+ maxConcurrentCalls = 0;
292
+ private activeCalls = 0;
293
+
294
+ async handleUserMessage(params: {
295
+ message: string;
296
+ }): Promise<string> {
297
+ const deferred = createDeferred<string>();
298
+ this.calls.push({
299
+ message: params.message,
300
+ deferred,
301
+ });
302
+ this.activeCalls += 1;
303
+ this.maxConcurrentCalls = Math.max(
304
+ this.maxConcurrentCalls,
305
+ this.activeCalls,
306
+ );
307
+ try {
308
+ return await deferred.promise;
309
+ } finally {
310
+ this.activeCalls -= 1;
311
+ }
312
+ }
313
+
314
+ resolveCall(index: number, response: string): void {
315
+ const call = this.calls[index];
316
+ assert.ok(call, `expected bridge call ${index}`);
317
+ call.deferred.resolve(response);
318
+ }
319
+ }
320
+
251
321
  class ThinkingTraceBridge {
252
322
  readonly supportsThinkingTrace = true;
253
323
  readonly conversationMessages: string[] = [];
@@ -461,6 +531,319 @@ test("provider creates one-time invites and replies through the encrypted relay"
461
531
  appSocket.terminate();
462
532
  });
463
533
 
534
+ test("provider keeps a non-group session alive after app initiated disconnect", async (t) => {
535
+ const relay = createRelayServer({
536
+ host: "127.0.0.1",
537
+ port: 0,
538
+ sessionTtlMs: 60_000,
539
+ frameCacheSize: 8,
540
+ });
541
+ const { port } = await relay.start();
542
+ t.after(async () => {
543
+ await relay.stop();
544
+ });
545
+
546
+ const provider = new PrivateClawProvider({
547
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
548
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
549
+ bridge: new EchoBridge("OpenClaw bridge"),
550
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
551
+ welcomeMessage: "欢迎来到 PrivateClaw",
552
+ });
553
+ await provider.connect();
554
+ t.after(async () => {
555
+ await provider.dispose();
556
+ });
557
+
558
+ const inviteBundle = await provider.createInviteBundle();
559
+ const invite = decodeInviteString(inviteBundle.inviteUri);
560
+
561
+ const appOneUrl = new URL(invite.appWsUrl);
562
+ appOneUrl.searchParams.set("appId", "app-one");
563
+ const appOne = new WebSocket(appOneUrl.toString());
564
+ const appOneAttached = nextMessage(appOne);
565
+ await waitForOpen(appOne);
566
+ assert.equal((await appOneAttached).type, "relay:attached");
567
+
568
+ appOne.send(
569
+ JSON.stringify({
570
+ type: "app:frame",
571
+ envelope: encryptPayload({
572
+ sessionId: invite.sessionId,
573
+ sessionKey: invite.sessionKey,
574
+ payload: {
575
+ kind: "client_hello",
576
+ appId: "app-one",
577
+ appVersion: "flutter-test",
578
+ deviceLabel: "Device One",
579
+ sentAt: new Date().toISOString(),
580
+ },
581
+ }),
582
+ }),
583
+ );
584
+ await nextMessages(appOne, 2);
585
+
586
+ appOne.send(
587
+ JSON.stringify({
588
+ type: "app:frame",
589
+ envelope: encryptPayload({
590
+ sessionId: invite.sessionId,
591
+ sessionKey: invite.sessionKey,
592
+ payload: {
593
+ kind: "session_close",
594
+ reason: "user_disconnect",
595
+ appId: "app-one",
596
+ sentAt: new Date().toISOString(),
597
+ },
598
+ }),
599
+ }),
600
+ );
601
+ await waitForNoMessage(appOne, 120);
602
+ appOne.close();
603
+ await waitForClose(appOne);
604
+
605
+ const appTwoUrl = new URL(invite.appWsUrl);
606
+ appTwoUrl.searchParams.set("appId", "app-two");
607
+ const appTwo = new WebSocket(appTwoUrl.toString());
608
+ const appTwoAttached = nextMessage(appTwo);
609
+ await waitForOpen(appTwo);
610
+ assert.equal((await appTwoAttached).type, "relay:attached");
611
+
612
+ appTwo.send(
613
+ JSON.stringify({
614
+ type: "app:frame",
615
+ envelope: encryptPayload({
616
+ sessionId: invite.sessionId,
617
+ sessionKey: invite.sessionKey,
618
+ payload: {
619
+ kind: "client_hello",
620
+ appId: "app-two",
621
+ appVersion: "flutter-test",
622
+ deviceLabel: "Device Two",
623
+ sentAt: new Date().toISOString(),
624
+ },
625
+ }),
626
+ }),
627
+ );
628
+ await nextMessages(appTwo, 1);
629
+
630
+ appTwo.send(
631
+ JSON.stringify({
632
+ type: "app:frame",
633
+ envelope: encryptPayload({
634
+ sessionId: invite.sessionId,
635
+ sessionKey: invite.sessionKey,
636
+ payload: {
637
+ kind: "user_message",
638
+ appId: "app-two",
639
+ text: "hello again",
640
+ clientMessageId: "client-message-reconnect-1",
641
+ sentAt: new Date().toISOString(),
642
+ },
643
+ }),
644
+ }),
645
+ );
646
+
647
+ const assistant = await nextRelayPayload(appTwo, invite);
648
+ assert.equal(assistant.kind, "assistant_message");
649
+ assert.match(assistant.text, /hello again/);
650
+
651
+ appTwo.close();
652
+ await waitForClose(appTwo);
653
+ });
654
+
655
+ test("provider turns a NO_REPLY bridge response into a fallback joke", async (t) => {
656
+ const relay = createRelayServer({
657
+ host: "127.0.0.1",
658
+ port: 0,
659
+ sessionTtlMs: 60_000,
660
+ frameCacheSize: 8,
661
+ });
662
+ const { port } = await relay.start();
663
+ t.after(async () => {
664
+ await relay.stop();
665
+ });
666
+
667
+ const bridge = new NoReplyThenJokeBridge();
668
+ const provider = new PrivateClawProvider({
669
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
670
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
671
+ bridge,
672
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
673
+ welcomeMessage: "欢迎来到 PrivateClaw",
674
+ });
675
+ await provider.connect();
676
+ t.after(async () => {
677
+ await provider.dispose();
678
+ });
679
+
680
+ const inviteBundle = await provider.createInviteBundle();
681
+ const invite = decodeInviteString(inviteBundle.inviteUri);
682
+
683
+ const appSocket = new WebSocket(invite.appWsUrl);
684
+ const attachedPromise = nextMessage(appSocket);
685
+ await waitForOpen(appSocket);
686
+ assert.equal((await attachedPromise).type, "relay:attached");
687
+
688
+ appSocket.send(
689
+ JSON.stringify({
690
+ type: "app:frame",
691
+ envelope: encryptPayload({
692
+ sessionId: invite.sessionId,
693
+ sessionKey: invite.sessionKey,
694
+ payload: {
695
+ kind: "client_hello",
696
+ appVersion: "flutter-test",
697
+ deviceLabel: "Simulator",
698
+ sentAt: new Date().toISOString(),
699
+ },
700
+ }),
701
+ }),
702
+ );
703
+ await nextMessages(appSocket, 2);
704
+
705
+ appSocket.send(
706
+ JSON.stringify({
707
+ type: "app:frame",
708
+ envelope: encryptPayload({
709
+ sessionId: invite.sessionId,
710
+ sessionKey: invite.sessionKey,
711
+ payload: {
712
+ kind: "user_message",
713
+ text: "你好",
714
+ clientMessageId: "no-reply-user-1",
715
+ sentAt: new Date().toISOString(),
716
+ },
717
+ }),
718
+ }),
719
+ );
720
+
721
+ const assistant = await nextRelayPayload(appSocket, invite);
722
+ assert.equal(assistant.kind, "assistant_message");
723
+ assert.equal(assistant.replyTo, "no-reply-user-1");
724
+ assert.equal(assistant.text, "Fallback joke");
725
+ assert.equal(bridge.prompts[0], "你好");
726
+ assert.equal(bridge.prompts.length, 2);
727
+ assert.match(
728
+ bridge.prompts[1] ?? "",
729
+ /Your previous assistant reply for this turn was exactly "NO_REPLY"\./u,
730
+ );
731
+ assert.match(
732
+ bridge.prompts[1] ?? "",
733
+ /same language as the recent user\/assistant conversation already in this session/u,
734
+ );
735
+
736
+ appSocket.terminate();
737
+ });
738
+
739
+ test("provider serializes bridge turns per session", async (t) => {
740
+ const relay = createRelayServer({
741
+ host: "127.0.0.1",
742
+ port: 0,
743
+ sessionTtlMs: 60_000,
744
+ frameCacheSize: 8,
745
+ });
746
+ const { port } = await relay.start();
747
+ t.after(async () => {
748
+ await relay.stop();
749
+ });
750
+
751
+ const bridge = new ControlledQueueBridge();
752
+ const provider = new PrivateClawProvider({
753
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
754
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
755
+ bridge,
756
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
757
+ welcomeMessage: "欢迎来到 PrivateClaw",
758
+ });
759
+ await provider.connect();
760
+ t.after(async () => {
761
+ await provider.dispose();
762
+ });
763
+
764
+ const inviteBundle = await provider.createInviteBundle();
765
+ const invite = decodeInviteString(inviteBundle.inviteUri);
766
+
767
+ const appSocket = new WebSocket(invite.appWsUrl);
768
+ const attachedPromise = nextMessage(appSocket);
769
+ await waitForOpen(appSocket);
770
+ assert.equal((await attachedPromise).type, "relay:attached");
771
+
772
+ appSocket.send(
773
+ JSON.stringify({
774
+ type: "app:frame",
775
+ envelope: encryptPayload({
776
+ sessionId: invite.sessionId,
777
+ sessionKey: invite.sessionKey,
778
+ payload: {
779
+ kind: "client_hello",
780
+ appVersion: "flutter-test",
781
+ deviceLabel: "Simulator",
782
+ sentAt: new Date().toISOString(),
783
+ },
784
+ }),
785
+ }),
786
+ );
787
+ await nextMessages(appSocket, 2);
788
+
789
+ appSocket.send(
790
+ JSON.stringify({
791
+ type: "app:frame",
792
+ envelope: encryptPayload({
793
+ sessionId: invite.sessionId,
794
+ sessionKey: invite.sessionKey,
795
+ payload: {
796
+ kind: "user_message",
797
+ text: "first queued message",
798
+ clientMessageId: "queued-message-1",
799
+ sentAt: new Date().toISOString(),
800
+ },
801
+ }),
802
+ }),
803
+ );
804
+ await waitForCondition(() => bridge.calls.length === 1);
805
+
806
+ appSocket.send(
807
+ JSON.stringify({
808
+ type: "app:frame",
809
+ envelope: encryptPayload({
810
+ sessionId: invite.sessionId,
811
+ sessionKey: invite.sessionKey,
812
+ payload: {
813
+ kind: "user_message",
814
+ text: "second queued message",
815
+ clientMessageId: "queued-message-2",
816
+ sentAt: new Date().toISOString(),
817
+ },
818
+ }),
819
+ }),
820
+ );
821
+ await new Promise((resolve) => setTimeout(resolve, 80));
822
+ assert.equal(bridge.calls.length, 1);
823
+ assert.equal(bridge.maxConcurrentCalls, 1);
824
+ assert.equal(bridge.calls[0]?.message, "first queued message");
825
+
826
+ const firstAssistantPromise = nextRelayPayload(appSocket, invite);
827
+ bridge.resolveCall(0, "First queued reply");
828
+ const firstAssistant = await firstAssistantPromise;
829
+ assert.equal(firstAssistant.kind, "assistant_message");
830
+ assert.equal(firstAssistant.replyTo, "queued-message-1");
831
+ assert.equal(firstAssistant.text, "First queued reply");
832
+
833
+ await waitForCondition(() => bridge.calls.length === 2);
834
+ assert.equal(bridge.calls[1]?.message, "second queued message");
835
+ assert.equal(bridge.maxConcurrentCalls, 1);
836
+
837
+ const secondAssistantPromise = nextRelayPayload(appSocket, invite);
838
+ bridge.resolveCall(1, "Second queued reply");
839
+ const secondAssistant = await secondAssistantPromise;
840
+ assert.equal(secondAssistant.kind, "assistant_message");
841
+ assert.equal(secondAssistant.replyTo, "queued-message-2");
842
+ assert.equal(secondAssistant.text, "Second queued reply");
843
+
844
+ appSocket.terminate();
845
+ });
846
+
464
847
  test("provider emits verbose session logs when enabled", async (t) => {
465
848
  const relay = createRelayServer({
466
849
  host: "127.0.0.1",
@@ -2297,6 +2680,34 @@ test("group bot mode greets a silent participant after the configured join delay
2297
2680
  await waitForNoMessage(app, 120);
2298
2681
  });
2299
2682
 
2683
+ test("group bot mode turns a NO_REPLY proactive prompt into a fallback joke", async (t) => {
2684
+ const bridge = new NoReplyThenJokeBridge();
2685
+ const { invite } = await createGroupBotModeHarness(t, bridge, {
2686
+ botMode: true,
2687
+ botModeSilentJoinDelayMs: 40,
2688
+ botModeIdleDelayMs: 250,
2689
+ });
2690
+ const app = await connectGroupApp({
2691
+ invite,
2692
+ appId: "app-one",
2693
+ displayName: "SolarFox",
2694
+ });
2695
+ t.after(async () => {
2696
+ app.close();
2697
+ await waitForClose(app);
2698
+ });
2699
+
2700
+ const proactive = await nextRelayPayload(app, invite);
2701
+ assert.equal(proactive.kind, "assistant_message");
2702
+ assert.equal(proactive.text, "Fallback joke");
2703
+ assert.equal(bridge.prompts.length, 2);
2704
+ assert.match(bridge.prompts[0] ?? "", /joined this PrivateClaw group chat/u);
2705
+ assert.match(
2706
+ bridge.prompts[1] ?? "",
2707
+ /Your previous assistant reply for this turn was exactly "NO_REPLY"\./u,
2708
+ );
2709
+ });
2710
+
2300
2711
  test("group bot mode cancels the silent-join greeting after the participant speaks", async (t) => {
2301
2712
  const bridge = new BotModeBridge();
2302
2713
  const { invite } = await createGroupBotModeHarness(t, bridge, {
@@ -2343,7 +2754,7 @@ test("group bot mode cancels the silent-join greeting after the participant spea
2343
2754
 
2344
2755
  test("group bot mode sends an idle follow-up after the room stays quiet", async (t) => {
2345
2756
  const bridge = new BotModeBridge();
2346
- const { invite } = await createGroupBotModeHarness(t, bridge, {
2757
+ const { invite, provider } = await createGroupBotModeHarness(t, bridge, {
2347
2758
  botMode: true,
2348
2759
  botModeSilentJoinDelayMs: 250,
2349
2760
  botModeIdleDelayMs: 60,
@@ -2384,10 +2795,87 @@ test("group bot mode sends an idle follow-up after the room stays quiet", async
2384
2795
  assert.equal(idleFollowUp.text, "Bot mode joke");
2385
2796
  assert.deepEqual(bridge.promptKinds, ["user", "idle_group"]);
2386
2797
  assert.match(bridge.prompts[1]!, /has had no new message/u);
2798
+ assert.match(bridge.prompts[1]!, /Idle topic:/u);
2799
+ assert.match(bridge.prompts[1]!, /Topic prompt:/u);
2387
2800
  assert.match(
2388
2801
  bridge.prompts[1]!,
2389
2802
  /Write the proactive message in the same language as the recent user\/assistant conversation already in this session\./u,
2390
2803
  );
2804
+ const sessionState = (provider as unknown as { sessions: Map<string, { botModeLastIdleTopicId?: string }> }).sessions.get(
2805
+ invite.sessionId,
2806
+ );
2807
+ assert.ok(sessionState?.botModeLastIdleTopicId);
2808
+ assert.ok(
2809
+ BOT_MODE_IDLE_TOPICS.some(
2810
+ (topic) => topic.id === sessionState.botModeLastIdleTopicId,
2811
+ ),
2812
+ );
2813
+ });
2814
+
2815
+ test("group bot mode proactive turns wait for the session bridge queue", async (t) => {
2816
+ const bridge = new ControlledQueueBridge();
2817
+ const { invite } = await createGroupBotModeHarness(t, bridge, {
2818
+ botMode: true,
2819
+ botModeSilentJoinDelayMs: 250,
2820
+ botModeIdleDelayMs: 60,
2821
+ });
2822
+ const app = await connectGroupApp({
2823
+ invite,
2824
+ appId: "app-one",
2825
+ displayName: "SolarFox",
2826
+ });
2827
+ t.after(async () => {
2828
+ app.close();
2829
+ await waitForClose(app);
2830
+ });
2831
+
2832
+ const participantEchoPromise = nextRelayPayload(app, invite);
2833
+ app.send(
2834
+ JSON.stringify({
2835
+ type: "app:frame",
2836
+ envelope: encryptPayload({
2837
+ sessionId: invite.sessionId,
2838
+ sessionKey: invite.sessionKey,
2839
+ payload: {
2840
+ kind: "user_message",
2841
+ appId: "app-one",
2842
+ text: "queue this turn first",
2843
+ clientMessageId: "queued-bot-mode-user-1",
2844
+ sentAt: new Date().toISOString(),
2845
+ },
2846
+ }),
2847
+ }),
2848
+ );
2849
+
2850
+ const participantEcho = await participantEchoPromise;
2851
+ assert.equal(participantEcho.kind, "participant_message");
2852
+ await waitForCondition(() => bridge.calls.length === 1);
2853
+ assert.equal(bridge.calls[0]?.message, "SolarFox: queue this turn first");
2854
+
2855
+ await new Promise((resolve) => setTimeout(resolve, 90));
2856
+ assert.equal(
2857
+ bridge.calls.length,
2858
+ 1,
2859
+ "idle bot-mode prompt should wait behind the queued user turn",
2860
+ );
2861
+ assert.equal(bridge.maxConcurrentCalls, 1);
2862
+
2863
+ const assistantReplyPromise = nextRelayPayload(app, invite);
2864
+ bridge.resolveCall(0, "Queued user reply");
2865
+ const assistantReply = await assistantReplyPromise;
2866
+ assert.equal(assistantReply.kind, "assistant_message");
2867
+ assert.equal(assistantReply.replyTo, "queued-bot-mode-user-1");
2868
+ assert.equal(assistantReply.text, "Queued user reply");
2869
+
2870
+ await waitForCondition(() => bridge.calls.length === 2);
2871
+ assert.match(bridge.calls[1]?.message ?? "", /has had no new message/u);
2872
+ assert.equal(bridge.maxConcurrentCalls, 1);
2873
+
2874
+ const proactiveReplyPromise = nextRelayPayload(app, invite);
2875
+ bridge.resolveCall(1, "Queued bot joke");
2876
+ const proactiveReply = await proactiveReplyPromise;
2877
+ assert.equal(proactiveReply.kind, "assistant_message");
2878
+ assert.equal(proactiveReply.text, "Queued bot joke");
2391
2879
  });
2392
2880
 
2393
2881
  test("group bot mode idle timing ignores non-human assistant broadcasts", async (t) => {