@privateclaw/privateclaw 0.1.11 → 0.1.12

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.
@@ -4,7 +4,8 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import test from "node:test";
6
6
  import { fileURLToPath } from "node:url";
7
- import { decodeInviteString } from "@privateclaw/protocol";
7
+ import { decodeInviteString, encryptPayload } from "@privateclaw/protocol";
8
+ import WebSocket from "ws";
8
9
  import { createRelayServer } from "../../../services/relay-server/src/relay-server.js";
9
10
  import { EchoBridge } from "./bridges/echo-bridge.js";
10
11
  import { privateClawConfigSchema } from "./compat/openclaw.js";
@@ -88,6 +89,10 @@ class FakeCliCommand {
88
89
  return this;
89
90
  }
90
91
 
92
+ argument(_spec: string): FakeCliCommand {
93
+ return this;
94
+ }
95
+
91
96
  option(_flags: string, _description?: string, _defaultValue?: string | boolean): FakeCliCommand {
92
97
  return this;
93
98
  }
@@ -341,3 +346,213 @@ test("privateclaw plugin local pair CLI defaults to the long session TTL", async
341
346
  const qrPng = await readFile(qrPath);
342
347
  assert.deepEqual(qrPng.subarray(0, PNG_SIGNATURE.length), PNG_SIGNATURE);
343
348
  });
349
+
350
+ test("privateclaw CLI can list and remove active group-session participants", async (t) => {
351
+ const relay = createRelayServer({
352
+ host: "127.0.0.1",
353
+ port: 0,
354
+ sessionTtlMs: 60_000,
355
+ frameCacheSize: 8,
356
+ });
357
+ const { port } = await relay.start();
358
+
359
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-cli-state-"));
360
+ t.after(async () => {
361
+ await rm(stateDir, { recursive: true, force: true });
362
+ await relay.stop();
363
+ });
364
+
365
+ const plugin = createOpenClawCompatiblePlugin({
366
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
367
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
368
+ bridge: new EchoBridge("OpenClaw bridge"),
369
+ });
370
+ const { api, getCli, getCommand, getService } = createMockApi();
371
+ plugin.register(api);
372
+
373
+ const service = getService();
374
+ await service.start({
375
+ config: {},
376
+ stateDir,
377
+ logger: api.logger,
378
+ });
379
+ t.after(async () => {
380
+ await service.stop?.({
381
+ config: {},
382
+ stateDir,
383
+ logger: api.logger,
384
+ });
385
+ });
386
+
387
+ const cli = getCli();
388
+ const root = new FakeCliCommand("root");
389
+ await cli.registrar({
390
+ program: root,
391
+ config: {},
392
+ logger: api.logger,
393
+ });
394
+
395
+ const privateclaw = root.children.get("privateclaw");
396
+ assert.ok(privateclaw, "plugin should register a top-level privateclaw command");
397
+ const sessions = privateclaw.children.get("sessions");
398
+ const kick = privateclaw.children.get("kick");
399
+ assert.ok(sessions?.actionHandler, "plugin should register the privateclaw sessions subcommand");
400
+ assert.ok(kick?.actionHandler, "plugin should register the privateclaw kick subcommand");
401
+
402
+ const command = getCommand();
403
+ const reply = await command.handler({
404
+ channel: "telegram",
405
+ senderId: "tester",
406
+ isAuthorizedSender: true,
407
+ commandBody: "/privateclaw group",
408
+ args: "group",
409
+ config: {},
410
+ });
411
+ const inviteUri = reply.text?.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
412
+ assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
413
+ const invite = decodeInviteString(inviteUri);
414
+
415
+ const appOneUrl = new URL(invite.appWsUrl);
416
+ appOneUrl.searchParams.set("appId", "app-one");
417
+ const appOne = new WebSocket(appOneUrl.toString());
418
+ const appOneAttached = new Promise<Record<string, unknown>>((resolve, reject) => {
419
+ appOne.once("message", (data) => resolve(JSON.parse(data.toString()) as Record<string, unknown>));
420
+ appOne.once("error", reject);
421
+ });
422
+ await new Promise<void>((resolve, reject) => {
423
+ appOne.once("open", () => resolve());
424
+ appOne.once("error", reject);
425
+ });
426
+ assert.equal((await appOneAttached).type, "relay:attached");
427
+ const appOneInitialFrames = new Promise<Record<string, unknown>[]>((resolve, reject) => {
428
+ const messages: Record<string, unknown>[] = [];
429
+ const onMessage = (data: unknown) => {
430
+ messages.push(JSON.parse(String(data)) as Record<string, unknown>);
431
+ if (messages.length === 3) {
432
+ appOne.off("message", onMessage);
433
+ resolve(messages);
434
+ }
435
+ };
436
+ appOne.on("message", onMessage);
437
+ appOne.once("error", reject);
438
+ });
439
+ appOne.send(
440
+ JSON.stringify({
441
+ type: "app:frame",
442
+ envelope: encryptPayload({
443
+ sessionId: invite.sessionId,
444
+ sessionKey: invite.sessionKey,
445
+ payload: {
446
+ kind: "client_hello",
447
+ appId: "app-one",
448
+ displayName: "SolarFox",
449
+ appVersion: "flutter-test",
450
+ deviceLabel: "Tester One",
451
+ sentAt: new Date().toISOString(),
452
+ },
453
+ }),
454
+ }),
455
+ );
456
+ await appOneInitialFrames;
457
+
458
+ const appTwoUrl = new URL(invite.appWsUrl);
459
+ appTwoUrl.searchParams.set("appId", "app-two");
460
+ const appTwo = new WebSocket(appTwoUrl.toString());
461
+ const appTwoAttached = new Promise<Record<string, unknown>>((resolve, reject) => {
462
+ appTwo.once("message", (data) => resolve(JSON.parse(data.toString()) as Record<string, unknown>));
463
+ appTwo.once("error", reject);
464
+ });
465
+ await new Promise<void>((resolve, reject) => {
466
+ appTwo.once("open", () => resolve());
467
+ appTwo.once("error", reject);
468
+ });
469
+ assert.equal((await appTwoAttached).type, "relay:attached");
470
+ const appTwoInitialFrames = new Promise<Record<string, unknown>[]>((resolve, reject) => {
471
+ const messages: Record<string, unknown>[] = [];
472
+ const onMessage = (data: unknown) => {
473
+ messages.push(JSON.parse(String(data)) as Record<string, unknown>);
474
+ if (messages.length === 3) {
475
+ appTwo.off("message", onMessage);
476
+ resolve(messages);
477
+ }
478
+ };
479
+ appTwo.on("message", onMessage);
480
+ appTwo.once("error", reject);
481
+ });
482
+ const appOneJoinFrames = new Promise<Record<string, unknown>[]>((resolve, reject) => {
483
+ const messages: Record<string, unknown>[] = [];
484
+ const onMessage = (data: unknown) => {
485
+ messages.push(JSON.parse(String(data)) as Record<string, unknown>);
486
+ if (messages.length === 2) {
487
+ appOne.off("message", onMessage);
488
+ resolve(messages);
489
+ }
490
+ };
491
+ appOne.on("message", onMessage);
492
+ appOne.once("error", reject);
493
+ });
494
+ appTwo.send(
495
+ JSON.stringify({
496
+ type: "app:frame",
497
+ envelope: encryptPayload({
498
+ sessionId: invite.sessionId,
499
+ sessionKey: invite.sessionKey,
500
+ payload: {
501
+ kind: "client_hello",
502
+ appId: "app-two",
503
+ displayName: "RiverCat",
504
+ appVersion: "flutter-test",
505
+ deviceLabel: "Tester Two",
506
+ sentAt: new Date().toISOString(),
507
+ },
508
+ }),
509
+ }),
510
+ );
511
+ await Promise.all([appTwoInitialFrames, appOneJoinFrames]);
512
+
513
+ const printed: string[] = [];
514
+ const originalLog = console.log;
515
+ console.log = (message?: unknown, ...optionalParams: unknown[]) => {
516
+ printed.push([message, ...optionalParams].map(String).join(" "));
517
+ };
518
+ t.after(() => {
519
+ console.log = originalLog;
520
+ });
521
+
522
+ await sessions.actionHandler?.();
523
+ assert.ok(printed.some((line) => line.includes(invite.sessionId)));
524
+ assert.ok(printed.some((line) => line.includes("type=group")));
525
+ assert.ok(printed.some((line) => line.includes("participants=2")));
526
+ assert.ok(printed.some((line) => line.includes("SolarFox (app-one)")));
527
+ assert.ok(printed.some((line) => line.includes("RiverCat (app-two)")));
528
+ printed.length = 0;
529
+
530
+ const appTwoClosed = new Promise<Record<string, unknown>>((resolve, reject) => {
531
+ const onMessage = (data: WebSocket.RawData) => {
532
+ const message = JSON.parse(data.toString()) as Record<string, unknown>;
533
+ if (message.type !== "relay:session_closed") {
534
+ return;
535
+ }
536
+ cleanup();
537
+ resolve(message);
538
+ };
539
+ const onError = (error: Error) => {
540
+ cleanup();
541
+ reject(error);
542
+ };
543
+ const cleanup = () => {
544
+ appTwo.off("message", onMessage);
545
+ appTwo.off("error", onError);
546
+ };
547
+ appTwo.on("message", onMessage);
548
+ appTwo.on("error", onError);
549
+ });
550
+ await kick.actionHandler?.(invite.sessionId, "app-two");
551
+ assert.ok(printed.some((line) => line.includes("RiverCat (app-two)")));
552
+ const closed = await appTwoClosed;
553
+ assert.equal(closed.type, "relay:session_closed");
554
+ assert.equal(closed.reason, "participant_removed");
555
+
556
+ appOne.close();
557
+ appTwo.close();
558
+ });
@@ -8,7 +8,15 @@ import {
8
8
  writeInviteQrPng,
9
9
  } from "./invite-qr-files.js";
