@privateclaw/privateclaw 0.1.13 → 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,18 +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,
49
58
  PRIVATECLAW_CLI_RELAY_OPTION_DESCRIPTION,
50
59
  PRIVATECLAW_CLI_ROOT_DESCRIPTION,
51
60
  PRIVATECLAW_CLI_SESSIONS_DESCRIPTION,
61
+ PRIVATECLAW_CLI_SESSIONS_KILL_DESCRIPTION,
62
+ PRIVATECLAW_CLI_SESSIONS_QR_DESCRIPTION,
52
63
  PRIVATECLAW_CLI_TTL_OPTION_DESCRIPTION,
53
64
  PRIVATECLAW_COMMAND_DESCRIPTION,
54
65
  PRIVATECLAW_INVITE_URI_LABEL,
@@ -114,6 +125,11 @@ interface PrivateClawPairCliOptions {
114
125
  foreground?: boolean;
115
126
  }
116
127
 
128
+ interface PrivateClawSessionsQrCliOptions {
129
+ open?: boolean;
130
+ notify?: boolean;
131
+ }
132
+
117
133
  const DEFAULT_PROVIDER_LABEL = "PrivateClaw";
118
134
  const DEFAULT_BRIDGE_MODE: PrivateClawBridgeMode = "openclaw-agent";
119
135
  const QQ_INLINE_IMAGE_REPLY_CHANNELS = new Set(["qqbot", "qq", "qqguild", "qq-guild"]);
@@ -354,6 +370,20 @@ function normalizePairCliOptions(raw: unknown): PrivateClawPairCliOptions {
354
370
  };
355
371
  }
