@privateclaw/privateclaw 0.1.13 → 0.1.15

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,12 @@ 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
+ closeManagedSessionsFromStateDir,
38
+ closeManagedSessionFromStateDir,
39
+ getManagedSessionQrBundleFromStateDir,
40
+ isManagedSessionQrLegacyResult,
33
41
  kickManagedParticipantFromStateDir,
34
42
  listManagedSessionsFromStateDir,
35
43
  PrivateClawSessionControlServer,
@@ -37,18 +45,23 @@ import {
37
45
  type PrivateClawControlHostKind,
38
46
  } from "./session-control.js";
39
47
  import {
48
+ buildPrivateClawBackgroundDaemonReminder,
40
49
  buildPrivateClawCommandErrorMessage,
41
50
  formatBilingualInline,
42
51
  PRIVATECLAW_CLI_FOREGROUND_OPTION_DESCRIPTION,
43
52
  PRIVATECLAW_CLI_GROUP_OPTION_DESCRIPTION,
44
53
  PRIVATECLAW_CLI_KICK_DESCRIPTION,
45
54
  PRIVATECLAW_CLI_LABEL_OPTION_DESCRIPTION,
55
+ PRIVATECLAW_CLI_NOTIFY_OPTION_DESCRIPTION,
46
56
  PRIVATECLAW_CLI_OPEN_OPTION_DESCRIPTION,
47
57
  PRIVATECLAW_CLI_PAIR_DESCRIPTION,
48
58
  PRIVATECLAW_CLI_PRINT_ONLY_OPTION_DESCRIPTION,
49
59
  PRIVATECLAW_CLI_RELAY_OPTION_DESCRIPTION,
50
60
  PRIVATECLAW_CLI_ROOT_DESCRIPTION,
51
61
  PRIVATECLAW_CLI_SESSIONS_DESCRIPTION,
62
+ PRIVATECLAW_CLI_SESSIONS_KILL_DESCRIPTION,
63
+ PRIVATECLAW_CLI_SESSIONS_KILLALL_DESCRIPTION,
64
+ PRIVATECLAW_CLI_SESSIONS_QR_DESCRIPTION,
52
65
  PRIVATECLAW_CLI_TTL_OPTION_DESCRIPTION,
53
66
  PRIVATECLAW_COMMAND_DESCRIPTION,
54
67
  PRIVATECLAW_INVITE_URI_LABEL,
@@ -114,6 +127,11 @@ interface PrivateClawPairCliOptions {
114
127
  foreground?: boolean;
115
128
  }
116
129
 
130
+ interface PrivateClawSessionsQrCliOptions {
131
+ open?: boolean;
132
+ notify?: boolean;
133
+ }
134
+
117
135
  const DEFAULT_PROVIDER_LABEL = "PrivateClaw";
118
136
  const DEFAULT_BRIDGE_MODE: PrivateClawBridgeMode = "openclaw-agent";
119
137
  const QQ_INLINE_IMAGE_REPLY_CHANNELS = new Set(["qqbot", "qq", "qqguild", "qq-guild"]);
@@ -354,6 +372,20 @@ function normalizePairCliOptions(raw: unknown): PrivateClawPairCliOptions {
354
372
  };
355
373
  }
356
374
 
375
+ function normalizeSessionsQrCliOptions(
376
+ raw: unknown,
377
+ ): PrivateClawSessionsQrCliOptions {
378
+ if (!raw || typeof raw !== "object") {
379
+ return {};
380
+ }
381
+
382
+ const options = raw as Record<string, unknown>;
383
+ return {
384
+ ...(typeof options.open === "boolean" ? { open: options.open } : {}),
385
+ ...(typeof options.notify === "boolean" ? { notify: options.notify } : {}),
386
+ };
387
+ }
388
+
357
389
  function parsePrivateClawCommandArgs(raw: string | undefined): {
358
390
  groupMode?: boolean;
359
391
  relayBaseUrl?: string;
@@ -624,6 +656,46 @@ class PrivateClawPluginRuntime {
624
656
  throw new Error(`Unknown PrivateClaw session: ${sessionId}`);
625
657
  }
626
658
 
659
+ private async getLocalManagedSessionQrBundle(
660
+ sessionId: string,
661
+ params?: { notifyParticipants?: boolean },
662
+ ): Promise<PrivateClawInviteBundle> {
663
+ for (const entry of this.providerEntries.values()) {
664
+ const provider = entry.provider;
665
+ if (!provider) {
666
+ continue;
667
+ }
668
+ if (
669
+ provider
670
+ .listManagedSessions()
671
+ .some((session) => session.sessionId === sessionId)
672
+ ) {
673
+ return provider.getSessionQrBundle(sessionId, params);
674
+ }
675
+ }
676
+ throw new Error(`Unknown PrivateClaw session: ${sessionId}`);
677
+ }
678
+
679
+ private async closeLocalManagedSession(
680
+ sessionId: string,
681
+ reason = "operator_terminated",
682
+ ): Promise<PrivateClawManagedSession> {
683
+ for (const entry of this.providerEntries.values()) {
684
+ const provider = entry.provider;
685
+ if (!provider) {
686
+ continue;
687
+ }
688
+ if (
689
+ provider
690
+ .listManagedSessions()
691
+ .some((session) => session.sessionId === sessionId)
692
+ ) {
693
+ return provider.closeManagedSession(sessionId, reason);
694
+ }
695
+ }
696
+ throw new Error(`Unknown PrivateClaw session: ${sessionId}`);
697
+ }
698
+
627
699
  private async ensureControlServer(
628
700
  kind: PrivateClawControlHostKind,
629
701
  ): Promise<void> {
@@ -633,6 +705,10 @@ class PrivateClawPluginRuntime {
633
705
  this.controlServer = new PrivateClawSessionControlServer({
634
706
  provider: {
635
707
  listManagedSessions: () => this.listLocalManagedSessions(),
708
+ getSessionQrBundle: (sessionId, params) =>
709
+ this.getLocalManagedSessionQrBundle(sessionId, params),
710
+ closeManagedSession: (sessionId, reason) =>
711
+ this.closeLocalManagedSession(sessionId, reason),
636
712
  kickGroupParticipant: (sessionId, appId, reason) =>
637
713
  this.kickLocalManagedParticipant(sessionId, appId, reason),
638
714
  },
@@ -720,6 +796,12 @@ class PrivateClawPluginRuntime {
720
796
  ...(params?.openInBrowser === true ? { openInBrowser: true } : {}),
721
797
  });
722
798
  printPairInviteBundle(bundle, params?.writeLine ?? ((line) => console.log(line)));
799
+ (params?.writeLine ?? ((line: string) => console.log(line)))(
800
+ buildPrivateClawBackgroundDaemonReminder(
801
+ "openclaw privateclaw",
802
+ bundle.invite.sessionId,
803
+ ),
804
+ );
723
805
  return bundle;
724
806
  }
725
807
 
@@ -761,19 +843,19 @@ class PrivateClawPluginRuntime {
761
843
  handoffToBackground: async () => {
762
844
  provider.suppressReconnectsForHandoff();
763
845
  try {
764
- await handoffForegroundPairToBackground({
765
- cliModuleUrl: new URL(
766
- import.meta.url.endsWith(".ts") ? "./cli.ts" : "./cli.js",
767
- import.meta.url,
846
+ await handoffForegroundPairToBackground({
847
+ cliModuleUrl: new URL(
848
+ import.meta.url.endsWith(".ts") ? "./cli.ts" : "./cli.js",
849
+ import.meta.url,
768
850
  ).href,
769
851
  stateDir: this.ensureStateDir(),
770
852
  ...(handoffEnv ? { env: handoffEnv } : {}),
771
853
  handoffState: provider.exportHandoffState(),
772
854
  });
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
- );
855
+ return formatBilingualInline(
856
+ "当前 PrivateClaw 会话已转入后台。可使用 `openclaw privateclaw sessions` 查看,必要时用 `openclaw privateclaw sessions kill <sessionId>` 终止。",
857
+ "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.",
858
+ );
777
859
  } catch (error) {
778
860
  provider.resumeReconnectsAfterHandoffFailure();
779
861
  throw error;
@@ -798,6 +880,58 @@ class PrivateClawPluginRuntime {
798
880
  });
799
881
  }
800
882
 
883
+ async closeManagedSession(sessionId: string) {
884
+ return closeManagedSessionFromStateDir({
885
+ stateDir: this.ensureStateDir(),
886
+ sessionId,
887
+ reason: "operator_terminated",
888
+ });
889
+ }
890
+
891
+ async closeBackgroundManagedSessions() {
892
+ return closeManagedSessionsFromStateDir({
893
+ stateDir: this.ensureStateDir(),
894
+ hostKinds: ["pair-daemon"],
895
+ reason: "operator_terminated_all",
896
+ });
897
+ }
898
+
899
+ async printManagedSessionQr(
900
+ sessionId: string,
901
+ params?: {
902
+ notifyParticipants?: boolean;
903
+ openInBrowser?: boolean;
904
+ writeLine?: (line: string) => void;
905
+ },
906
+ ) {
907
+ const result = await getManagedSessionQrBundleFromStateDir({
908
+ stateDir: this.ensureStateDir(),
909
+ sessionId,
910
+ ...(params?.notifyParticipants ? { notifyParticipants: true } : {}),
911
+ });
912
+ if (isManagedSessionQrLegacyResult(result)) {
913
+ for (const line of buildManagedSessionQrLegacyLines({
914
+ result,
915
+ ...(params?.notifyParticipants ? { notifyParticipants: true } : {}),
916
+ })) {
917
+ (params?.writeLine ?? ((line: string) => console.log(line)))(line);
918
+ }
919
+ if (params?.openInBrowser) {
920
+ await openInBrowserPreview(pathToFileURL(result.legacyPngPath).href);
921
+ }
922
+ return result;
923
+ }
924
+ const bundle = await renderInviteBundleOutput(result.bundle, {
925
+ qrMediaDir: this.getMediaDir(),
926
+ ...(params?.openInBrowser ? { openInBrowser: true } : {}),
927
+ ...(params?.writeLine ? { writeLine: params.writeLine } : {}),
928
+ });
929
+ return {
930
+ ...result,
931
+ bundle,
932
+ };
933
+ }
934
+
801
935
  async dispose(): Promise<void> {
802
936
  if (this.controlServer) {
803
937
  await this.controlServer.stop();
@@ -917,7 +1051,7 @@ function createPluginDefinition(
917
1051
  await runtime.runBackgroundPairSession(pairParams);
918
1052
  });
919
1053
 
920
- privateclaw
1054
+ const sessions = privateclaw
921
1055
  .command("sessions")
922
1056
  .description(PRIVATECLAW_CLI_SESSIONS_DESCRIPTION)
923
1057
  .action(async () => {
@@ -927,6 +1061,139 @@ function createPluginDefinition(
927
1061
  }
928
1062
  });
929
1063
 
1064
+ sessions
1065
+ .command("qr")
1066
+ .description(PRIVATECLAW_CLI_SESSIONS_QR_DESCRIPTION)
1067
+ .argument("<sessionId>")
1068
+ .option("--open", PRIVATECLAW_CLI_OPEN_OPTION_DESCRIPTION)
1069
+ .option("--notify", PRIVATECLAW_CLI_NOTIFY_OPTION_DESCRIPTION)
1070
+ .action(async (sessionIdRaw: unknown, rawOptions: unknown) => {
1071
+ try {
1072
+ const sessionId = readString(sessionIdRaw);
1073
+ if (!sessionId) {
1074
+ throw new Error(
1075
+ formatBilingualInline(
1076
+ "`sessions qr` 需要提供 sessionId。",
1077
+ "`sessions qr` requires a sessionId.",
1078
+ ),
1079
+ );
1080
+ }
1081
+ const options = normalizeSessionsQrCliOptions(rawOptions);
1082
+ const result = await runtime.printManagedSessionQr(sessionId, {
1083
+ ...(options.notify ? { notifyParticipants: true } : {}),
1084
+ ...(options.open ? { openInBrowser: true } : {}),
1085
+ writeLine: (line: string) => {
1086
+ console.log(line);
1087
+ },
1088
+ });
1089
+ if (options.notify && !isManagedSessionQrLegacyResult(result)) {
1090
+ console.log(
1091
+ formatBilingualInline(
1092
+ `已向会话 ${result.session.sessionId} 中的 ${result.session.participantCount} 位参与者推送二维码。`,
1093
+ `Sent the QR code to ${result.session.participantCount} participant(s) in session ${result.session.sessionId}.`,
1094
+ ),
1095
+ );
1096
+ } else if (options.notify && isManagedSessionQrLegacyResult(result)) {
1097
+ process.exitCode = 1;
1098
+ }
1099
+ } catch (error) {
1100
+ console.error(formatCommandError(error));
1101
+ process.exitCode = 1;
1102
+ }
1103
+ });
1104
+
1105
+ sessions
1106
+ .command("kill")
1107
+ .description(PRIVATECLAW_CLI_SESSIONS_KILL_DESCRIPTION)
1108
+ .argument("<sessionId>")
1109
+ .action(async (sessionIdRaw: unknown) => {
1110
+ try {
1111
+ const sessionId = readString(sessionIdRaw);
1112
+ if (!sessionId) {
1113
+ throw new Error(
1114
+ formatBilingualInline(
1115
+ "`sessions kill` 需要提供 sessionId。",
1116
+ "`sessions kill` requires a sessionId.",
1117
+ ),
1118
+ );
1119
+ }
1120
+ const result = await runtime.closeManagedSession(sessionId);
1121
+ console.log(
1122
+ result.terminatedHost
1123
+ ? formatBilingualInline(
1124
+ `会话 ${result.session.sessionId} 已通过终止 legacy host ${result.host.kind}#${result.host.pid} 停止。`,
1125
+ `Session ${result.session.sessionId} was stopped by terminating the legacy host ${result.host.kind}#${result.host.pid}.`,
1126
+ )
1127
+ : formatBilingualInline(
1128
+ `会话 ${result.session.sessionId} 已终止。`,
1129
+ `Session ${result.session.sessionId} has been terminated.`,
1130
+ ),
1131
+ );
1132
+ } catch (error) {
1133
+ console.error(formatCommandError(error));
1134
+ process.exitCode = 1;
1135
+ }
1136
+ });
1137
+
1138
+ sessions
1139
+ .command("killall")
1140
+ .description(PRIVATECLAW_CLI_SESSIONS_KILLALL_DESCRIPTION)
1141
+ .action(async () => {
1142
+ try {
1143
+ const result = await runtime.closeBackgroundManagedSessions();
1144
+ if (result.closed.length === 0 && result.failed.length === 0) {
1145
+ console.log(
1146
+ formatBilingualInline(
1147
+ "当前没有需要终止的后台 daemon 会话。",
1148
+ "There are no background daemon sessions to terminate.",
1149
+ ),
1150
+ );
1151
+ return;
1152
+ }
1153
+ if (result.closed.length > 0) {
1154
+ console.log(
1155
+ formatBilingualInline(
1156
+ `已终止 ${result.closed.length} 个后台 daemon 会话。`,
1157
+ `Terminated ${result.closed.length} background daemon session(s).`,
1158
+ ),
1159
+ );
1160
+ for (const item of result.closed) {
1161
+ console.log(
1162
+ item.terminatedHost
1163
+ ? formatBilingualInline(
1164
+ `- ${item.session.sessionId}:已通过终止 legacy host ${item.host.kind}#${item.host.pid} 停止。`,
1165
+ `- ${item.session.sessionId}: stopped by terminating the legacy host ${item.host.kind}#${item.host.pid}.`,
1166
+ )
1167
+ : formatBilingualInline(
1168
+ `- ${item.session.sessionId}:已终止。`,
1169
+ `- ${item.session.sessionId}: terminated.`,
1170
+ ),
1171
+ );
1172
+ }
1173
+ }
1174
+ if (result.failed.length > 0) {
1175
+ console.error(
1176
+ formatBilingualInline(
1177
+ `${result.failed.length} 个后台 daemon 会话终止失败。`,
1178
+ `${result.failed.length} background daemon session(s) failed to terminate.`,
1179
+ ),
1180
+ );
1181
+ for (const item of result.failed) {
1182
+ console.error(
1183
+ formatBilingualInline(
1184
+ `- ${item.session.sessionId}(${item.host.kind}#${item.host.pid}):${item.error}`,
1185
+ `- ${item.session.sessionId} (${item.host.kind}#${item.host.pid}): ${item.error}`,
1186
+ ),
1187
+ );
1188
+ }
1189
+ process.exitCode = 1;
1190
+ }
1191
+ } catch (error) {
1192
+ console.error(formatCommandError(error));
1193
+ process.exitCode = 1;
1194
+ }
1195
+ });
1196
+
930
1197
  privateclaw
931
1198
  .command("kick")
932
1199
  .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
  ? {