10
10
  import { loadAvailableOpenClawCommands } from "./openclaw-command-discovery.js";
11
- import { parsePositiveIntegerFlag, runPairSession } from "./pair-session.js";
11
+ import {
12
+ parsePositiveIntegerFlag,
13
+ printPairInviteBundle,
14
+ runPairSession,
15
+ } from "./pair-session.js";
16
+ import {
17
+ handoffForegroundPairToBackground,
18
+ spawnBackgroundPairDaemon,
19
+ } from "./pair-daemon.js";
12
20
  import { WebhookBridge } from "./bridges/webhook-bridge.js";
13
21
  import {
14
22
  type OpenClawExtensionPluginCompat,
@@ -20,14 +28,26 @@ import {
20
28
  import { DEFAULT_SESSION_TTL_MS, PrivateClawProvider } from "./provider.js";
21
29
  import { DEFAULT_RELAY_BASE_URL } from "./relay-defaults.js";
22
30
  import { resolveRelayEndpoints } from "./relay-endpoints.js";
31
+ import {
32
+ buildManagedSessionsReportLines,
33
+ kickManagedParticipantFromStateDir,
34
+ listManagedSessionsFromStateDir,
35
+ PrivateClawSessionControlServer,
36
+ resolvePrivateClawStateDir,
37
+ type PrivateClawControlHostKind,
38
+ } from "./session-control.js";
23
39
  import {
24
40
  buildPrivateClawCommandErrorMessage,
41
+ formatBilingualInline,
42
+ PRIVATECLAW_CLI_FOREGROUND_OPTION_DESCRIPTION,
25
43
  PRIVATECLAW_CLI_GROUP_OPTION_DESCRIPTION,
44
+ PRIVATECLAW_CLI_KICK_DESCRIPTION,
26
45
  PRIVATECLAW_CLI_LABEL_OPTION_DESCRIPTION,
27
46
  PRIVATECLAW_CLI_OPEN_OPTION_DESCRIPTION,
28
47
  PRIVATECLAW_CLI_PAIR_DESCRIPTION,
29
48
  PRIVATECLAW_CLI_PRINT_ONLY_OPTION_DESCRIPTION,
30
49
  PRIVATECLAW_CLI_ROOT_DESCRIPTION,
50
+ PRIVATECLAW_CLI_SESSIONS_DESCRIPTION,
31
51
  PRIVATECLAW_CLI_TTL_OPTION_DESCRIPTION,
32
52
  PRIVATECLAW_COMMAND_DESCRIPTION,
33
53
  PRIVATECLAW_INVITE_URI_LABEL,
@@ -88,6 +108,7 @@ interface PrivateClawPairCliOptions {
88
108
  printOnly?: boolean;
89
109
  group?: boolean;
90
110
  open?: boolean;
111
+ foreground?: boolean;
91
112
  }
92
113
 
93
114
  const DEFAULT_PROVIDER_LABEL = "PrivateClaw";
@@ -322,6 +343,9 @@ function normalizePairCliOptions(raw: unknown): PrivateClawPairCliOptions {
322
343
  ...(typeof options.printOnly === "boolean" ? { printOnly: options.printOnly } : {}),
323
344
  ...(typeof options.group === "boolean" ? { group: options.group } : {}),
324
345
  ...(typeof options.open === "boolean" ? { open: options.open } : {}),
346
+ ...(typeof options.foreground === "boolean"
347
+ ? { foreground: options.foreground }
348
+ : {}),
325
349
  };
326
350
  }
327
351
 
@@ -370,21 +394,79 @@ function buildProviderOptions(
370
394
  };
371
395
  }
372
396
 
397
+ function buildDaemonEnvFromPluginConfig(
398
+ pluginConfig: ResolvedPrivateClawPluginConfig,
399
+ ): NodeJS.ProcessEnv {
400
+ return {
401
+ PRIVATECLAW_RELAY_BASE_URL: pluginConfig.relayBaseUrl,
402
+ PRIVATECLAW_BRIDGE_MODE: pluginConfig.bridgeMode,
403
+ PRIVATECLAW_PROVIDER_LABEL: pluginConfig.providerLabel,
404
+ ...(typeof pluginConfig.sessionTtlMs === "number"
405
+ ? { PRIVATECLAW_SESSION_TTL_MS: String(pluginConfig.sessionTtlMs) }
406
+ : {}),
407
+ ...(pluginConfig.welcomeMessage
408
+ ? { PRIVATECLAW_WELCOME_MESSAGE: pluginConfig.welcomeMessage }
409
+ : {}),
410
+ ...(pluginConfig.webhookUrl
411
+ ? { PRIVATECLAW_WEBHOOK_URL: pluginConfig.webhookUrl }
412
+ : {}),
413
+ ...(pluginConfig.webhookToken
414
+ ? { PRIVATECLAW_WEBHOOK_TOKEN: pluginConfig.webhookToken }
415
+ : {}),
416
+ ...(pluginConfig.echoPrefix
417
+ ? { PRIVATECLAW_ECHO_PREFIX: pluginConfig.echoPrefix }
418
+ : {}),
419
+ ...(pluginConfig.openclawAgentExecutable
420
+ ? { PRIVATECLAW_OPENCLAW_AGENT_BIN: pluginConfig.openclawAgentExecutable }
421
+ : {}),
422
+ ...(pluginConfig.openclawAgentId
423
+ ? { PRIVATECLAW_OPENCLAW_AGENT_ID: pluginConfig.openclawAgentId }
424
+ : {}),
425
+ ...(pluginConfig.openclawAgentChannel
426
+ ? { PRIVATECLAW_OPENCLAW_AGENT_CHANNEL: pluginConfig.openclawAgentChannel }
427
+ : {}),
428
+ ...(typeof pluginConfig.openclawAgentLocal === "boolean"
429
+ ? {
430
+ PRIVATECLAW_OPENCLAW_AGENT_LOCAL: pluginConfig.openclawAgentLocal
431
+ ? "true"
432
+ : "false",
433
+ }
434
+ : {}),
435
+ ...(pluginConfig.openclawAgentThinking
436
+ ? { PRIVATECLAW_OPENCLAW_AGENT_THINKING: pluginConfig.openclawAgentThinking }
437
+ : {}),
438
+ ...(typeof pluginConfig.openclawAgentTimeoutSeconds === "number"
439
+ ? {
440
+ PRIVATECLAW_OPENCLAW_AGENT_TIMEOUT_SECONDS: String(
441
+ pluginConfig.openclawAgentTimeoutSeconds,
442
+ ),
443
+ }
444
+ : {}),
445
+ };
446
+ }
447
+
373
448
  class PrivateClawPluginRuntime {
374
449
  private provider: PrivateClawProvider | undefined;
375
450
  private stateDir: string | undefined;
451
+ private controlServer: PrivateClawSessionControlServer | undefined;
376
452
 
377
453
  constructor(
378
454
  private readonly providerOptions: PrivateClawProviderOptions,
379
455
  private readonly defaultTtlMs: number = DEFAULT_SESSION_TTL_MS,
456
+ private readonly daemonEnv?: NodeJS.ProcessEnv,
380
457
  ) {}
381
458
 
382
459
  setStateDir(stateDir: string): void {
383
460
  this.stateDir = stateDir;
384
461
  }
385
462
 
463
+ private ensureStateDir(): string {
464
+ this.stateDir = resolvePrivateClawStateDir(this.stateDir);
465
+ return this.stateDir;
466
+ }
467
+
386
468
  private getMediaDir(): string {
387
- return resolvePrivateClawMediaDir(this.stateDir);
469
+ return resolvePrivateClawMediaDir(this.ensureStateDir());
388
470
  }
389
471
 
390
472
  private getProvider(): PrivateClawProvider {
@@ -395,11 +477,29 @@ class PrivateClawPluginRuntime {
395
477
  return this.provider;
396
478
  }
397
479
 
480
+ private async ensureControlServer(
481
+ kind: PrivateClawControlHostKind,
482
+ ): Promise<void> {
483
+ if (this.controlServer) {
484
+ return;
485
+ }
486
+ this.controlServer = new PrivateClawSessionControlServer({
487
+ provider: this.getProvider(),
488
+ stateDir: this.ensureStateDir(),
489
+ kind,
490
+ ...(this.providerOptions.onLog
491
+ ? { onLog: this.providerOptions.onLog }
492
+ : {}),
493
+ });
494
+ await this.controlServer.start();
495
+ }
496
+
398
497
  async createInviteBundle(params?: {
399
498
  ttlMs?: number;
400
499
  label?: string;
401
500
  groupMode?: boolean;
402
501
  }): Promise<PrivateClawInviteBundle> {
502
+ await this.ensureControlServer("plugin-service");
403
503
  return this.getProvider().createInviteBundle(
404
504
  {
405
505
  ...(typeof params?.ttlMs === "number"
@@ -434,31 +534,113 @@ class PrivateClawPluginRuntime {
434
534
  };
435
535
  }
436
536
 
537
+ async runBackgroundPairSession(params?: {
538
+ ttlMs?: number;
539
+ label?: string;
540
+ groupMode?: boolean;
541
+ openInBrowser?: boolean;
542
+ writeLine?: (line: string) => void;
543
+ }): Promise<PrivateClawInviteBundle> {
544
+ if (!this.daemonEnv) {
545
+ throw new Error(
546
+ formatBilingualInline(
547
+ "当前运行时无法安全地转入后台,请改用 --foreground。",
548
+ "This runtime cannot safely move into the background. Use --foreground instead.",
549
+ ),
550
+ );
551
+ }
552
+
553
+ const bundle = await spawnBackgroundPairDaemon({
554
+ cliModuleUrl: new URL(
555
+ import.meta.url.endsWith(".ts") ? "./cli.ts" : "./cli.js",
556
+ import.meta.url,
557
+ ).href,
558
+ stateDir: this.ensureStateDir(),
559
+ ...(this.daemonEnv ? { env: this.daemonEnv } : {}),
560
+ ...(typeof params?.ttlMs === "number" ? { ttlMs: params.ttlMs } : {}),
561
+ ...(params?.label ? { label: params.label } : {}),
562
+ ...(params?.groupMode === true ? { groupMode: true } : {}),
563
+ ...(params?.openInBrowser === true ? { openInBrowser: true } : {}),
564
+ });
565
+ printPairInviteBundle(bundle, params?.writeLine ?? ((line) => console.log(line)));
566
+ return bundle;
567
+ }
568
+
437
569
  async runPairSession(params?: {
438
570
  ttlMs?: number;
439
571
  label?: string;
440
572
  printOnly?: boolean;
441
573
  groupMode?: boolean;
574
+ foreground?: boolean;
442
575
  openInBrowser?: boolean;
443
576
  writeLine?: (line: string) => void;
444
577
  }): Promise<PrivateClawInviteBundle> {
578
+ if (!params?.printOnly) {
579
+ await this.ensureControlServer("pair-foreground");
580
+ }
581
+ const provider = this.getProvider();
445
582
  return runPairSession({
446
- provider: this.getProvider(),
583
+ provider,
447
584
  ...(typeof params?.ttlMs === "number"
448
585
  ? { ttlMs: params.ttlMs }
449
586
  : { ttlMs: this.defaultTtlMs }),
450
587
  ...(params?.label ? { label: params.label } : {}),
451
588
  ...(typeof params?.printOnly === "boolean" ? { printOnly: params.printOnly } : {}),
452
589
  ...(params?.groupMode === true ? { groupMode: true } : {}),
590
+ ...(typeof params?.foreground === "boolean"
591
+ ? { foreground: params.foreground }
592
+ : {}),
453
593
  ...(typeof params?.openInBrowser === "boolean"
454
594
  ? { openInBrowser: params.openInBrowser }
455
595
  : {}),
456
596
  qrMediaDir: this.getMediaDir(),
597
+ ...(this.daemonEnv && !params?.printOnly
598
+ ? {
599
+ handoffToBackground: async () => {
600
+ provider.suppressReconnectsForHandoff();
601
+ 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
+ );
615
+ } catch (error) {
616
+ provider.resumeReconnectsAfterHandoffFailure();
617
+ throw error;
618
+ }
619
+ },
620
+ }
621
+ : {}),
457
622
  ...(params?.writeLine ? { writeLine: params.writeLine } : {}),
458
623
  });
459
624
  }
460
625
 
626
+ async listManagedSessions() {
627
+ return listManagedSessionsFromStateDir(this.ensureStateDir());
628
+ }
629
+
630
+ async kickManagedParticipant(sessionId: string, appId: string) {
631
+ return kickManagedParticipantFromStateDir({
632
+ stateDir: this.ensureStateDir(),
633
+ sessionId,
634
+ appId,
635
+ reason: "participant_removed",
636
+ });
637
+ }
638
+
461
639
  async dispose(): Promise<void> {
640
+ if (this.controlServer) {
641
+ await this.controlServer.stop();
642
+ this.controlServer = undefined;
643
+ }
462
644
  if (!this.provider) {
463
645
  return;
464
646
  }
@@ -540,11 +722,12 @@ function createPluginDefinition(
540
722
  .option("--group", PRIVATECLAW_CLI_GROUP_OPTION_DESCRIPTION)
541
723
  .option("--print-only", PRIVATECLAW_CLI_PRINT_ONLY_OPTION_DESCRIPTION)
542
724
  .option("--open", PRIVATECLAW_CLI_OPEN_OPTION_DESCRIPTION)
725
+ .option("--foreground", PRIVATECLAW_CLI_FOREGROUND_OPTION_DESCRIPTION)
543
726
  .action(async (rawOptions: unknown) => {
544
727
  const options = normalizePairCliOptions(rawOptions);
545
728
  const ttlMs = parsePositiveIntegerFlag(options.ttlMs, "--ttl-ms");
546
729
  const label = readString(options.label);
547
- await runtime.runPairSession({
730
+ const pairParams = {
548
731
  ...(typeof ttlMs === "number" ? { ttlMs } : {}),
549
732
  ...(label ? { label } : {}),
550
733
  ...(options.group ? { groupMode: true } : {}),
@@ -554,10 +737,53 @@ function createPluginDefinition(
554
737
  ...(typeof options.open === "boolean"
555
738
  ? { openInBrowser: options.open }
556
739
  : {}),
557
- writeLine: (line) => {
740
+ writeLine: (line: string) => {
558
741
  console.log(line);
559
742
  },
560
- });
743
+ };
744
+ if (options.printOnly || options.foreground) {
745
+ await runtime.runPairSession({
746
+ ...pairParams,
747
+ foreground: true,
748
+ });
749
+ return;
750
+ }
751
+ await runtime.runBackgroundPairSession(pairParams);
752
+ });
753
+
754
+ privateclaw
755
+ .command("sessions")
756
+ .description(PRIVATECLAW_CLI_SESSIONS_DESCRIPTION)
757
+ .action(async () => {
758
+ const listings = await runtime.listManagedSessions();
759
+ for (const line of buildManagedSessionsReportLines(listings)) {
760
+ console.log(line);
761
+ }
762
+ });
763
+
764
+ privateclaw
765
+ .command("kick")
766
+ .description(PRIVATECLAW_CLI_KICK_DESCRIPTION)
767
+ .argument("<sessionId>")
768
+ .argument("<appId>")
769
+ .action(async (sessionIdRaw: unknown, appIdRaw: unknown) => {
770
+ const sessionId = readString(sessionIdRaw);
771
+ const appId = readString(appIdRaw);
772
+ if (!sessionId || !appId) {
773
+ throw new Error(
774
+ formatBilingualInline(
775
+ "kick 需要提供 sessionId 和 appId。",
776
+ "kick requires both a sessionId and appId.",
777
+ ),
778
+ );
779
+ }
780
+ const result = await runtime.kickManagedParticipant(sessionId, appId);
781
+ console.log(
782
+ formatBilingualInline(
783
+ `已从会话 ${result.session.sessionId} 中移除 ${result.participant.displayName} (${result.participant.appId})。`,
784
+ `Removed ${result.participant.displayName} (${result.participant.appId}) from session ${result.session.sessionId}.`,
785
+ ),
786
+ );
561
787
  });
562
788
  },
563
789
  { commands: ["privateclaw"] },
@@ -578,7 +804,11 @@ export function createPrivateClawPlugin(): OpenClawExtensionPluginCompat {
578
804
  return createPluginDefinition((api) => {
579
805
  const pluginConfig = resolvePluginConfig(api.pluginConfig);
580
806
  const resolved = buildProviderOptions(pluginConfig, api);
581
- return new PrivateClawPluginRuntime(resolved.options, resolved.defaultTtlMs);
807
+ return new PrivateClawPluginRuntime(
808
+ resolved.options,
809
+ resolved.defaultTtlMs,
810
+ buildDaemonEnvFromPluginConfig(pluginConfig),
811
+ );
582
812
  });
583
813
  }
584
814