@privateclaw/privateclaw 0.1.12 → 0.1.14

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.
@@ -1,3 +1,4 @@
1
+ import { pathToFileURL } from "node:url";
1
2
  import { EchoBridge } from "./bridges/echo-bridge.js";
2
3
  import {
3
4
  OpenClawAgentBridge,
@@ -9,8 +10,10 @@ import {
9
10
  } from "./invite-qr-files.js";
10
11
  import { loadAvailableOpenClawCommands } from "./openclaw-command-discovery.js";
11
12
  import {
13
+ openInBrowserPreview,
12
14
  parsePositiveIntegerFlag,
13
15
  printPairInviteBundle,
16
+ renderInviteBundleOutput,
14
17
  runPairSession,
15
18
  } from "./pair-session.js";
16
19
  import {
@@ -29,7 +32,11 @@ import { DEFAULT_SESSION_TTL_MS, PrivateClawProvider } from "./provider.js";
29
32
  import { DEFAULT_RELAY_BASE_URL } from "./relay-defaults.js";
30
33
  import { resolveRelayEndpoints } from "./relay-endpoints.js";
31
34
  import {
35
+ buildManagedSessionQrLegacyLines,
32
36
  buildManagedSessionsReportLines,
37
+ closeManagedSessionFromStateDir,
38
+ getManagedSessionQrBundleFromStateDir,
39
+ isManagedSessionQrLegacyResult,
33
40
  kickManagedParticipantFromStateDir,
34
41
  listManagedSessionsFromStateDir,
35
42
  PrivateClawSessionControlServer,
@@ -37,17 +44,22 @@ import {
37
44
  type PrivateClawControlHostKind,
38
45
  } from "./session-control.js";
39
46
  import {
47
+ buildPrivateClawBackgroundDaemonReminder,
40
48
  buildPrivateClawCommandErrorMessage,
41
49
  formatBilingualInline,
42
50
  PRIVATECLAW_CLI_FOREGROUND_OPTION_DESCRIPTION,
43
51
  PRIVATECLAW_CLI_GROUP_OPTION_DESCRIPTION,
44
52
  PRIVATECLAW_CLI_KICK_DESCRIPTION,
45
53
  PRIVATECLAW_CLI_LABEL_OPTION_DESCRIPTION,
54
+ PRIVATECLAW_CLI_NOTIFY_OPTION_DESCRIPTION,
46
55
  PRIVATECLAW_CLI_OPEN_OPTION_DESCRIPTION,
47
56
  PRIVATECLAW_CLI_PAIR_DESCRIPTION,
48
57
  PRIVATECLAW_CLI_PRINT_ONLY_OPTION_DESCRIPTION,
58
+ PRIVATECLAW_CLI_RELAY_OPTION_DESCRIPTION,
49
59
  PRIVATECLAW_CLI_ROOT_DESCRIPTION,
50
60
  PRIVATECLAW_CLI_SESSIONS_DESCRIPTION,
61
+ PRIVATECLAW_CLI_SESSIONS_KILL_DESCRIPTION,
62
+ PRIVATECLAW_CLI_SESSIONS_QR_DESCRIPTION,
51
63
  PRIVATECLAW_CLI_TTL_OPTION_DESCRIPTION,
52
64
  PRIVATECLAW_COMMAND_DESCRIPTION,
53
65
  PRIVATECLAW_INVITE_URI_LABEL,
@@ -56,6 +68,7 @@ import {
56
68
  import type {
57
69
  PrivateClawAgentBridge,
58
70
  PrivateClawInviteBundle,
71
+ PrivateClawManagedSession,
59
72
  PrivateClawProviderOptions,
60
73
  } from "./types.js";
61
74
 
@@ -105,12 +118,18 @@ interface ResolvedPrivateClawPluginConfig {
105
118
  interface PrivateClawPairCliOptions {
106
119
  ttlMs?: string;
107
120
  label?: string;
121
+ relay?: string;
108
122
  printOnly?: boolean;
109
123
  group?: boolean;
110
124
  open?: boolean;
111
125
  foreground?: boolean;
112
126
  }
113
127
 
128
+ interface PrivateClawSessionsQrCliOptions {
129
+ open?: boolean;
130
+ notify?: boolean;
131
+ }
132
+
114
133
  const DEFAULT_PROVIDER_LABEL = "PrivateClaw";
115
134
  const DEFAULT_BRIDGE_MODE: PrivateClawBridgeMode = "openclaw-agent";
116
135
  const QQ_INLINE_IMAGE_REPLY_CHANNELS = new Set(["qqbot", "qq", "qqguild", "qq-guild"]);
@@ -337,9 +356,11 @@ function normalizePairCliOptions(raw: unknown): PrivateClawPairCliOptions {
337
356
  const options = raw as Record<string, unknown>;
338
357
  const ttlMs = readString(options.ttlMs);
339
358
  const label = readString(options.label);
359
+ const relay = readString(options.relay);
340
360
  return {
341
361
  ...(ttlMs ? { ttlMs } : {}),
342
362
  ...(label ? { label } : {}),
363
+ ...(relay ? { relay } : {}),
343
364
  ...(typeof options.printOnly === "boolean" ? { printOnly: options.printOnly } : {}),
344
365
  ...(typeof options.group === "boolean" ? { group: options.group } : {}),
345
366
  ...(typeof options.open === "boolean" ? { open: options.open } : {}),
@@ -349,18 +370,110 @@ function normalizePairCliOptions(raw: unknown): PrivateClawPairCliOptions {
349
370
  };
350
371
  }
351
372
 
373
+ function normalizeSessionsQrCliOptions(
374
+ raw: unknown,
375
+ ): PrivateClawSessionsQrCliOptions {
376
+ if (!raw || typeof raw !== "object") {
377
+ return {};
378
+ }
379
+
380
+ const options = raw as Record<string, unknown>;
381
+ return {
382
+ ...(typeof options.open === "boolean" ? { open: options.open } : {}),
383
+ ...(typeof options.notify === "boolean" ? { notify: options.notify } : {}),
384
+ };
385
+ }
386
+
352
387
  function parsePrivateClawCommandArgs(raw: string | undefined): {
353
388
  groupMode?: boolean;
389
+ relayBaseUrl?: string;
354
390
  } {
355
391
  const normalizedArgs = (raw ?? "")
356
392
  .split(/\s+/)
357
- .map((token) => token.trim().toLowerCase())
393
+ .map((token) => token.trim())
358
394
  .filter((token) => token !== "");
359
- return normalizedArgs.some(
360
- (token) => token === "group" || token === "--group" || token === "-g",
361
- )
362
- ? { groupMode: true }
363
- : {};
395
+ let groupMode = false;
396
+ let relayBaseUrl: string | undefined;
397
+
398
+ for (let index = 0; index < normalizedArgs.length; index += 1) {
399
+ const token = normalizedArgs[index];
400
+ if (!token) {
401
+ continue;
402
+ }
403
+ const normalized = token.toLowerCase();
404
+ if (normalized === "group" || normalized === "--group" || normalized === "-g") {
405
+ groupMode = true;
406
+ continue;
407
+ }
408
+
409
+ if (normalized === "--relay" || normalized === "-r") {
410
+ const nextToken = normalizedArgs[index + 1]?.trim();
411
+ if (!nextToken) {
412
+ throw new Error(
413
+ formatBilingualInline(
414
+ "`/privateclaw --relay` 后面需要提供 relay URL。",
415
+ "`/privateclaw --relay` requires a relay URL.",
416
+ ),
417
+ );
418
+ }
419
+ relayBaseUrl = nextToken;
420
+ index += 1;
421
+ continue;
422
+ }
423
+
424
+ const equalsIndex = token.indexOf("=");
425
+ if (equalsIndex <= 0) {
426
+ continue;
427
+ }
428
+ const key = token.slice(0, equalsIndex).toLowerCase();
429
+ if (key !== "relay" && key !== "--relay" && key !== "-r") {
430
+ continue;
431
+ }
432
+ const value = token.slice(equalsIndex + 1).trim();
433
+ if (!value) {
434
+ throw new Error(
435
+ formatBilingualInline(
436
+ "`relay=` 后面需要提供 relay URL。",
437
+ "`relay=` requires a relay URL.",
438
+ ),
439
+ );
440
+ }
441
+ relayBaseUrl = value;
442
+ }
443
+
444
+ return {
445
+ ...(groupMode ? { groupMode: true } : {}),
446
+ ...(relayBaseUrl ? { relayBaseUrl } : {}),
447
+ };
448
+ }
449
+
450
+ function inferRelayBaseUrlFromAppWsUrl(appWsUrl: string): string {
451
+ try {
452
+ const url = new URL(appWsUrl);
453
+ url.pathname = "/";
454
+ url.search = "";
455
+ url.hash = "";
456
+ return url.origin;
457
+ } catch {
458
+ return DEFAULT_RELAY_BASE_URL;
459
+ }
460
+ }
461
+
462
+ function mergeDaemonEnvForRelay(
463
+ baseEnv: NodeJS.ProcessEnv | undefined,
464
+ relayBaseUrl?: string,
465
+ ): NodeJS.ProcessEnv | undefined {
466
+ if (!baseEnv) {
467
+ return undefined;
468
+ }
469
+ const normalizedRelayBaseUrl = readString(relayBaseUrl);
470
+ if (!normalizedRelayBaseUrl) {
471
+ return baseEnv;
472
+ }
473
+ return {
474
+ ...baseEnv,
475
+ PRIVATECLAW_RELAY_BASE_URL: normalizedRelayBaseUrl,
476
+ };
364
477
  }
365
478
 
366
479
  function buildProviderOptions(
@@ -446,15 +559,27 @@ function buildDaemonEnvFromPluginConfig(
446
559
  }
447
560
 
448
561
  class PrivateClawPluginRuntime {
449
- private provider: PrivateClawProvider | undefined;
562
+ private readonly providerEntries = new Map<
563
+ string,
564
+ {
565
+ provider?: PrivateClawProvider;
566
+ providerOptions: PrivateClawProviderOptions;
567
+ }
568
+ >();
450
569
  private stateDir: string | undefined;
451
570
  private controlServer: PrivateClawSessionControlServer | undefined;
571
+ private readonly defaultRelayBaseUrl: string;
452
572
 
453
573
  constructor(
454
574
  private readonly providerOptions: PrivateClawProviderOptions,
455
575
  private readonly defaultTtlMs: number = DEFAULT_SESSION_TTL_MS,
456
576
  private readonly daemonEnv?: NodeJS.ProcessEnv,
457
- ) {}
577
+ defaultRelayBaseUrl?: string,
578
+ ) {
579
+ this.defaultRelayBaseUrl =
580
+ readString(defaultRelayBaseUrl) ??
581
+ inferRelayBaseUrlFromAppWsUrl(providerOptions.appWsUrl);
582
+ }
458
583
 
459
584
  setStateDir(stateDir: string): void {
460
585
  this.stateDir = stateDir;
@@ -469,12 +594,104 @@ class PrivateClawPluginRuntime {
469
594
  return resolvePrivateClawMediaDir(this.ensureStateDir());
470
595
  }
471
596
 
472
- private getProvider(): PrivateClawProvider {
473
- if (!this.provider) {
474
- this.provider = new PrivateClawProvider(this.providerOptions);
597
+ private resolveRelayBaseUrl(relayBaseUrl?: string): string {
598
+ return readString(relayBaseUrl) ?? this.defaultRelayBaseUrl;
599
+ }
600
+
601
+ private getProviderEntry(relayBaseUrl?: string): {
602
+ provider?: PrivateClawProvider;
603
+ providerOptions: PrivateClawProviderOptions;
604
+ } {
605
+ const resolvedRelayBaseUrl = this.resolveRelayBaseUrl(relayBaseUrl);
606
+ let entry = this.providerEntries.get(resolvedRelayBaseUrl);
607
+ if (!entry) {
608
+ const relay = resolveRelayEndpoints(resolvedRelayBaseUrl);
609
+ entry = {
610
+ providerOptions: {
611
+ ...this.providerOptions,
612
+ providerWsUrl: relay.providerWsUrl,
613
+ appWsUrl: relay.appWsUrl,
614
+ },
615
+ };
616
+ this.providerEntries.set(resolvedRelayBaseUrl, entry);
617
+ }
618
+ return entry;
619
+ }
620
+
621
+ private getProvider(relayBaseUrl?: string): PrivateClawProvider {
622
+ const entry = this.getProviderEntry(relayBaseUrl);
623
+ if (!entry.provider) {
624
+ entry.provider = new PrivateClawProvider(entry.providerOptions);
625
+ }
626
+
627
+ return entry.provider;
628
+ }
629
+
630
+ private listLocalManagedSessions(): PrivateClawManagedSession[] {
631
+ return [...this.providerEntries.values()].flatMap((entry) =>
632
+ entry.provider?.listManagedSessions() ?? [],
633
+ );
634
+ }
635
+
636
+ private async kickLocalManagedParticipant(
637
+ sessionId: string,
638
+ appId: string,
639
+ reason = "participant_removed",
640
+ ) {
641
+ for (const entry of this.providerEntries.values()) {
642
+ const provider = entry.provider;
643
+ if (!provider) {
644
+ continue;
645
+ }
646
+ if (
647
+ provider
648
+ .listManagedSessions()
649
+ .some((session) => session.sessionId === sessionId)
650
+ ) {
651
+ return provider.kickGroupParticipant(sessionId, appId, reason);
652
+ }
653
+ }
654
+ throw new Error(`Unknown PrivateClaw session: ${sessionId}`);
655
+ }
656
+
657
+ private async getLocalManagedSessionQrBundle(
658
+ sessionId: string,
659
+ params?: { notifyParticipants?: boolean },
660
+ ): Promise<PrivateClawInviteBundle> {
661
+ for (const entry of this.providerEntries.values()) {
662
+ const provider = entry.provider;
663
+ if (!provider) {
664
+ continue;
665
+ }
666
+ if (
667
+ provider
668
+ .listManagedSessions()
669
+ .some((session) => session.sessionId === sessionId)
670
+ ) {
671
+ return provider.getSessionQrBundle(sessionId, params);
672
+ }
475
673
  }
674
+ throw new Error(`Unknown PrivateClaw session: ${sessionId}`);
675
+ }
476
676
 
477
- return this.provider;
677
+ private async closeLocalManagedSession(
678
+ sessionId: string,
679
+ reason = "operator_terminated",
680
+ ): Promise<PrivateClawManagedSession> {
681
+ for (const entry of this.providerEntries.values()) {
682
+ const provider = entry.provider;
683
+ if (!provider) {
684
+ continue;
685
+ }
686
+ if (
687
+ provider
688
+ .listManagedSessions()
689
+ .some((session) => session.sessionId === sessionId)
690
+ ) {
691
+ return provider.closeManagedSession(sessionId, reason);
692
+ }
693
+ }
694
+ throw new Error(`Unknown PrivateClaw session: ${sessionId}`);
478
695
  }
479
696
 
480
697
  private async ensureControlServer(
@@ -484,7 +701,15 @@ class PrivateClawPluginRuntime {
484
701
  return;
485
702
  }
486
703
  this.controlServer = new PrivateClawSessionControlServer({
487
- provider: this.getProvider(),
704
+ provider: {
705
+ listManagedSessions: () => this.listLocalManagedSessions(),
706
+ getSessionQrBundle: (sessionId, params) =>
707
+ this.getLocalManagedSessionQrBundle(sessionId, params),
708
+ closeManagedSession: (sessionId, reason) =>
709
+ this.closeLocalManagedSession(sessionId, reason),
710
+ kickGroupParticipant: (sessionId, appId, reason) =>
711
+ this.kickLocalManagedParticipant(sessionId, appId, reason),
712
+ },
488
713
  stateDir: this.ensureStateDir(),
489
714
  kind,
490
715
  ...(this.providerOptions.onLog
@@ -498,9 +723,10 @@ class PrivateClawPluginRuntime {
498
723
  ttlMs?: number;
499
724
  label?: string;
500
725
  groupMode?: boolean;
726
+ relayBaseUrl?: string;
501
727
  }): Promise<PrivateClawInviteBundle> {
502
728
  await this.ensureControlServer("plugin-service");
503
- return this.getProvider().createInviteBundle(
729
+ return this.getProvider(params?.relayBaseUrl).createInviteBundle(
504
730
  {
505
731
  ...(typeof params?.ttlMs === "number"
506
732
  ? { ttlMs: params.ttlMs }
@@ -538,6 +764,7 @@ class PrivateClawPluginRuntime {
538
764
  ttlMs?: number;
539
765
  label?: string;
540
766
  groupMode?: boolean;
767
+ relayBaseUrl?: string;
541
768
  openInBrowser?: boolean;
542
769
  writeLine?: (line: string) => void;
543
770
  }): Promise<PrivateClawInviteBundle> {
@@ -549,6 +776,10 @@ class PrivateClawPluginRuntime {
549
776
  ),
550
777
  );
551
778
  }
779
+ const daemonEnv = mergeDaemonEnvForRelay(
780
+ this.daemonEnv,
781
+ params?.relayBaseUrl,
782
+ );
552
783
 
553
784
  const bundle = await spawnBackgroundPairDaemon({
554
785
  cliModuleUrl: new URL(
@@ -556,13 +787,19 @@ class PrivateClawPluginRuntime {
556
787
  import.meta.url,
557
788
  ).href,
558
789
  stateDir: this.ensureStateDir(),
559
- ...(this.daemonEnv ? { env: this.daemonEnv } : {}),
790
+ ...(daemonEnv ? { env: daemonEnv } : {}),
560
791
  ...(typeof params?.ttlMs === "number" ? { ttlMs: params.ttlMs } : {}),
561
792
  ...(params?.label ? { label: params.label } : {}),
562
793
  ...(params?.groupMode === true ? { groupMode: true } : {}),
563
794
  ...(params?.openInBrowser === true ? { openInBrowser: true } : {}),
564
795
  });
565
796
  printPairInviteBundle(bundle, params?.writeLine ?? ((line) => console.log(line)));
797
+ (params?.writeLine ?? ((line: string) => console.log(line)))(
798
+ buildPrivateClawBackgroundDaemonReminder(
799
+ "openclaw privateclaw",
800
+ bundle.invite.sessionId,
801
+ ),
802
+ );
566
803
  return bundle;
567
804
  }
568
805
 
@@ -571,6 +808,7 @@ class PrivateClawPluginRuntime {
571
808
  label?: string;
572
809
  printOnly?: boolean;
573
810
  groupMode?: boolean;
811
+ relayBaseUrl?: string;
574
812
  foreground?: boolean;
575
813
  openInBrowser?: boolean;
576
814
  writeLine?: (line: string) => void;
@@ -578,7 +816,11 @@ class PrivateClawPluginRuntime {
578
816
  if (!params?.printOnly) {
579
817
  await this.ensureControlServer("pair-foreground");
580
818
  }
581
- const provider = this.getProvider();
819
+ const provider = this.getProvider(params?.relayBaseUrl);
820
+ const handoffEnv = mergeDaemonEnvForRelay(
821
+ this.daemonEnv,
822
+ params?.relayBaseUrl,
823
+ );
582
824
  return runPairSession({
583
825
  provider,
584
826
  ...(typeof params?.ttlMs === "number"
@@ -599,19 +841,19 @@ class PrivateClawPluginRuntime {
599
841
  handoffToBackground: async () => {
600
842
  provider.suppressReconnectsForHandoff();
601
843
  try {
602
- await handoffForegroundPairToBackground({
603
- cliModuleUrl: new URL(
604
- import.meta.url.endsWith(".ts") ? "./cli.ts" : "./cli.js",
605
- import.meta.url,
606
- ).href,
607
- stateDir: this.ensureStateDir(),
608
- ...(this.daemonEnv ? { env: this.daemonEnv } : {}),
609
- handoffState: provider.exportHandoffState(),
610
- });
611
- return formatBilingualInline(
612
- "当前 PrivateClaw 会话已转入后台。可使用 `openclaw privateclaw sessions` 查看。",
613
- "The current PrivateClaw session is now running in the background. Use `openclaw privateclaw sessions` to inspect it.",
614
- );
844
+ await handoffForegroundPairToBackground({
845
+ cliModuleUrl: new URL(
846
+ import.meta.url.endsWith(".ts") ? "./cli.ts" : "./cli.js",
847
+ import.meta.url,
848
+ ).href,
849
+ stateDir: this.ensureStateDir(),
850
+ ...(handoffEnv ? { env: handoffEnv } : {}),
851
+ handoffState: provider.exportHandoffState(),
852
+ });
853
+ return formatBilingualInline(
854
+ "当前 PrivateClaw 会话已转入后台。可使用 `openclaw privateclaw sessions` 查看,必要时用 `openclaw privateclaw sessions kill <sessionId>` 终止。",
855
+ "The current PrivateClaw session is now running in the background. Use `openclaw privateclaw sessions` to inspect it, and `openclaw privateclaw sessions kill <sessionId>` if you need to terminate it.",
856
+ );
615
857
  } catch (error) {
616
858
  provider.resumeReconnectsAfterHandoffFailure();
617
859
  throw error;
@@ -636,17 +878,62 @@ class PrivateClawPluginRuntime {
636
878
  });
637
879
  }
638
880
 
881
+ async closeManagedSession(sessionId: string) {
882
+ return closeManagedSessionFromStateDir({
883
+ stateDir: this.ensureStateDir(),
884
+ sessionId,
885
+ reason: "operator_terminated",
886
+ });
887
+ }
888
+
889
+ async printManagedSessionQr(
890
+ sessionId: string,
891
+ params?: {
892
+ notifyParticipants?: boolean;
893
+ openInBrowser?: boolean;
894
+ writeLine?: (line: string) => void;
895
+ },
896
+ ) {
897
+ const result = await getManagedSessionQrBundleFromStateDir({
898
+ stateDir: this.ensureStateDir(),
899
+ sessionId,
900
+ ...(params?.notifyParticipants ? { notifyParticipants: true } : {}),
901
+ });
902
+ if (isManagedSessionQrLegacyResult(result)) {
903
+ for (const line of buildManagedSessionQrLegacyLines({
904
+ result,
905
+ ...(params?.notifyParticipants ? { notifyParticipants: true } : {}),
906
+ })) {
907
+ (params?.writeLine ?? ((line: string) => console.log(line)))(line);
908
+ }
909
+ if (params?.openInBrowser) {
910
+ await openInBrowserPreview(pathToFileURL(result.legacyPngPath).href);
911
+ }
912
+ return result;
913
+ }
914
+ const bundle = await renderInviteBundleOutput(result.bundle, {
915
+ qrMediaDir: this.getMediaDir(),
916
+ ...(params?.openInBrowser ? { openInBrowser: true } : {}),
917
+ ...(params?.writeLine ? { writeLine: params.writeLine } : {}),
918
+ });
919
+ return {
920
+ ...result,
921
+ bundle,
922
+ };
923
+ }
924
+
639
925
  async dispose(): Promise<void> {
640
926
  if (this.controlServer) {
641
927
  await this.controlServer.stop();
642
928
  this.controlServer = undefined;
643
929
  }
644
- if (!this.provider) {
645
- return;
930
+ const providers = [...this.providerEntries.values()]
931
+ .map((entry) => entry.provider)
932
+ .filter((provider): provider is PrivateClawProvider => provider != null);
933
+ this.providerEntries.clear();
934
+ for (const provider of providers) {
935
+ await provider.dispose();
646
936
  }
647
-
648
- await this.provider.dispose();
649
- this.provider = undefined;
650
937
  }
651
938
  }
652
939
 
@@ -717,24 +1004,27 @@ function createPluginDefinition(
717
1004
  privateclaw
718
1005
  .command("pair")
719
1006
  .description(PRIVATECLAW_CLI_PAIR_DESCRIPTION)
720
- .option("--ttl-ms <ms>", PRIVATECLAW_CLI_TTL_OPTION_DESCRIPTION)
721
- .option("--label <label>", PRIVATECLAW_CLI_LABEL_OPTION_DESCRIPTION)
722
- .option("--group", PRIVATECLAW_CLI_GROUP_OPTION_DESCRIPTION)
723
- .option("--print-only", PRIVATECLAW_CLI_PRINT_ONLY_OPTION_DESCRIPTION)
724
- .option("--open", PRIVATECLAW_CLI_OPEN_OPTION_DESCRIPTION)
725
- .option("--foreground", PRIVATECLAW_CLI_FOREGROUND_OPTION_DESCRIPTION)
726
- .action(async (rawOptions: unknown) => {
727
- const options = normalizePairCliOptions(rawOptions);
728
- const ttlMs = parsePositiveIntegerFlag(options.ttlMs, "--ttl-ms");
729
- const label = readString(options.label);
730
- const pairParams = {
731
- ...(typeof ttlMs === "number" ? { ttlMs } : {}),
732
- ...(label ? { label } : {}),
733
- ...(options.group ? { groupMode: true } : {}),
734
- ...(typeof options.printOnly === "boolean"
735
- ? { printOnly: options.printOnly }
736
- : {}),
737
- ...(typeof options.open === "boolean"
1007
+ .option("--ttl-ms <ms>", PRIVATECLAW_CLI_TTL_OPTION_DESCRIPTION)
1008
+ .option("--label <label>", PRIVATECLAW_CLI_LABEL_OPTION_DESCRIPTION)
1009
+ .option("-r, --relay <url>", PRIVATECLAW_CLI_RELAY_OPTION_DESCRIPTION)
1010
+ .option("--group", PRIVATECLAW_CLI_GROUP_OPTION_DESCRIPTION)
1011
+ .option("--print-only", PRIVATECLAW_CLI_PRINT_ONLY_OPTION_DESCRIPTION)
1012
+ .option("--open", PRIVATECLAW_CLI_OPEN_OPTION_DESCRIPTION)
1013
+ .option("--foreground", PRIVATECLAW_CLI_FOREGROUND_OPTION_DESCRIPTION)
1014
+ .action(async (rawOptions: unknown) => {
1015
+ const options = normalizePairCliOptions(rawOptions);
1016
+ const ttlMs = parsePositiveIntegerFlag(options.ttlMs, "--ttl-ms");
1017
+ const label = readString(options.label);
1018
+ const relayBaseUrl = readString(options.relay);
1019
+ const pairParams = {
1020
+ ...(typeof ttlMs === "number" ? { ttlMs } : {}),
1021
+ ...(label ? { label } : {}),
1022
+ ...(relayBaseUrl ? { relayBaseUrl } : {}),
1023
+ ...(options.group ? { groupMode: true } : {}),
1024
+ ...(typeof options.printOnly === "boolean"
1025
+ ? { printOnly: options.printOnly }
1026
+ : {}),
1027
+ ...(typeof options.open === "boolean"
738
1028
  ? { openInBrowser: options.open }
739
1029
  : {}),
740
1030
  writeLine: (line: string) => {
@@ -751,7 +1041,7 @@ function createPluginDefinition(
751
1041
  await runtime.runBackgroundPairSession(pairParams);
752
1042
  });
753
1043
 
754
- privateclaw
1044
+ const sessions = privateclaw
755
1045
  .command("sessions")
756
1046
  .description(PRIVATECLAW_CLI_SESSIONS_DESCRIPTION)
757
1047
  .action(async () => {
@@ -761,6 +1051,80 @@ function createPluginDefinition(
761
1051
  }
762
1052
  });
763
1053
 
1054
+ sessions
1055
+ .command("qr")
1056
+ .description(PRIVATECLAW_CLI_SESSIONS_QR_DESCRIPTION)
1057
+ .argument("<sessionId>")
1058
+ .option("--open", PRIVATECLAW_CLI_OPEN_OPTION_DESCRIPTION)
1059
+ .option("--notify", PRIVATECLAW_CLI_NOTIFY_OPTION_DESCRIPTION)
1060
+ .action(async (sessionIdRaw: unknown, rawOptions: unknown) => {
1061
+ try {
1062
+ const sessionId = readString(sessionIdRaw);
1063
+ if (!sessionId) {
1064
+ throw new Error(
1065
+ formatBilingualInline(
1066
+ "`sessions qr` 需要提供 sessionId。",
1067
+ "`sessions qr` requires a sessionId.",
1068
+ ),
1069
+ );
1070
+ }
1071
+ const options = normalizeSessionsQrCliOptions(rawOptions);
1072
+ const result = await runtime.printManagedSessionQr(sessionId, {
1073
+ ...(options.notify ? { notifyParticipants: true } : {}),
1074
+ ...(options.open ? { openInBrowser: true } : {}),
1075
+ writeLine: (line: string) => {
1076
+ console.log(line);
1077
+ },
1078
+ });
1079
+ if (options.notify && !isManagedSessionQrLegacyResult(result)) {
1080
+ console.log(
1081
+ formatBilingualInline(
1082
+ `已向会话 ${result.session.sessionId} 中的 ${result.session.participantCount} 位参与者推送二维码。`,
1083
+ `Sent the QR code to ${result.session.participantCount} participant(s) in session ${result.session.sessionId}.`,
1084
+ ),
1085
+ );
1086
+ } else if (options.notify && isManagedSessionQrLegacyResult(result)) {
1087
+ process.exitCode = 1;
1088
+ }
1089
+ } catch (error) {
1090
+ console.error(formatCommandError(error));
1091
+ process.exitCode = 1;
1092
+ }
1093
+ });
1094
+
1095
+ sessions
1096
+ .command("kill")
1097
+ .description(PRIVATECLAW_CLI_SESSIONS_KILL_DESCRIPTION)
1098
+ .argument("<sessionId>")
1099
+ .action(async (sessionIdRaw: unknown) => {
1100
+ try {
1101
+ const sessionId = readString(sessionIdRaw);
1102
+ if (!sessionId) {
1103
+ throw new Error(
1104
+ formatBilingualInline(
1105
+ "`sessions kill` 需要提供 sessionId。",
1106
+ "`sessions kill` requires a sessionId.",
1107
+ ),
1108
+ );
1109
+ }
1110
+ const result = await runtime.closeManagedSession(sessionId);
1111
+ console.log(
1112
+ result.terminatedHost
1113
+ ? formatBilingualInline(
1114
+ `会话 ${result.session.sessionId} 已通过终止 legacy host ${result.host.kind}#${result.host.pid} 停止。`,
1115
+ `Session ${result.session.sessionId} was stopped by terminating the legacy host ${result.host.kind}#${result.host.pid}.`,
1116
+ )
1117
+ : formatBilingualInline(
1118
+ `会话 ${result.session.sessionId} 已终止。`,
1119
+ `Session ${result.session.sessionId} has been terminated.`,
1120
+ ),
1121
+ );
1122
+ } catch (error) {
1123
+ console.error(formatCommandError(error));
1124
+ process.exitCode = 1;
1125
+ }
1126
+ });
1127
+
764
1128
  privateclaw
765
1129
  .command("kick")
766
1130
  .description(PRIVATECLAW_CLI_KICK_DESCRIPTION)
@@ -796,7 +1160,13 @@ export function createOpenClawCompatiblePlugin(
796
1160
  options: PrivateClawProviderOptions & { defaultTtlMs?: number },
797
1161
  ): OpenClawExtensionPluginCompat {
798
1162
  return createPluginDefinition(
799
- () => new PrivateClawPluginRuntime(options, options.defaultTtlMs),
1163
+ () =>
1164
+ new PrivateClawPluginRuntime(
1165
+ options,
1166
+ options.defaultTtlMs,
1167
+ undefined,
1168
+ inferRelayBaseUrlFromAppWsUrl(options.appWsUrl),
1169
+ ),
800
1170
  );
801
1171
  }
802
1172
 
@@ -808,6 +1178,7 @@ export function createPrivateClawPlugin(): OpenClawExtensionPluginCompat {
808
1178
  resolved.options,
809
1179
  resolved.defaultTtlMs,
810
1180
  buildDaemonEnvFromPluginConfig(pluginConfig),
1181
+ pluginConfig.relayBaseUrl,
811
1182
  );
812
1183
  });
813
1184
  }