@privateclaw/privateclaw 0.1.40 → 0.1.41

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.
package/src/setup.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { once } from "node:events";
3
- import { mkdtemp, readFile, rm } from "node:fs/promises";
4
- import os from "node:os";
3
+ import { readFile } from "node:fs/promises";
5
4
  import path from "node:path";
6
5
  import { createInterface } from "node:readline/promises";
7
6
  import { stdin, stdout } from "node:process";
8
- import { formatBilingualInline } from "./text.js";
7
+ import { fileURLToPath } from "node:url";
8
+ import {
9
+ appendPrivateClawAppInstallFooter,
10
+ formatBilingualInline,
11
+ } from "./text.js";
9
12
 
10
13
  export interface LocalOpenClawStatus {
11
14
  openClawAvailable: boolean;
@@ -13,13 +16,22 @@ export interface LocalOpenClawStatus {
13
16
  privateClawPluginPresent?: boolean;
14
17
  }
15
18
 
19
+ interface PrivateClawSetupCommandCandidate {
20
+ label: string;
21
+ command: string;
22
+ args: string[];
23
+ display: string;
24
+ env?: NodeJS.ProcessEnv;
25
+ }
26
+
16
27
  export interface PrivateClawSetupStep {
17
28
  title: string;
18
29
  command: string;
19
30
  args: string[];
20
31
  display: string;
21
- kind?: "command" | "npm-pack-install";
22
- packageSpec?: string;
32
+ env?: NodeJS.ProcessEnv;
33
+ kind?: "command" | "install-candidates";
34
+ candidates?: readonly PrivateClawSetupCommandCandidate[];
23
35
  }
24
36
 
25
37
  export interface PrivateClawSetupChoice {
@@ -61,11 +73,17 @@ interface RunOneShotCommandResult {
61
73
  type OneShotCommandRunner = (
62
74
  command: string,
63
75
  args: string[],
76
+ options?: {
77
+ cwd?: string;
78
+ env?: NodeJS.ProcessEnv;
79
+ },
64
80
  ) => Promise<RunOneShotCommandResult>;
65
81
 
66
82
  export interface RunPrivateClawSetupOptions {
67
83
  packageSpec?: string;
84
+ packageRoot?: string;
68
85
  relayBaseUrl?: string;
86
+ configPath?: string;
69
87
  label?: string;
70
88
  foreground?: boolean;
71
89
  openInBrowser?: boolean;
@@ -90,8 +108,8 @@ export interface RunPrivateClawSetupOptions {
90
108
  }
91
109
 
92
110
  const PRIVATECLAW_PACKAGE_NAME = "@privateclaw/privateclaw";
93
- const PRIVATECLAW_VERIFICATION_COMMAND = "openclaw privateclaw pair --help";
94
111
  const PRIVATECLAW_PLUGIN_ID = "privateclaw";
112
+ const OPENCLAW_UNSAFE_INSTALL_FLAG = "--dangerously-force-unsafe-install";
95
113
 
96
114
  const MINUTE_MS = 60_000;
97
115
  const HOUR_MS = 60 * MINUTE_MS;
@@ -176,7 +194,7 @@ function createStep(
176
194
  command: string,
177
195
  args: string[],
178
196
  display: string,
179
- extra?: Pick<PrivateClawSetupStep, "kind" | "packageSpec">,
197
+ extra?: Pick<PrivateClawSetupStep, "kind" | "env" | "candidates">,
180
198
  ): PrivateClawSetupStep {
181
199
  return {
182
200
  title,
@@ -207,15 +225,115 @@ function delay(ms: number): Promise<void> {
207
225
  });
208
226
  }
209
227
 
228
+ function shellEscape(value: string): string {
229
+ if (/^[A-Za-z0-9_./:@%+=,-]+$/u.test(value)) {
230
+ return value;
231
+ }
232
+ return `'${value.replace(/'/gu, `'\"'\"'`)}'`;
233
+ }
234
+
235
+ function buildCommandDisplay(command: string, args: string[]): string {
236
+ return [command, ...args].map(shellEscape).join(" ");
237
+ }
238
+
239
+ export function buildOpenClawCommandEnv(configPath: string): NodeJS.ProcessEnv {
240
+ const resolvedConfigPath = path.resolve(configPath);
241
+ const stateDir = path.dirname(resolvedConfigPath);
242
+ return {
243
+ ...process.env,
244
+ OPENCLAW_STATE_DIR: stateDir,
245
+ OPENCLAW_CONFIG_PATH: resolvedConfigPath,
246
+ };
247
+ }
248
+
249
+ function buildOpenClawDisplayPrefix(configPath?: string): string | undefined {
250
+ if (!configPath) {
251
+ return undefined;
252
+ }
253
+ const resolvedConfigPath = path.resolve(configPath);
254
+ const stateDir = path.dirname(resolvedConfigPath);
255
+ return `OPENCLAW_STATE_DIR=${shellEscape(stateDir)} OPENCLAW_CONFIG_PATH=${shellEscape(resolvedConfigPath)}`;
256
+ }
257
+
258
+ function buildDisplayWithOptionalPrefix(
259
+ command: string,
260
+ args: string[],
261
+ prefix?: string,
262
+ ): string {
263
+ const commandDisplay = buildCommandDisplay(command, args);
264
+ return prefix ? `${prefix} ${commandDisplay}` : commandDisplay;
265
+ }
266
+
267
+ function createOpenClawStep(
268
+ title: string,
269
+ args: string[],
270
+ configPath?: string,
271
+ ): PrivateClawSetupStep {
272
+ const env = configPath ? buildOpenClawCommandEnv(configPath) : undefined;
273
+ return createStep(
274
+ title,
275
+ "openclaw",
276
+ args,
277
+ buildDisplayWithOptionalPrefix(
278
+ "openclaw",
279
+ args,
280
+ buildOpenClawDisplayPrefix(configPath),
281
+ ),
282
+ {
283
+ ...(env ? { env } : {}),
284
+ },
285
+ );
286
+ }
287
+
288
+ function createNpmExecOpenClawStep(
289
+ title: string,
290
+ args: string[],
291
+ configPath?: string,
292
+ ): PrivateClawSetupStep {
293
+ const command = resolveNpmCommand();
294
+ const fullArgs = ["exec", "-y", "openclaw@latest", "--", ...args];
295
+ const env = configPath ? buildOpenClawCommandEnv(configPath) : undefined;
296
+ return createStep(
297
+ title,
298
+ command,
299
+ fullArgs,
300
+ buildDisplayWithOptionalPrefix(
301
+ command,
302
+ fullArgs,
303
+ buildOpenClawDisplayPrefix(configPath),
304
+ ),
305
+ {
306
+ ...(env ? { env } : {}),
307
+ },
308
+ );
309
+ }
310
+
311
+ function createOpenClawOneShotRunner(configPath?: string): OneShotCommandRunner {
312
+ if (!configPath) {
313
+ return runOneShotCommand;
314
+ }
315
+ const env = buildOpenClawCommandEnv(configPath);
316
+ return (command, args, options) =>
317
+ runOneShotCommand(command, args, {
318
+ ...(options ?? {}),
319
+ env: {
320
+ ...env,
321
+ ...(options?.env ?? {}),
322
+ },
323
+ });
324
+ }
325
+
210
326
  async function runOneShotCommand(
211
327
  command: string,
212
328
  args: string[],
213
329
  options?: {
214
330
  cwd?: string;
331
+ env?: NodeJS.ProcessEnv;
215
332
  },
216
333
  ): Promise<RunOneShotCommandResult> {
217
334
  const child = spawn(command, args, {
218
335
  ...(options?.cwd ? { cwd: options.cwd } : {}),
336
+ ...(options?.env ? { env: options.env } : {}),
219
337
  stdio: ["ignore", "pipe", "pipe"],
220
338
  });
221
339
  let stdoutText = "";
@@ -257,10 +375,12 @@ async function runStreamingCommand(
257
375
  args: string[],
258
376
  options?: {
259
377
  cwd?: string;
378
+ env?: NodeJS.ProcessEnv;
260
379
  },
261
380
  ): Promise<RunOneShotCommandResult> {
262
381
  const child = spawn(command, args, {
263
382
  ...(options?.cwd ? { cwd: options.cwd } : {}),
383
+ ...(options?.env ? { env: options.env } : {}),
264
384
  stdio: ["ignore", "pipe", "pipe"],
265
385
  });
266
386
  let stdoutText = "";
@@ -395,92 +515,110 @@ function resolveNpmCommand(): string {
395
515
  return process.platform === "win32" ? "npm.cmd" : "npm";
396
516
  }
397
517
 
398
- function isExactSemverVersion(value: string): boolean {
399
- return /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(
400
- value.trim(),
518
+ function resolveCurrentPrivateClawPackageRoot(): string {
519
+ return fileURLToPath(new URL("../", import.meta.url));
520
+ }
521
+
522
+ function buildPrivateClawVerificationDisplay(configPath?: string): string {
523
+ return buildDisplayWithOptionalPrefix(
524
+ "openclaw",
525
+ ["privateclaw", "pair", "--help"],
526
+ buildOpenClawDisplayPrefix(configPath),
401
527
  );
402
528
  }
403
529
 
404
- function buildPackedArchiveHint(packageSpec: string): string {
405
- const normalizedSpec = packageSpec.trim();
406
- const lastAt = normalizedSpec.lastIndexOf("@");
407
- const hasSelector = lastAt > 0;
408
- const packageName = hasSelector ? normalizedSpec.slice(0, lastAt) : normalizedSpec;
409
- const selector = hasSelector ? normalizedSpec.slice(lastAt + 1) : "";
410
- const sanitizedName = packageName.replace(/^@/u, "").replace(/\//gu, "-");
411
- if (selector && isExactSemverVersion(selector)) {
412
- return `${sanitizedName}-${selector.replace(/^v/iu, "")}.tgz`;
413
- }
414
- return `${sanitizedName}-*.tgz`;
530
+ function createOpenClawInstallCandidates(params: {
531
+ packageRoot: string;
532
+ packageSpec: string;
533
+ configPath?: string;
534
+ }): PrivateClawSetupCommandCandidate[] {
535
+ const normalizedPackageRoot = path.resolve(params.packageRoot);
536
+ const installArgs = [
537
+ "plugins",
538
+ "install",
539
+ OPENCLAW_UNSAFE_INSTALL_FLAG,
540
+ normalizedPackageRoot,
541
+ ];
542
+ const exactSpecArgs = [
543
+ "plugins",
544
+ "install",
545
+ OPENCLAW_UNSAFE_INSTALL_FLAG,
546
+ params.packageSpec,
547
+ ];
548
+ const openClawLocalStep = createOpenClawStep(
549
+ "Install the local PrivateClaw package directory into OpenClaw",
550
+ installArgs,
551
+ params.configPath,
552
+ );
553
+ const npmExecFallbackStep = createNpmExecOpenClawStep(
554
+ "Install the local PrivateClaw package directory via npm exec openclaw",
555
+ installArgs,
556
+ params.configPath,
557
+ );
558
+ const exactVersionStep = createOpenClawStep(
559
+ "Install the published PrivateClaw package with the exact npm spec",
560
+ exactSpecArgs,
561
+ params.configPath,
562
+ );
563
+ return [
564
+ {
565
+ label: "openclaw (local package directory)",
566
+ command: openClawLocalStep.command,
567
+ args: openClawLocalStep.args,
568
+ display: openClawLocalStep.display,
569
+ ...(openClawLocalStep.env ? { env: openClawLocalStep.env } : {}),
570
+ },
571
+ {
572
+ label: "npm exec fallback (local package directory)",
573
+ command: npmExecFallbackStep.command,
574
+ args: npmExecFallbackStep.args,
575
+ display: npmExecFallbackStep.display,
576
+ ...(npmExecFallbackStep.env ? { env: npmExecFallbackStep.env } : {}),
577
+ },
578
+ {
579
+ label: "openclaw (exact version fallback)",
580
+ command: exactVersionStep.command,
581
+ args: exactVersionStep.args,
582
+ display: exactVersionStep.display,
583
+ ...(exactVersionStep.env ? { env: exactVersionStep.env } : {}),
584
+ },
585
+ ];
415
586
  }
416
587
 
417
- function createNpmPackInstallStep(packageSpec: string): PrivateClawSetupStep {
588
+ function createOpenClawInstallStep(params: {
589
+ packageRoot: string;
590
+ packageSpec: string;
591
+ configPath?: string;
592
+ }): PrivateClawSetupStep {
593
+ const candidates = createOpenClawInstallCandidates(params);
594
+ const [firstCandidate] = candidates;
595
+ if (!firstCandidate) {
596
+ throw new Error("Missing OpenClaw install candidates.");
597
+ }
418
598
  return createStep(
419
- "Pack the PrivateClaw npm package locally, then install the generated archive into OpenClaw",
420
- resolveNpmCommand(),
421
- ["pack", packageSpec],
422
- `npm pack ${packageSpec} && openclaw plugins install ./${buildPackedArchiveHint(packageSpec)}`,
599
+ "Install the local PrivateClaw package into OpenClaw",
600
+ firstCandidate.command,
601
+ firstCandidate.args,
602
+ firstCandidate.display,
423
603
  {
424
- kind: "npm-pack-install",
425
- packageSpec,
604
+ kind: "install-candidates",
605
+ candidates,
606
+ ...(firstCandidate.env ? { env: firstCandidate.env } : {}),
426
607
  },
427
608
  );
428
609
  }
429
610
 
430
- function createManualNpmArchiveInstallSteps(
431
- packageSpec: string,
432
- ): [PrivateClawSetupStep, PrivateClawSetupStep] {
433
- const archiveHint = buildPackedArchiveHint(packageSpec);
434
- return [
435
- createStep(
436
- "Pack the PrivateClaw plugin from npm into a local archive",
437
- resolveNpmCommand(),
438
- ["pack", packageSpec],
439
- `npm pack ${packageSpec}`,
440
- ),
441
- createStep(
442
- "Install the generated PrivateClaw plugin archive into OpenClaw",
443
- "openclaw",
444
- ["plugins", "install", `./${archiveHint}`],
445
- `openclaw plugins install ./${archiveHint}`,
446
- ),
447
- ];
448
- }
449
-
450
- async function runNpmPackInstallStep(step: PrivateClawSetupStep): Promise<void> {
451
- if (!step.packageSpec) {
452
- throw new Error("Missing packageSpec for npm-pack-install step.");
453
- }
454
- const tempDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-install-"));
455
- try {
456
- const packResult = await runOneShotCommand(
457
- resolveNpmCommand(),
458
- [
459
- "pack",
460
- step.packageSpec,
461
- "--json",
462
- "--ignore-scripts",
463
- "--pack-destination",
464
- tempDir,
465
- ],
466
- );
467
- const packOutput = packResult.stdout.trim() || packResult.combined.trim();
468
- const parsed = JSON.parse(packOutput) as Array<{ filename?: unknown }>;
469
- const archiveFileName =
470
- typeof parsed[0]?.filename === "string" && parsed[0].filename.trim() !== ""
471
- ? parsed[0].filename.trim()
472
- : undefined;
473
- if (!archiveFileName) {
474
- throw new Error(`Could not determine the generated archive for ${step.packageSpec}.`);
475
- }
476
- await runStreamingCommand("openclaw", [
477
- "plugins",
478
- "install",
479
- path.join(tempDir, archiveFileName),
480
- ]);
481
- } finally {
482
- await rm(tempDir, { recursive: true, force: true });
483
- }
611
+ function createManualOpenClawInstallSteps(params: {
612
+ packageRoot: string;
613
+ packageSpec: string;
614
+ configPath?: string;
615
+ }): PrivateClawSetupStep[] {
616
+ const candidates = createOpenClawInstallCandidates(params);
617
+ return candidates.map((candidate) =>
618
+ createStep(candidate.label, candidate.command, candidate.args, candidate.display, {
619
+ ...(candidate.env ? { env: candidate.env } : {}),
620
+ }),
621
+ );
484
622
  }
485
623
 
486
624
  export function parsePrivateClawSessionDurationPreset(
@@ -506,6 +644,7 @@ function buildPairingCommandStep(params: {
506
644
  groupMode: boolean;
507
645
  ttlMs: number;
508
646
  relayBaseUrl?: string;
647
+ configPath?: string;
509
648
  label?: string;
510
649
  foreground?: boolean;
511
650
  openInBrowser?: boolean;
@@ -535,11 +674,10 @@ function buildPairingCommandStep(params: {
535
674
  if (params.verbose) {
536
675
  args.push("--verbose");
537
676
  }
538
- return createStep(
677
+ return createOpenClawStep(
539
678
  "Start the requested PrivateClaw pairing flow",
540
- "openclaw",
541
679
  args,
542
- `openclaw ${args.join(" ")}`,
680
+ params.configPath,
543
681
  );
544
682
  }
545
683
 
@@ -609,38 +747,59 @@ export async function resolvePrivateClawSetupSelection(params: {
609
747
 
610
748
  export function buildPrivateClawSetupPlan(params: {
611
749
  packageSpec: string;
750
+ packageRoot: string;
612
751
  status: LocalOpenClawStatus;
613
752
  selection: PrivateClawSetupSelection;
614
753
  relayBaseUrl?: string;
754
+ configPath?: string;
615
755
  label?: string;
616
756
  foreground?: boolean;
617
757
  openInBrowser?: boolean;
618
758
  verbose?: boolean;
619
759
  }): PrivateClawSetupPlan {
620
- const installStep = createNpmPackInstallStep(params.packageSpec);
621
- const manualInstallSteps = createManualNpmArchiveInstallSteps(params.packageSpec);
622
- const updateStep = createStep(
760
+ const installStep = createOpenClawInstallStep({
761
+ packageRoot: params.packageRoot,
762
+ packageSpec: params.packageSpec,
763
+ ...(params.configPath ? { configPath: params.configPath } : {}),
764
+ });
765
+ const manualInstallSteps = createManualOpenClawInstallSteps({
766
+ packageRoot: params.packageRoot,
767
+ packageSpec: params.packageSpec,
768
+ ...(params.configPath ? { configPath: params.configPath } : {}),
769
+ });
770
+ const updateStep = createOpenClawStep(
623
771
  "Update the existing PrivateClaw OpenClaw plugin",
624
- "openclaw",
625
772
  ["plugins", "update", PRIVATECLAW_PLUGIN_ID],
626
- `openclaw plugins update ${PRIVATECLAW_PLUGIN_ID}`,
773
+ params.configPath,
627
774
  );
628
- const enableStep = createStep(
775
+ const enableStep = createOpenClawStep(
629
776
  "Enable the PrivateClaw OpenClaw plugin",
630
- "openclaw",
631
777
  ["plugins", "enable", PRIVATECLAW_PLUGIN_ID],
632
- `openclaw plugins enable ${PRIVATECLAW_PLUGIN_ID}`,
778
+ params.configPath,
633
779
  );
634
- const restartStep = createStep(
780
+ const gatewayModeStep = params.configPath
781
+ ? createOpenClawStep(
782
+ "Mark this isolated OpenClaw config as a local gateway",
783
+ ["config", "set", "gateway.mode", "local"],
784
+ params.configPath,
785
+ )
786
+ : undefined;
787
+ const restartStep = createOpenClawStep(
635
788
  "Restart the OpenClaw gateway so the new plugin command is reloaded",
636
- "openclaw",
637
789
  ["gateway", "restart"],
638
- "openclaw gateway restart",
790
+ params.configPath,
639
791
  );
792
+ const startStep = createOpenClawStep(
793
+ "Start the OpenClaw gateway with this config",
794
+ ["gateway", "run"],
795
+ params.configPath,
796
+ );
797
+ const startupStep = params.configPath ? startStep : restartStep;
640
798
  const pairingCommand = buildPairingCommandStep({
641
799
  groupMode: params.selection.groupMode,
642
800
  ttlMs: params.selection.ttlMs,
643
801
  ...(params.relayBaseUrl ? { relayBaseUrl: params.relayBaseUrl } : {}),
802
+ ...(params.configPath ? { configPath: params.configPath } : {}),
644
803
  ...(params.label ? { label: params.label } : {}),
645
804
  ...(params.foreground ? { foreground: true } : {}),
646
805
  ...(params.openInBrowser ? { openInBrowser: true } : {}),
@@ -657,9 +816,17 @@ export function buildPrivateClawSetupPlan(params: {
657
816
  ),
658
817
  ];
659
818
  const verificationNotes = [
819
+ ...(params.configPath
820
+ ? [
821
+ `[privateclaw-provider] ${formatBilingualInline(
822
+ `若要启动这个隔离配置对应的 OpenClaw,请运行:${startStep.display}`,
823
+ `To start OpenClaw for this isolated config, run: ${startStep.display}`,
824
+ )}`,
825
+ ]
826
+ : []),
660
827
  `[privateclaw-provider] ${formatBilingualInline(
661
- `若需要手工确认插件命令是否就绪,可运行:${PRIVATECLAW_VERIFICATION_COMMAND}`,
662
- `If you want to verify the plugin command manually, run: ${PRIVATECLAW_VERIFICATION_COMMAND}`,
828
+ `若需要手工确认插件命令是否就绪,可运行:${buildPrivateClawVerificationDisplay(params.configPath)}`,
829
+ `If you want to verify the plugin command manually, run: ${buildPrivateClawVerificationDisplay(params.configPath)}`,
663
830
  )}`,
664
831
  ];
665
832
 
@@ -674,7 +841,13 @@ export function buildPrivateClawSetupPlan(params: {
674
841
  "Could not detect `openclaw` on this machine. Run these commands on the machine where OpenClaw is installed:",
675
842
  )}`,
676
843
  automaticSteps: [],
677
- manualSteps: [...manualInstallSteps, enableStep, restartStep, pairingCommand],
844
+ manualSteps: [
845
+ ...manualInstallSteps,
846
+ enableStep,
847
+ ...(gatewayModeStep ? [gatewayModeStep] : []),
848
+ startupStep,
849
+ pairingCommand,
850
+ ],
678
851
  selectionNotes,
679
852
  verificationNotes,
680
853
  pairingCommand,
@@ -691,8 +864,10 @@ export function buildPrivateClawSetupPlan(params: {
691
864
  "本机的 OpenClaw + PrivateClaw 已经可用,接下来直接开始配对:",
692
865
  "OpenClaw + PrivateClaw are already available locally. Starting pairing next:",
693
866
  )}`,
694
- automaticSteps: [],
695
- manualSteps: [pairingCommand],
867
+ automaticSteps: gatewayModeStep ? [gatewayModeStep] : [],
868
+ manualSteps: params.configPath
869
+ ? [...(gatewayModeStep ? [gatewayModeStep] : []), startupStep, pairingCommand]
870
+ : [pairingCommand],
696
871
  selectionNotes,
697
872
  verificationNotes,
698
873
  pairingCommand,
@@ -703,24 +878,34 @@ export function buildPrivateClawSetupPlan(params: {
703
878
  packageSpec: params.packageSpec,
704
879
  localOpenClaw: true,
705
880
  privateClawCommandAvailable: false,
706
- introduction:
707
- `[privateclaw-provider] ${formatBilingualInline(
708
- params.status.privateClawPluginPresent
709
- ? "检测到本机已经安装过 PrivateClaw 插件,但命令还没有生效。现在会更新、启用并重启 OpenClaw:"
710
- : "检测到本机可以直接运行 OpenClaw。现在会安装、启用 PrivateClaw 插件并重启 OpenClaw:",
711
- params.status.privateClawPluginPresent
712
- ? "A local PrivateClaw plugin is already present, but the command is not active yet. Updating, enabling, and restarting OpenClaw now:"
713
- : "OpenClaw is available locally. Installing, enabling, and restarting the PrivateClaw plugin now:",
714
- )}`,
881
+ introduction:
882
+ `[privateclaw-provider] ${formatBilingualInline(
883
+ params.configPath
884
+ ? params.status.privateClawPluginPresent
885
+ ? "检测到本机已经安装过 PrivateClaw 插件,但命令还没有生效。现在会更新并启用插件;隔离配置对应的 OpenClaw 启动命令见下方:"
886
+ : "检测到本机可以直接运行 OpenClaw。现在会安装并启用 PrivateClaw 插件;隔离配置对应的 OpenClaw 启动命令见下方:"
887
+ : params.status.privateClawPluginPresent
888
+ ? "检测到本机已经安装过 PrivateClaw 插件,但命令还没有生效。现在会更新、启用并重启 OpenClaw:"
889
+ : "检测到本机可以直接运行 OpenClaw。现在会安装、启用 PrivateClaw 插件并重启 OpenClaw:",
890
+ params.configPath
891
+ ? params.status.privateClawPluginPresent
892
+ ? "A local PrivateClaw plugin is already present, but the command is not active yet. Updating and enabling it now; the isolated OpenClaw start command is shown below:"
893
+ : "OpenClaw is available locally. Installing and enabling the PrivateClaw plugin now; the isolated OpenClaw start command is shown below:"
894
+ : params.status.privateClawPluginPresent
895
+ ? "A local PrivateClaw plugin is already present, but the command is not active yet. Updating, enabling, and restarting OpenClaw now:"
896
+ : "OpenClaw is available locally. Installing, enabling, and restarting the PrivateClaw plugin now:",
897
+ )}`,
715
898
  automaticSteps: [
716
899
  ...(params.status.privateClawPluginPresent ? [updateStep] : [installStep]),
717
900
  enableStep,
718
- restartStep,
901
+ ...(gatewayModeStep ? [gatewayModeStep] : []),
902
+ ...(params.configPath ? [] : [restartStep]),
719
903
  ],
720
904
  manualSteps: [
721
905
  ...(params.status.privateClawPluginPresent ? [updateStep] : [installStep]),
722
906
  enableStep,
723
- restartStep,
907
+ ...(gatewayModeStep ? [gatewayModeStep] : []),
908
+ startupStep,
724
909
  pairingCommand,
725
910
  ],
726
911
  selectionNotes,
@@ -732,12 +917,14 @@ export function buildPrivateClawSetupPlan(params: {
732
917
  export function renderPrivateClawSetupGuidance(
733
918
  plan: PrivateClawSetupPlan,
734
919
  ): string {
735
- return [
736
- plan.introduction,
737
- ...plan.selectionNotes.map((line) => `[privateclaw-provider] ${line}`),
738
- ...plan.manualSteps.map((step) => `[privateclaw-provider] ${step.display}`),
739
- ...plan.verificationNotes,
740
- ].join("\n");
920
+ return appendPrivateClawAppInstallFooter(
921
+ [
922
+ plan.introduction,
923
+ ...plan.selectionNotes.map((line) => `[privateclaw-provider] ${line}`),
924
+ ...plan.manualSteps.map((step) => `[privateclaw-provider] ${step.display}`),
925
+ ...plan.verificationNotes,
926
+ ].join("\n"),
927
+ );
741
928
  }
742
929
 
743
930
  async function promptForPrivateClawChoice(
@@ -802,11 +989,26 @@ async function promptForPrivateClawChoice(
802
989
  async function runPrivateClawSetupStep(
803
990
  step: PrivateClawSetupStep,
804
991
  ): Promise<void> {
805
- if (step.kind === "npm-pack-install") {
806
- await runNpmPackInstallStep(step);
807
- return;
992
+ if (step.kind === "install-candidates") {
993
+ let lastError: unknown;
994
+ for (const candidate of step.candidates ?? []) {
995
+ try {
996
+ await runStreamingCommand(candidate.command, candidate.args, {
997
+ ...(candidate.env ? { env: candidate.env } : {}),
998
+ });
999
+ return;
1000
+ } catch (error) {
1001
+ lastError = error;
1002
+ console.warn(
1003
+ `[privateclaw-provider] Install attempt failed (${candidate.label}): ${error instanceof Error ? error.message : String(error)}`,
1004
+ );
1005
+ }
1006
+ }
1007
+ throw lastError ?? new Error("Missing OpenClaw install candidates.");
808
1008
  }
809
- await runStreamingCommand(step.command, step.args);
1009
+ await runStreamingCommand(step.command, step.args, {
1010
+ ...(step.env ? { env: step.env } : {}),
1011
+ });
810
1012
  }
811
1013
 
812
1014
  async function waitForPrivateClawCommandAvailability(
@@ -831,9 +1033,14 @@ export async function runPrivateClawSetup(
831
1033
  options: RunPrivateClawSetupOptions = {},
832
1034
  ): Promise<void> {
833
1035
  const detectStatus =
834
- options.detectLocalOpenClawStatus ?? detectLocalOpenClawStatus;
1036
+ options.detectLocalOpenClawStatus ??
1037
+ (() =>
1038
+ detectLocalOpenClawStatus(
1039
+ createOpenClawOneShotRunner(options.configPath),
1040
+ ));
835
1041
  const packageSpec =
836
1042
  options.packageSpec ?? (await resolveCurrentPrivateClawPackageSpec());
1043
+ const packageRoot = options.packageRoot ?? resolveCurrentPrivateClawPackageRoot();
837
1044
  const selection =
838
1045
  options.selection ??
839
1046
  (await resolvePrivateClawSetupSelection({
@@ -849,8 +1056,10 @@ export async function runPrivateClawSetup(
849
1056
  const status = await detectStatus();
850
1057
  const plan = buildPrivateClawSetupPlan({
851
1058
  packageSpec,
1059
+ packageRoot,
852
1060
  status,
853
1061
  selection,
1062
+ ...(options.configPath ? { configPath: options.configPath } : {}),
854
1063
  ...(options.relayBaseUrl ? { relayBaseUrl: options.relayBaseUrl } : {}),
855
1064
  ...(options.label ? { label: options.label } : {}),
856
1065
  ...(options.foreground ? { foreground: true } : {}),
@@ -875,7 +1084,10 @@ export async function runPrivateClawSetup(
875
1084
  const runStep = options.runStep ?? runPrivateClawSetupStep;
876
1085
  const runPairingCommand =
877
1086
  options.runPairingCommand ??
878
- ((step: PrivateClawSetupStep) => runStreamingCommand(step.command, step.args));
1087
+ ((step: PrivateClawSetupStep) =>
1088
+ runStreamingCommand(step.command, step.args, {
1089
+ ...(step.env ? { env: step.env } : {}),
1090
+ }));
879
1091
 
880
1092
  for (const step of plan.automaticSteps) {
881
1093
  log(`[privateclaw-provider] ${formatBilingualInline("正在执行", "Running")}: ${step.display}`);
@@ -891,15 +1103,15 @@ export async function runPrivateClawSetup(
891
1103
  if (!refreshedStatus.privateClawCommandAvailable) {
892
1104
  throw new Error(
893
1105
  formatBilingualInline(
894
- `OpenClaw 已重载,但 \`privateclaw\` 仍然无法响应 \`${PRIVATECLAW_VERIFICATION_COMMAND}\`。请确认 gateway 已正常重启后再试。`,
895
- `OpenClaw reloaded, but \`privateclaw\` still does not respond to \`${PRIVATECLAW_VERIFICATION_COMMAND}\`. Confirm the gateway restarted cleanly, then try again.`,
1106
+ `PrivateClaw 安装/启用步骤已完成,但 \`privateclaw\` 仍然无法响应 \`${buildPrivateClawVerificationDisplay(options.configPath)}\`。请确认当前 OpenClaw 配置已正确生效后再试。`,
1107
+ `The PrivateClaw install/enable steps completed, but \`privateclaw\` still does not respond to \`${buildPrivateClawVerificationDisplay(options.configPath)}\`. Confirm the current OpenClaw config loaded cleanly, then try again.`,
896
1108
  ),
897
1109
  );
898
1110
  }
899
1111
  log(
900
1112
  `[privateclaw-provider] ${formatBilingualInline(
901
- `已确认命令就绪:${PRIVATECLAW_VERIFICATION_COMMAND}`,
902
- `Verified command availability with: ${PRIVATECLAW_VERIFICATION_COMMAND}`,
1113
+ `已确认命令就绪:${buildPrivateClawVerificationDisplay(options.configPath)}`,
1114
+ `Verified command availability with: ${buildPrivateClawVerificationDisplay(options.configPath)}`,
903
1115
  )}`,
904
1116
  );
905
1117
  }