356
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
+
357
387
  function parsePrivateClawCommandArgs(raw: string | undefined): {
358
388
  groupMode?: boolean;
359
389
  relayBaseUrl?: string;
@@ -624,6 +654,46 @@ class PrivateClawPluginRuntime {
624
654
  throw new Error(`Unknown PrivateClaw session: ${sessionId}`);
625
655
  }
626
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
+ }
673
+ }
674
+ throw new Error(`Unknown PrivateClaw session: ${sessionId}`);
675
+ }
676
+
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}`);
695
+ }
696
+
627
697
  private async ensureControlServer(
628
698
  kind: PrivateClawControlHostKind,
629
699
  ): Promise<void> {
@@ -633,6 +703,10 @@ class PrivateClawPluginRuntime {
633
703
  this.controlServer = new PrivateClawSessionControlServer({
634
704
  provider: {
635
705
  listManagedSessions: () => this.listLocalManagedSessions(),
706
+ getSessionQrBundle: (sessionId, params) =>
707
+ this.getLocalManagedSessionQrBundle(sessionId, params),
708
+ closeManagedSession: (sessionId, reason) =>
709
+ this.closeLocalManagedSession(sessionId, reason),
636
710
  kickGroupParticipant: (sessionId, appId, reason) =>
637
711
  this.kickLocalManagedParticipant(sessionId, appId, reason),
638
712
  },
@@ -720,6 +794,12 @@ class PrivateClawPluginRuntime {
720
794
  ...(params?.openInBrowser === true ? { openInBrowser: true } : {}),
721
795
  });
722
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
+ );
723
803
  return bundle;
724
804
  }
725
805
 
@@ -761,19 +841,19 @@ class PrivateClawPluginRuntime {
761
841
  handoffToBackground: async () => {
762
842
  provider.suppressReconnectsForHandoff();
763
843
  try {
764
- await handoffForegroundPairToBackground({
765
- cliModuleUrl: new URL(
766
- import.meta.url.endsWith(".ts") ? "./cli.ts" : "./cli.js",
767
- import.meta.url,
844
+ await handoffForegroundPairToBackground({
845
+ cliModuleUrl: new URL(
846
+ import.meta.url.endsWith(".ts") ? "./cli.ts" : "./cli.js",
847
+ import.meta.url,
768
848
  ).href,
769
849
  stateDir: this.ensureStateDir(),
770
850
  ...(handoffEnv ? { env: handoffEnv } : {}),
771
851
  handoffState: provider.exportHandoffState(),
772
852
  });
773
- return formatBilingualInline(
774
- "当前 PrivateClaw 会话已转入后台。可使用 `openclaw privateclaw sessions` 查看。",
775
- "The current PrivateClaw session is now running in the background. Use `openclaw privateclaw sessions` to inspect it.",
776
- );
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
+ );
777
857
  } catch (error) {
778
858
  provider.resumeReconnectsAfterHandoffFailure();
779
859
  throw error;
@@ -798,6 +878,50 @@ class PrivateClawPluginRuntime {
798
878
  });
799
879
  }
800
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
+
801
925
  async dispose(): Promise<void> {
802
926
  if (this.controlServer) {
803
927
  await this.controlServer.stop();
@@ -917,7 +1041,7 @@ function createPluginDefinition(
917
1041
  await runtime.runBackgroundPairSession(pairParams);
918
1042
  });
919
1043
 
920
- privateclaw
1044
+ const sessions = privateclaw
921
1045
  .command("sessions")
922
1046
  .description(PRIVATECLAW_CLI_SESSIONS_DESCRIPTION)
923
1047
  .action(async () => {
@@ -927,6 +1051,80 @@ function createPluginDefinition(
927
1051
  }
928
1052
  });
929
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
+
930
1128
  privateclaw
931
1129
  .command("kick")
932
1130
  .description(PRIVATECLAW_CLI_KICK_DESCRIPTION)
@@ -123,6 +123,35 @@ export function printPairInviteBundle(
123
123
  writeLine(bundle.qrTerminal);
124
124
  }
125
125
 
126
+ export async function renderInviteBundleOutput(
127
+ bundle: PrivateClawInviteBundle,
128
+ params?: {
129
+ qrMediaDir?: string;
130
+ openInBrowser?: boolean;
131
+ writeLine?: (line: string) => void;
132
+ },
133
+ ): Promise<PrivateClawInviteBundle> {
134
+ const mediaDir = params?.qrMediaDir ?? resolvePrivateClawMediaDir();
135
+ const qrPng = await writeInviteQrPng(bundle, mediaDir);
136
+ const renderedBundle: PrivateClawInviteBundle = {
137
+ ...bundle,
138
+ qrPngPath: qrPng.pngPath,
139
+ };
140
+
141
+ printPairInviteBundle(renderedBundle, params?.writeLine ?? ((line) => console.log(line)));
142
+
143
+ if (params?.openInBrowser) {
144
+ const preview = await writeInviteQrPreviewHtml(
145
+ renderedBundle,
146
+ mediaDir,
147
+ qrPng.pngPath,
148
+ );
149
+ await openInBrowserPreview(preview.previewFileUrl);
150
+ }
151
+
152
+ return renderedBundle;
153
+ }
154
+
126
155
  export async function runPairSession({
127
156
  provider,
128
157
  ttlMs,
@@ -136,32 +165,18 @@ export async function runPairSession({
136
165
  console.log(line);
137
166
  },
138
167
  handoffToBackground,
139
- }: PairSessionOptions): Promise<PrivateClawInviteBundle> {
168
+ }: PairSessionOptions): Promise<PrivateClawInviteBundle> {
140
169
  try {
141
170
  const inviteBundle = await provider.createInviteBundle({
142
171
  ...(typeof ttlMs === "number" ? { ttlMs } : {}),
143
172
  ...(label ? { label: label.trim() } : {}),
144
173
  ...(groupMode ? { groupMode: true } : {}),
145
174
  });
146
- const qrPng = await writeInviteQrPng(
147
- inviteBundle,
148
- qrMediaDir ?? resolvePrivateClawMediaDir(),
149
- );
150
- const bundle: PrivateClawInviteBundle = {
151
- ...inviteBundle,
152
- qrPngPath: qrPng.pngPath,
153
- };
154
-
155
- printPairInviteBundle(bundle, writeLine);
156
-
157
- if (openInBrowser) {
158
- const preview = await writeInviteQrPreviewHtml(
159
- bundle,
160
- qrMediaDir ?? resolvePrivateClawMediaDir(),
161
- qrPng.pngPath,
162
- );
163
- await openInBrowserPreview(preview.previewFileUrl);
164
- }
175
+ const bundle = await renderInviteBundleOutput(inviteBundle, {
176
+ ...(qrMediaDir ? { qrMediaDir } : {}),
177
+ ...(openInBrowser ? { openInBrowser: true } : {}),
178
+ writeLine,
179
+ });
165
180
 
166
181
  if (printOnly) {
167
182
  await provider.dispose();
@@ -221,7 +236,7 @@ export async function runPairSession({
221
236
  }
222
237
  }
223
238
 
224
- async function openInBrowserPreview(target: string): Promise<void> {
239
+ export async function openInBrowserPreview(target: string): Promise<void> {
225
240
  const command =
226
241
  process.platform === "win32"
227
242
  ? {
package/src/provider.ts CHANGED
@@ -536,6 +536,36 @@ export class PrivateClawProvider {
536
536
  return [...this.sessions.values()].map(toManagedSessionSnapshot);
537
537
  }
538
538
 
539
+ async getSessionQrBundle(
540
+ sessionId: string,
541
+ params?: { notifyParticipants?: boolean },
542
+ ): Promise<PrivateClawInviteBundle> {
543
+ const session = this.requireSession(sessionId);
544
+ const bundle = await this.buildInviteBundleForInvite(session.invite);
545
+
546
+ if (params?.notifyParticipants) {
547
+ const qrAttachment = await this.buildSessionQrAttachmentFromBundle(bundle);
548
+ await this.sendAssistantMessage(sessionId, {
549
+ text: buildSessionQrMessage(session),
550
+ attachments: [qrAttachment],
551
+ storeHistory: false,
552
+ });
553
+ }
554
+
555
+ return bundle;
556
+ }
557
+
558
+ async closeManagedSession(
559
+ sessionId: string,
560
+ reason = "operator_terminated",
561
+ ): Promise<PrivateClawManagedSession> {
562
+ const session = this.requireSession(sessionId);
563
+ const snapshot = toManagedSessionSnapshot(session);
564
+ await this.relayClient.closeSession(sessionId, reason);
565
+ this.deleteSession(sessionId);
566
+ return snapshot;
567
+ }
568
+
539
569
  exportHandoffState(): PrivateClawProviderHandoffState {
540
570
  return {
541
571
  providerId: this.relayClient.getProviderId(),
@@ -1612,8 +1642,13 @@ export class PrivateClawProvider {
1612
1642
  }
1613
1643
 
1614
1644
  private async buildSessionQrAttachment(sessionId: string): Promise<PrivateClawAttachment> {
1615
- const session = this.requireSession(sessionId);
1616
- const bundle = await this.buildInviteBundleForInvite(session.invite);
1645
+ const bundle = await this.getSessionQrBundle(sessionId);
1646
+ return this.buildSessionQrAttachmentFromBundle(bundle);
1647
+ }
1648
+
1649
+ private async buildSessionQrAttachmentFromBundle(
1650
+ bundle: PrivateClawInviteBundle,
1651
+ ): Promise<PrivateClawAttachment> {
1617
1652
  const pngBuffer = await QRCode.toBuffer(bundle.inviteUri, {
1618
1653
  type: "png",
1619
1654
  errorCorrectionLevel: PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL,