@privateclaw/privateclaw 0.1.35 → 0.1.36

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.
@@ -408,6 +408,287 @@ test("plugin routes paired app text through OpenClaw runtime helpers with the re
408
408
  });
409
409
  });
410
410
 
411
+ test("plugin falls back to the bridge when runtime session recording reports an error", async (t) => {
412
+ const relay = createRelayServer({
413
+ host: "127.0.0.1",
414
+ port: 0,
415
+ sessionTtlMs: 60_000,
416
+ frameCacheSize: 8,
417
+ });
418
+ const { port } = await relay.start();
419
+
420
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-state-"));
421
+ t.after(async () => {
422
+ await rm(stateDir, { recursive: true, force: true });
423
+ await relay.stop();
424
+ });
425
+
426
+ let dispatchCalled = false;
427
+ const fakeRuntime = {
428
+ channel: {
429
+ reply: {
430
+ finalizeInboundContext: <T extends Record<string, unknown>>(ctx: T) =>
431
+ ({
432
+ ...ctx,
433
+ CommandAuthorized: true,
434
+ }) as T & { CommandAuthorized: true },
435
+ dispatchReplyWithBufferedBlockDispatcher: async () => {
436
+ dispatchCalled = true;
437
+ return {};
438
+ },
439
+ },
440
+ routing: {
441
+ resolveAgentRoute: ({ ctx }: { ctx: Record<string, unknown> }) => ({
442
+ agentId: "runtime-agent",
443
+ sessionKey: `runtime-${String(ctx.To ?? "session")}`,
444
+ mainSessionKey: `runtime-${String(ctx.To ?? "session")}`,
445
+ lastRoutePolicy: "current" as const,
446
+ }),
447
+ },
448
+ session: {
449
+ resolveStorePath: () => path.join(stateDir, "memory", "runtime-agent.sqlite"),
450
+ recordInboundSession: async (params: { onRecordError(error: unknown): void }) => {
451
+ params.onRecordError(new Error("simulated session-store failure"));
452
+ },
453
+ },
454
+ },
455
+ } satisfies OpenClawPluginRuntimeCompat;
456
+
457
+ const plugin = createOpenClawCompatiblePlugin({
458
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
459
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
460
+ bridge: new EchoBridge("Runtime fallback"),
461
+ welcomeMessage: "Welcome to PrivateClaw",
462
+ });
463
+ const { api, getCommand, getService } = createMockApi(fakeRuntime);
464
+ plugin.register(api);
465
+
466
+ const service = getService();
467
+ await service.start({
468
+ config: {},
469
+ stateDir,
470
+ logger: api.logger,
471
+ });
472
+ t.after(async () => {
473
+ await service.stop?.({
474
+ config: {},
475
+ stateDir,
476
+ logger: api.logger,
477
+ });
478
+ });
479
+
480
+ const command = getCommand();
481
+ const reply = await command.handler({
482
+ channel: "telegram",
483
+ senderId: "tester",
484
+ isAuthorizedSender: true,
485
+ commandBody: "/privateclaw",
486
+ config: {},
487
+ });
488
+ const inviteUri = reply.text?.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
489
+ assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
490
+ const invite = decodeInviteString(inviteUri);
491
+
492
+ const appUrl = new URL(invite.appWsUrl);
493
+ appUrl.searchParams.set("appId", "runtime-record-error-app");
494
+ const appSocket = new WebSocket(appUrl.toString());
495
+ t.after(() => {
496
+ appSocket.terminate();
497
+ });
498
+ const attached = nextMessage(appSocket);
499
+ await waitForOpen(appSocket);
500
+ assert.equal((await attached).type, "relay:attached");
501
+ const initialFrames = nextMessages(appSocket, 2);
502
+ appSocket.send(
503
+ JSON.stringify({
504
+ type: "app:frame",
505
+ envelope: encryptPayload({
506
+ sessionId: invite.sessionId,
507
+ sessionKey: invite.sessionKey,
508
+ payload: {
509
+ kind: "client_hello",
510
+ appId: "runtime-record-error-app",
511
+ displayName: "Runtime Record Error",
512
+ appVersion: "plugin-test",
513
+ deviceLabel: "Runtime Record Error Device",
514
+ sentAt: new Date().toISOString(),
515
+ },
516
+ }),
517
+ }),
518
+ );
519
+ await initialFrames;
520
+
521
+ appSocket.send(
522
+ JSON.stringify({
523
+ type: "app:frame",
524
+ envelope: encryptPayload({
525
+ sessionId: invite.sessionId,
526
+ sessionKey: invite.sessionKey,
527
+ payload: {
528
+ kind: "user_message",
529
+ appId: "runtime-record-error-app",
530
+ text: "hello fallback",
531
+ clientMessageId: "runtime-record-error-msg-1",
532
+ sentAt: new Date().toISOString(),
533
+ },
534
+ }),
535
+ }),
536
+ );
537
+
538
+ const replyFrame = await nextMessage(appSocket);
539
+ const replyPayload = decryptPayload({
540
+ sessionId: invite.sessionId,
541
+ sessionKey: invite.sessionKey,
542
+ envelope: replyFrame.envelope as Parameters<typeof decryptPayload>[0]["envelope"],
543
+ });
544
+ assert.equal(replyPayload.kind, "assistant_message");
545
+ assert.equal(replyPayload.text, "Runtime fallback: hello fallback");
546
+ assert.equal(dispatchCalled, false);
547
+ });
548
+
549
+ test("plugin falls back to the bridge when runtime reply dispatch reports an error", async (t) => {
550
+ const relay = createRelayServer({
551
+ host: "127.0.0.1",
552
+ port: 0,
553
+ sessionTtlMs: 60_000,
554
+ frameCacheSize: 8,
555
+ });
556
+ const { port } = await relay.start();
557
+
558
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-state-"));
559
+ t.after(async () => {
560
+ await rm(stateDir, { recursive: true, force: true });
561
+ await relay.stop();
562
+ });
563
+
564
+ const fakeRuntime = {
565
+ channel: {
566
+ reply: {
567
+ finalizeInboundContext: <T extends Record<string, unknown>>(ctx: T) =>
568
+ ({
569
+ ...ctx,
570
+ CommandAuthorized: true,
571
+ }) as T & { CommandAuthorized: true },
572
+ dispatchReplyWithBufferedBlockDispatcher: async ({
573
+ dispatcherOptions,
574
+ }: {
575
+ dispatcherOptions: {
576
+ onError?(error: unknown, info: { kind: "tool" | "block" | "final" }): void;
577
+ };
578
+ }) => {
579
+ dispatcherOptions.onError?.(
580
+ new Error("simulated runtime dispatch failure"),
581
+ { kind: "final" },
582
+ );
583
+ return {};
584
+ },
585
+ },
586
+ routing: {
587
+ resolveAgentRoute: ({ ctx }: { ctx: Record<string, unknown> }) => ({
588
+ agentId: "runtime-agent",
589
+ sessionKey: `runtime-${String(ctx.To ?? "session")}`,
590
+ mainSessionKey: `runtime-${String(ctx.To ?? "session")}`,
591
+ lastRoutePolicy: "current" as const,
592
+ }),
593
+ },
594
+ session: {
595
+ resolveStorePath: () => path.join(stateDir, "memory", "runtime-agent.sqlite"),
596
+ recordInboundSession: async () => undefined,
597
+ },
598
+ },
599
+ } satisfies OpenClawPluginRuntimeCompat;
600
+
601
+ const plugin = createOpenClawCompatiblePlugin({
602
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
603
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
604
+ bridge: new EchoBridge("Runtime fallback"),
605
+ welcomeMessage: "Welcome to PrivateClaw",
606
+ });
607
+ const { api, getCommand, getService } = createMockApi(fakeRuntime);
608
+ plugin.register(api);
609
+
610
+ const service = getService();
611
+ await service.start({
612
+ config: {},
613
+ stateDir,
614
+ logger: api.logger,
615
+ });
616
+ t.after(async () => {
617
+ await service.stop?.({
618
+ config: {},
619
+ stateDir,
620
+ logger: api.logger,
621
+ });
622
+ });
623
+
624
+ const command = getCommand();
625
+ const reply = await command.handler({
626
+ channel: "telegram",
627
+ senderId: "tester",
628
+ isAuthorizedSender: true,
629
+ commandBody: "/privateclaw",
630
+ config: {},
631
+ });
632
+ const inviteUri = reply.text?.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
633
+ assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
634
+ const invite = decodeInviteString(inviteUri);
635
+
636
+ const appUrl = new URL(invite.appWsUrl);
637
+ appUrl.searchParams.set("appId", "runtime-dispatch-error-app");
638
+ const appSocket = new WebSocket(appUrl.toString());
639
+ t.after(() => {
640
+ appSocket.terminate();
641
+ });
642
+ const attached = nextMessage(appSocket);
643
+ await waitForOpen(appSocket);
644
+ assert.equal((await attached).type, "relay:attached");
645
+ const initialFrames = nextMessages(appSocket, 2);
646
+ appSocket.send(
647
+ JSON.stringify({
648
+ type: "app:frame",
649
+ envelope: encryptPayload({
650
+ sessionId: invite.sessionId,
651
+ sessionKey: invite.sessionKey,
652
+ payload: {
653
+ kind: "client_hello",
654
+ appId: "runtime-dispatch-error-app",
655
+ displayName: "Runtime Dispatch Error",
656
+ appVersion: "plugin-test",
657
+ deviceLabel: "Runtime Dispatch Error Device",
658
+ sentAt: new Date().toISOString(),
659
+ },
660
+ }),
661
+ }),
662
+ );
663
+ await initialFrames;
664
+
665
+ appSocket.send(
666
+ JSON.stringify({
667
+ type: "app:frame",
668
+ envelope: encryptPayload({
669
+ sessionId: invite.sessionId,
670
+ sessionKey: invite.sessionKey,
671
+ payload: {
672
+ kind: "user_message",
673
+ appId: "runtime-dispatch-error-app",
674
+ text: "hello dispatch fallback",
675
+ clientMessageId: "runtime-dispatch-error-msg-1",
676
+ sentAt: new Date().toISOString(),
677
+ },
678
+ }),
679
+ }),
680
+ );
681
+
682
+ const replyFrame = await nextMessage(appSocket);
683
+ const replyPayload = decryptPayload({
684
+ sessionId: invite.sessionId,
685
+ sessionKey: invite.sessionKey,
686
+ envelope: replyFrame.envelope as Parameters<typeof decryptPayload>[0]["envelope"],
687
+ });
688
+ assert.equal(replyPayload.kind, "assistant_message");
689
+ assert.equal(replyPayload.text, "Runtime fallback: hello dispatch fallback");
690
+ });
691
+
411
692
  test("privateclaw channel outbound delivers replies into managed sessions", async (t) => {
412
693
  const relay = createRelayServer({
413
694
  host: "127.0.0.1",
@@ -931,6 +931,7 @@ class PrivateClawPluginRuntime {
931
931
  agentId: route.agentId,
932
932
  },
933
933
  );
934
+ let recordErrorMessage: string | undefined;
934
935
  await runtime.session.recordInboundSession({
935
936
  storePath,
936
937
  sessionKey: route.sessionKey,
@@ -946,16 +947,28 @@ class PrivateClawPluginRuntime {
946
947
  accountId: PRIVATECLAW_OPENCLAW_ACCOUNT_ID,
947
948
  },
948
949
  onRecordError: (error) => {
950
+ const detail = formatCommandError(error);
951
+ if (!recordErrorMessage) {
952
+ recordErrorMessage = detail;
953
+ }
949
954
  this.providerOptions.onLog?.(
950
- `[privateclaw] runtime_session_record_error session=${message.sessionId} message=${formatCommandError(error)}`,
955
+ `[privateclaw] runtime_session_record_error session=${message.sessionId} message=${detail}`,
951
956
  );
952
957
  },
953
958
  });
959
+ if (recordErrorMessage) {
960
+ throw new Error(
961
+ `Failed to record the OpenClaw runtime session for ${message.sessionId}: ${recordErrorMessage}`,
962
+ );
963
+ }
964
+ let finalReplyDelivered = false;
965
+ let dispatchErrorKind: string | undefined;
966
+ let dispatchErrorMessage: string | undefined;
954
967
  await runtime.reply.dispatchReplyWithBufferedBlockDispatcher({
955
968
  ctx: finalizedCtx,
956
969
  cfg,
957
970
  dispatcherOptions: {
958
- deliver: async (payload) => {
971
+ deliver: async (payload, info) => {
959
972
  const replyToId =
960
973
  typeof payload.replyToId === "string" && payload.replyToId.trim() !== ""
961
974
  ? payload.replyToId
@@ -970,24 +983,37 @@ class PrivateClawPluginRuntime {
970
983
  : {}),
971
984
  replyToId,
972
985
  });
986
+ if (info.kind === "final") {
987
+ finalReplyDelivered = true;
988
+ }
973
989
  },
974
990
  onError: (error, info) => {
991
+ const detail = formatCommandError(error);
992
+ if (!dispatchErrorMessage) {
993
+ dispatchErrorKind = info.kind;
994
+ dispatchErrorMessage = detail;
995
+ }
975
996
  this.providerOptions.onLog?.(
976
- `[privateclaw] runtime_dispatch_error kind=${info.kind} message=${formatCommandError(error)}`,
997
+ `[privateclaw] runtime_dispatch_error kind=${info.kind} message=${detail}`,
977
998
  );
978
999
  },
979
1000
  },
980
1001
  });
1002
+ if (dispatchErrorMessage && !finalReplyDelivered) {
1003
+ throw new Error(
1004
+ `Failed to dispatch the OpenClaw runtime reply for ${message.sessionId} (${dispatchErrorKind ?? "unknown"}): ${dispatchErrorMessage}`,
1005
+ );
1006
+ }
981
1007
  }
982
1008
 
983
1009
  private async routeOrForwardAppMessage(
984
1010
  message: PrivateClawRoutedAppMessage,
985
1011
  ): Promise<boolean> {
986
- if (this.openClawRuntime?.channel) {
987
- await this.routeAppMessageToOpenClaw(message);
988
- return true;
989
- }
990
1012
  try {
1013
+ if (this.openClawRuntime?.channel) {
1014
+ await this.routeAppMessageToOpenClaw(message);
1015
+ return true;
1016
+ }
991
1017
  await dispatchRoutedAppMessageToPluginServiceFromStateDir({
992
1018
  stateDir: this.ensureStateDir(),
993
1019
  message,
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { spawn } from "node:child_process";
3
3
  import { createServer } from "node:http";
4
- import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
4
+ import { access, mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
5
5
  import { type AddressInfo } from "node:net";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
@@ -77,6 +77,21 @@ function nextMessages(socket: WebSocket, count: number): Promise<Record<string,
77
77
  });
78
78
  }
79
79
 
80
+ function findUnusedPid(start = 999_999): number {
81
+ let candidate = start;
82
+ for (;;) {
83
+ try {
84
+ process.kill(candidate, 0);
85
+ candidate += 1;
86
+ } catch (error) {
87
+ if ((error as NodeJS.ErrnoException | undefined)?.code === "ESRCH") {
88
+ return candidate;
89
+ }
90
+ candidate += 1;
91
+ }
92
+ }
93
+ }
94
+
80
95
  function waitForClose(socket: WebSocket): Promise<void> {
81
96
  return new Promise((resolve) => {
82
97
  if (socket.readyState === WebSocket.CLOSED) {
@@ -816,3 +831,69 @@ test("session control falls back to the saved QR PNG when an older host lacks th
816
831
  /TestFlight|Google Play|Google Group/u,
817
832
  );
818
833
  });
834
+
835
+ test("session listings keep a live descriptor when one sessions probe fails", async (t) => {
836
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-session-control-live-"));
837
+ t.after(async () => {
838
+ await rm(stateDir, { recursive: true, force: true });
839
+ });
840
+
841
+ const descriptorDir = resolvePrivateClawControlDir(stateDir);
842
+ await mkdir(descriptorDir, { recursive: true, mode: 0o700 });
843
+ const descriptorPath = path.join(descriptorDir, "pair-daemon-live.json");
844
+ await writeFile(
845
+ descriptorPath,
846
+ JSON.stringify(
847
+ {
848
+ version: 1,
849
+ controlId: "live-control-id",
850
+ kind: "pair-daemon",
851
+ pid: process.pid,
852
+ host: "127.0.0.1",
853
+ port: 1,
854
+ token: "live-token",
855
+ startedAt: new Date().toISOString(),
856
+ },
857
+ null,
858
+ 2,
859
+ ),
860
+ "utf8",
861
+ );
862
+
863
+ const listings = await listManagedSessionsFromStateDir(stateDir);
864
+ assert.deepEqual(listings, []);
865
+ await access(descriptorPath);
866
+ });
867
+
868
+ test("session listings prune a stale descriptor after a failed sessions probe", async (t) => {
869
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-session-control-stale-"));
870
+ t.after(async () => {
871
+ await rm(stateDir, { recursive: true, force: true });
872
+ });
873
+
874
+ const descriptorDir = resolvePrivateClawControlDir(stateDir);
875
+ await mkdir(descriptorDir, { recursive: true, mode: 0o700 });
876
+ const descriptorPath = path.join(descriptorDir, "pair-daemon-stale.json");
877
+ await writeFile(
878
+ descriptorPath,
879
+ JSON.stringify(
880
+ {
881
+ version: 1,
882
+ controlId: "stale-control-id",
883
+ kind: "pair-daemon",
884
+ pid: findUnusedPid(),
885
+ host: "127.0.0.1",
886
+ port: 1,
887
+ token: "stale-token",
888
+ startedAt: new Date().toISOString(),
889
+ },
890
+ null,
891
+ 2,
892
+ ),
893
+ "utf8",
894
+ );
895
+
896
+ const listings = await listManagedSessionsFromStateDir(stateDir);
897
+ assert.deepEqual(listings, []);
898
+ await assert.rejects(access(descriptorPath));
899
+ });
@@ -182,6 +182,32 @@ function readNonEmptyString(value: unknown): string | undefined {
182
182
  return trimmed === "" ? undefined : trimmed;
183
183
  }
184
184
 
185
+ function isDescriptorProcessAlive(
186
+ descriptor: Pick<PrivateClawSessionControlDescriptor, "pid">,
187
+ ): boolean {
188
+ if (!Number.isInteger(descriptor.pid) || descriptor.pid <= 0) {
189
+ return false;
190
+ }
191
+ try {
192
+ process.kill(descriptor.pid, 0);
193
+ return true;
194
+ } catch (error) {
195
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
196
+ return code !== "ESRCH";
197
+ }
198
+ }
199
+
200
+ async function pruneDescriptorIfProcessExited(params: {
201
+ descriptor: PrivateClawSessionControlDescriptor;
202
+ descriptorPath: string;
203
+ }): Promise<boolean> {
204
+ if (isDescriptorProcessAlive(params.descriptor)) {
205
+ return false;
206
+ }
207
+ await rm(params.descriptorPath, { force: true });
208
+ return true;
209
+ }
210
+
185
211
  function normalizeManagedSessionLookupId(sessionId: string): string {
186
212
  const trimmed = sessionId.trim();
187
213
  const separatorIndex = trimmed.indexOf(":");
@@ -713,7 +739,7 @@ export async function listManagedSessionsFromStateDir(
713
739
  sessions: response.sessions ?? [],
714
740
  });
715
741
  } catch {
716
- await rm(descriptorPath, { force: true });
742
+ await pruneDescriptorIfProcessExited({ descriptor, descriptorPath });
717
743
  }
718
744
  }
719
745
 
@@ -780,7 +806,7 @@ async function resolvePluginServiceDescriptor(params: {
780
806
  await requestDescriptorJson<{ ok: true }>(candidate.descriptor, "/healthz");
781
807
  return candidate;
782
808
  } catch {
783
- await rm(candidate.descriptorPath, { force: true });
809
+ await pruneDescriptorIfProcessExited(candidate);
784
810
  }
785
811
  }
786
812
  throw new Error(