@privateclaw/privateclaw 0.1.25 → 0.1.27

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 ADDED
@@ -0,0 +1,814 @@
1
+ import { spawn } from "node:child_process";
2
+ import { once } from "node:events";
3
+ import { readFile } from "node:fs/promises";
4
+ import { createInterface } from "node:readline/promises";
5
+ import { stdin, stdout } from "node:process";
6
+ import { formatBilingualInline } from "./text.js";
7
+
8
+ export interface LocalOpenClawStatus {
9
+ openClawAvailable: boolean;
10
+ privateClawCommandAvailable: boolean;
11
+ privateClawPluginPresent?: boolean;
12
+ }
13
+
14
+ export interface PrivateClawSetupStep {
15
+ title: string;
16
+ command: string;
17
+ args: string[];
18
+ display: string;
19
+ }
20
+
21
+ export interface PrivateClawSetupChoice {
22
+ value: string;
23
+ label: string;
24
+ }
25
+
26
+ export interface PrivateClawSessionDurationPreset {
27
+ id: string;
28
+ ttlMs: number;
29
+ label: string;
30
+ aliases: readonly string[];
31
+ }
32
+
33
+ export interface PrivateClawSetupSelection {
34
+ groupMode: boolean;
35
+ ttlMs: number;
36
+ durationLabel: string;
37
+ }
38
+
39
+ export interface PrivateClawSetupPlan {
40
+ packageSpec: string;
41
+ localOpenClaw: boolean;
42
+ privateClawCommandAvailable: boolean;
43
+ introduction: string;
44
+ automaticSteps: PrivateClawSetupStep[];
45
+ manualSteps: PrivateClawSetupStep[];
46
+ selectionNotes: string[];
47
+ verificationNotes: string[];
48
+ pairingCommand: PrivateClawSetupStep;
49
+ }
50
+
51
+ interface RunOneShotCommandResult {
52
+ stdout: string;
53
+ stderr: string;
54
+ combined: string;
55
+ }
56
+
57
+ type OneShotCommandRunner = (
58
+ command: string,
59
+ args: string[],
60
+ ) => Promise<RunOneShotCommandResult>;
61
+
62
+ export interface RunPrivateClawSetupOptions {
63
+ packageSpec?: string;
64
+ relayBaseUrl?: string;
65
+ label?: string;
66
+ foreground?: boolean;
67
+ openInBrowser?: boolean;
68
+ verbose?: boolean;
69
+ groupMode?: boolean;
70
+ ttlMs?: number;
71
+ durationPreset?: string;
72
+ selection?: PrivateClawSetupSelection;
73
+ detectLocalOpenClawStatus?: () => Promise<LocalOpenClawStatus>;
74
+ promptForChoice?: (
75
+ question: string,
76
+ choices: readonly PrivateClawSetupChoice[],
77
+ defaultValue?: string,
78
+ ) => Promise<string>;
79
+ runStep?: (step: PrivateClawSetupStep) => Promise<void>;
80
+ runPairingCommand?: (
81
+ step: PrivateClawSetupStep,
82
+ ) => Promise<RunOneShotCommandResult>;
83
+ onLog?: (line: string) => void;
84
+ verificationTimeoutMs?: number;
85
+ verificationPollMs?: number;
86
+ }
87
+
88
+ const PRIVATECLAW_PACKAGE_NAME = "@privateclaw/privateclaw";
89
+ const PRIVATECLAW_VERIFICATION_COMMAND = "openclaw privateclaw pair --help";
90
+ const PRIVATECLAW_PLUGIN_ID = "privateclaw";
91
+
92
+ const MINUTE_MS = 60_000;
93
+ const HOUR_MS = 60 * MINUTE_MS;
94
+ const DAY_MS = 24 * HOUR_MS;
95
+ const WEEK_MS = 7 * DAY_MS;
96
+ const MONTH_MS = 30 * DAY_MS;
97
+ const YEAR_MS = 365 * DAY_MS;
98
+
99
+ export const EFFECTIVELY_PERMANENT_SESSION_TTL_MS = 100 * YEAR_MS;
100
+
101
+ export const PRIVATECLAW_SESSION_DURATION_PRESETS: readonly PrivateClawSessionDurationPreset[] =
102
+ [
103
+ {
104
+ id: "30m",
105
+ ttlMs: 30 * MINUTE_MS,
106
+ label: "30 分钟 / 30 minutes",
107
+ aliases: ["30min", "30mins", "30minutes"],
108
+ },
109
+ {
110
+ id: "2h",
111
+ ttlMs: 2 * HOUR_MS,
112
+ label: "2 小时 / 2 hours",
113
+ aliases: ["2hr", "2hrs", "2hours"],
114
+ },
115
+ {
116
+ id: "4h",
117
+ ttlMs: 4 * HOUR_MS,
118
+ label: "4 小时 / 4 hours",
119
+ aliases: ["4hr", "4hrs", "4hours"],
120
+ },
121
+ {
122
+ id: "8h",
123
+ ttlMs: 8 * HOUR_MS,
124
+ label: "8 小时 / 8 hours",
125
+ aliases: ["8hr", "8hrs", "8hours"],
126
+ },
127
+ {
128
+ id: "24h",
129
+ ttlMs: DAY_MS,
130
+ label: "24 小时 / 24 hours",
131
+ aliases: ["24hr", "24hrs", "1d", "1day"],
132
+ },
133
+ {
134
+ id: "1w",
135
+ ttlMs: WEEK_MS,
136
+ label: "1 周 / 1 week",
137
+ aliases: ["1week", "week"],
138
+ },
139
+ {
140
+ id: "1mo",
141
+ ttlMs: MONTH_MS,
142
+ label: "1 个月 / 1 month",
143
+ aliases: ["1month", "month"],
144
+ },
145
+ {
146
+ id: "1y",
147
+ ttlMs: YEAR_MS,
148
+ label: "1 年 / 1 year",
149
+ aliases: ["1year", "year"],
150
+ },
151
+ {
152
+ id: "permanent",
153
+ ttlMs: EFFECTIVELY_PERMANENT_SESSION_TTL_MS,
154
+ label: "永久(100 年) / Permanent (100 years)",
155
+ aliases: ["forever", "infinite"],
156
+ },
157
+ ] as const;
158
+
159
+ const PRIVATECLAW_SETUP_MODE_CHOICES: readonly PrivateClawSetupChoice[] = [
160
+ {
161
+ value: "single",
162
+ label: "单独会话 / Single chat",
163
+ },
164
+ {
165
+ value: "group",
166
+ label: "群聊会话 / Group chat",
167
+ },
168
+ ] as const;
169
+
170
+ function createStep(
171
+ title: string,
172
+ command: string,
173
+ args: string[],
174
+ display: string,
175
+ ): PrivateClawSetupStep {
176
+ return {
177
+ title,
178
+ command,
179
+ args,
180
+ display,
181
+ };
182
+ }
183
+
184
+ function isUnavailableCommandError(error: unknown): error is NodeJS.ErrnoException {
185
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
186
+ return code === "ENOENT" || code === "EACCES" || code === "EPERM";
187
+ }
188
+
189
+ function isInteractiveTerminal(): boolean {
190
+ return Boolean(
191
+ process.stdin.isTTY &&
192
+ process.stdout.isTTY &&
193
+ !process.stdin.destroyed &&
194
+ !process.stdout.destroyed,
195
+ );
196
+ }
197
+
198
+ function delay(ms: number): Promise<void> {
199
+ return new Promise((resolve) => {
200
+ setTimeout(resolve, ms);
201
+ });
202
+ }
203
+
204
+ async function runOneShotCommand(
205
+ command: string,
206
+ args: string[],
207
+ ): Promise<RunOneShotCommandResult> {
208
+ const child = spawn(command, args, {
209
+ stdio: ["ignore", "pipe", "pipe"],
210
+ });
211
+ let stdoutText = "";
212
+ let stderrText = "";
213
+ child.stdout.setEncoding("utf8");
214
+ child.stderr.setEncoding("utf8");
215
+ child.stdout.on("data", (chunk: string) => {
216
+ stdoutText += chunk;
217
+ });
218
+ child.stderr.on("data", (chunk: string) => {
219
+ stderrText += chunk;
220
+ });
221
+ const childError = once(child, "error").then(([error]) => {
222
+ throw error;
223
+ });
224
+ const childClose = once(child, "close").then(([code, signal]) => ({
225
+ code,
226
+ signal,
227
+ }));
228
+
229
+ const { code, signal } = await Promise.race([childError, childClose]);
230
+ if (code !== 0) {
231
+ const combined = `${stdoutText}${stderrText}`.trim();
232
+ throw new Error(
233
+ `Command \`${[command, ...args].join(" ")}\` exited with ${
234
+ code == null ? `signal ${signal ?? "unknown"}` : `code ${code}`
235
+ }${combined ? `: ${combined}` : "."}`,
236
+ );
237
+ }
238
+ return {
239
+ stdout: stdoutText,
240
+ stderr: stderrText,
241
+ combined: `${stdoutText}${stderrText}`,
242
+ };
243
+ }
244
+
245
+ async function runStreamingCommand(
246
+ command: string,
247
+ args: string[],
248
+ ): Promise<RunOneShotCommandResult> {
249
+ const child = spawn(command, args, {
250
+ stdio: ["ignore", "pipe", "pipe"],
251
+ });
252
+ let stdoutText = "";
253
+ let stderrText = "";
254
+ child.stdout.setEncoding("utf8");
255
+ child.stderr.setEncoding("utf8");
256
+ child.stdout.on("data", (chunk: string) => {
257
+ stdoutText += chunk;
258
+ process.stdout.write(chunk);
259
+ });
260
+ child.stderr.on("data", (chunk: string) => {
261
+ stderrText += chunk;
262
+ process.stderr.write(chunk);
263
+ });
264
+ const childError = once(child, "error").then(([error]) => {
265
+ throw error;
266
+ });
267
+ const childClose = once(child, "close").then(([code, signal]) => ({
268
+ code,
269
+ signal,
270
+ }));
271
+
272
+ try {
273
+ const { code, signal } = await Promise.race([childError, childClose]);
274
+ if (code !== 0) {
275
+ throw new Error(
276
+ `Command \`${[command, ...args].join(" ")}\` exited with ${
277
+ code == null ? `signal ${signal ?? "unknown"}` : `code ${code}`
278
+ }.`,
279
+ );
280
+ }
281
+ return {
282
+ stdout: stdoutText,
283
+ stderr: stderrText,
284
+ combined: `${stdoutText}${stderrText}`,
285
+ };
286
+ } catch (error) {
287
+ if (isUnavailableCommandError(error)) {
288
+ throw new Error(
289
+ formatBilingualInline(
290
+ `无法运行 \`${[command, ...args].join(" ")}\`,因为本机缺少可执行命令 \`${command}\`。`,
291
+ `Could not run \`${[command, ...args].join(" ")}\` because \`${command}\` is unavailable or not executable locally.`,
292
+ ),
293
+ );
294
+ }
295
+ throw error;
296
+ }
297
+ }
298
+
299
+ async function commandExists(
300
+ command: string,
301
+ runCommand: OneShotCommandRunner = runOneShotCommand,
302
+ ): Promise<boolean> {
303
+ try {
304
+ await runCommand(command, ["--version"]);
305
+ return true;
306
+ } catch (error) {
307
+ return !isUnavailableCommandError(error);
308
+ }
309
+ }
310
+
311
+ function outputMentionsPrivateClawCommand(output: string): boolean {
312
+ return /\/?privateclaw\b/iu.test(output);
313
+ }
314
+
315
+ async function detectPrivateClawCommandAvailability(
316
+ runCommand: OneShotCommandRunner,
317
+ ): Promise<boolean> {
318
+ try {
319
+ const commands = await runCommand("openclaw", ["commands", "list"]);
320
+ if (outputMentionsPrivateClawCommand(commands.combined)) {
321
+ return true;
322
+ }
323
+ } catch {
324
+ // Newer OpenClaw builds may not expose `openclaw commands list`.
325
+ }
326
+
327
+ try {
328
+ await runCommand("openclaw", ["privateclaw", "pair", "--help"]);
329
+ return true;
330
+ } catch {
331
+ return false;
332
+ }
333
+ }
334
+
335
+ async function detectPrivateClawPluginPresence(
336
+ runCommand: OneShotCommandRunner,
337
+ ): Promise<boolean> {
338
+ try {
339
+ await runCommand("openclaw", ["plugins", "info", PRIVATECLAW_PLUGIN_ID]);
340
+ return true;
341
+ } catch {
342
+ return false;
343
+ }
344
+ }
345
+
346
+ export async function detectLocalOpenClawStatus(
347
+ runCommand: OneShotCommandRunner = runOneShotCommand,
348
+ ): Promise<LocalOpenClawStatus> {
349
+ if (!(await commandExists("openclaw", runCommand))) {
350
+ return {
351
+ openClawAvailable: false,
352
+ privateClawCommandAvailable: false,
353
+ };
354
+ }
355
+
356
+ const [privateClawCommandAvailable, privateClawPluginPresent] =
357
+ await Promise.all([
358
+ detectPrivateClawCommandAvailability(runCommand),
359
+ detectPrivateClawPluginPresence(runCommand),
360
+ ]);
361
+
362
+ return {
363
+ openClawAvailable: true,
364
+ privateClawCommandAvailable,
365
+ privateClawPluginPresent,
366
+ };
367
+ }
368
+
369
+ export async function resolveCurrentPrivateClawPackageSpec(): Promise<string> {
370
+ try {
371
+ const packageJsonUrl = new URL("../package.json", import.meta.url);
372
+ const packageJson = JSON.parse(
373
+ await readFile(packageJsonUrl, "utf8"),
374
+ ) as { name?: unknown; version?: unknown };
375
+ const packageName =
376
+ typeof packageJson.name === "string" && packageJson.name.trim() !== ""
377
+ ? packageJson.name.trim()
378
+ : PRIVATECLAW_PACKAGE_NAME;
379
+ const packageVersion =
380
+ typeof packageJson.version === "string" && packageJson.version.trim() !== ""
381
+ ? packageJson.version.trim()
382
+ : "latest";
383
+ return `${packageName}@${packageVersion}`;
384
+ } catch {
385
+ return `${PRIVATECLAW_PACKAGE_NAME}@latest`;
386
+ }
387
+ }
388
+
389
+ export function parsePrivateClawSessionDurationPreset(
390
+ value: string,
391
+ label = "--duration",
392
+ ): PrivateClawSessionDurationPreset {
393
+ const normalized = value.trim().toLowerCase();
394
+ const preset = PRIVATECLAW_SESSION_DURATION_PRESETS.find(
395
+ (entry) => entry.id === normalized || entry.aliases.includes(normalized),
396
+ );
397
+ if (!preset) {
398
+ throw new Error(
399
+ formatBilingualInline(
400
+ `${label} 仅支持这些预设:${PRIVATECLAW_SESSION_DURATION_PRESETS.map((entry) => entry.id).join(", ")}。`,
401
+ `${label} only supports these presets: ${PRIVATECLAW_SESSION_DURATION_PRESETS.map((entry) => entry.id).join(", ")}.`,
402
+ ),
403
+ );
404
+ }
405
+ return preset;
406
+ }
407
+
408
+ function buildPairingCommandStep(params: {
409
+ groupMode: boolean;
410
+ ttlMs: number;
411
+ relayBaseUrl?: string;
412
+ label?: string;
413
+ foreground?: boolean;
414
+ openInBrowser?: boolean;
415
+ verbose?: boolean;
416
+ }): PrivateClawSetupStep {
417
+ const args = [
418
+ "privateclaw",
419
+ "pair",
420
+ "--ttl-ms",
421
+ String(params.ttlMs),
422
+ ];
423
+ if (params.groupMode) {
424
+ args.push("--group");
425
+ }
426
+ if (params.label) {
427
+ args.push("--label", params.label);
428
+ }
429
+ if (params.relayBaseUrl) {
430
+ args.push("--relay", params.relayBaseUrl);
431
+ }
432
+ if (params.openInBrowser) {
433
+ args.push("--open");
434
+ }
435
+ if (params.foreground) {
436
+ args.push("--foreground");
437
+ }
438
+ if (params.verbose) {
439
+ args.push("--verbose");
440
+ }
441
+ return createStep(
442
+ "Start the requested PrivateClaw pairing flow",
443
+ "openclaw",
444
+ args,
445
+ `openclaw ${args.join(" ")}`,
446
+ );
447
+ }
448
+
449
+ export async function resolvePrivateClawSetupSelection(params: {
450
+ groupMode?: boolean;
451
+ ttlMs?: number;
452
+ durationPreset?: string;
453
+ promptForChoice?: (
454
+ question: string,
455
+ choices: readonly PrivateClawSetupChoice[],
456
+ defaultValue?: string,
457
+ ) => Promise<string>;
458
+ }): Promise<PrivateClawSetupSelection> {
459
+ const promptForChoice = params.promptForChoice ?? promptForPrivateClawChoice;
460
+ let groupMode = params.groupMode;
461
+ if (typeof groupMode !== "boolean") {
462
+ const mode = await promptForChoice(
463
+ formatBilingualInline(
464
+ "请选择要创建的会话类型:",
465
+ "Choose which session type to start:",
466
+ ),
467
+ PRIVATECLAW_SETUP_MODE_CHOICES,
468
+ "single",
469
+ );
470
+ groupMode = mode === "group";
471
+ }
472
+
473
+ if (typeof params.ttlMs === "number") {
474
+ return {
475
+ groupMode,
476
+ ttlMs: params.ttlMs,
477
+ durationLabel: formatBilingualInline(
478
+ `${params.ttlMs} 毫秒`,
479
+ `${params.ttlMs} ms`,
480
+ ),
481
+ };
482
+ }
483
+
484
+ if (params.durationPreset) {
485
+ const preset = parsePrivateClawSessionDurationPreset(params.durationPreset);
486
+ return {
487
+ groupMode,
488
+ ttlMs: preset.ttlMs,
489
+ durationLabel: preset.label,
490
+ };
491
+ }
492
+
493
+ const durationChoices = PRIVATECLAW_SESSION_DURATION_PRESETS.map((preset) => ({
494
+ value: preset.id,
495
+ label: preset.label,
496
+ }));
497
+ const durationPresetId = await promptForChoice(
498
+ formatBilingualInline(
499
+ "请选择本次会话时长:",
500
+ "Choose the session duration:",
501
+ ),
502
+ durationChoices,
503
+ "24h",
504
+ );
505
+ const preset = parsePrivateClawSessionDurationPreset(durationPresetId);
506
+ return {
507
+ groupMode,
508
+ ttlMs: preset.ttlMs,
509
+ durationLabel: preset.label,
510
+ };
511
+ }
512
+
513
+ export function buildPrivateClawSetupPlan(params: {
514
+ packageSpec: string;
515
+ status: LocalOpenClawStatus;
516
+ selection: PrivateClawSetupSelection;
517
+ relayBaseUrl?: string;
518
+ label?: string;
519
+ foreground?: boolean;
520
+ openInBrowser?: boolean;
521
+ verbose?: boolean;
522
+ }): PrivateClawSetupPlan {
523
+ const installStep = createStep(
524
+ "Install the PrivateClaw OpenClaw plugin",
525
+ "openclaw",
526
+ ["plugins", "install", params.packageSpec],
527
+ `openclaw plugins install ${params.packageSpec}`,
528
+ );
529
+ const updateStep = createStep(
530
+ "Update the existing PrivateClaw OpenClaw plugin",
531
+ "openclaw",
532
+ ["plugins", "update", PRIVATECLAW_PLUGIN_ID],
533
+ `openclaw plugins update ${PRIVATECLAW_PLUGIN_ID}`,
534
+ );
535
+ const enableStep = createStep(
536
+ "Enable the PrivateClaw OpenClaw plugin",
537
+ "openclaw",
538
+ ["plugins", "enable", PRIVATECLAW_PLUGIN_ID],
539
+ `openclaw plugins enable ${PRIVATECLAW_PLUGIN_ID}`,
540
+ );
541
+ const restartStep = createStep(
542
+ "Restart the OpenClaw gateway so the new plugin command is reloaded",
543
+ "openclaw",
544
+ ["gateway", "restart"],
545
+ "openclaw gateway restart",
546
+ );
547
+ const pairingCommand = buildPairingCommandStep({
548
+ groupMode: params.selection.groupMode,
549
+ ttlMs: params.selection.ttlMs,
550
+ ...(params.relayBaseUrl ? { relayBaseUrl: params.relayBaseUrl } : {}),
551
+ ...(params.label ? { label: params.label } : {}),
552
+ ...(params.foreground ? { foreground: true } : {}),
553
+ ...(params.openInBrowser ? { openInBrowser: true } : {}),
554
+ ...(params.verbose ? { verbose: true } : {}),
555
+ });
556
+ const selectionNotes = [
557
+ formatBilingualInline(
558
+ `配对模式:${params.selection.groupMode ? "群聊" : "单独会话"}`,
559
+ `Pairing mode: ${params.selection.groupMode ? "group chat" : "single chat"}`,
560
+ ),
561
+ formatBilingualInline(
562
+ `会话时长:${params.selection.durationLabel.split(" / ")[0]}`,
563
+ `Session duration: ${params.selection.durationLabel.split(" / ")[1] ?? params.selection.durationLabel}`,
564
+ ),
565
+ ];
566
+ const verificationNotes = [
567
+ `[privateclaw-provider] ${formatBilingualInline(
568
+ `若需要手工确认插件命令是否就绪,可运行:${PRIVATECLAW_VERIFICATION_COMMAND}`,
569
+ `If you want to verify the plugin command manually, run: ${PRIVATECLAW_VERIFICATION_COMMAND}`,
570
+ )}`,
571
+ ];
572
+
573
+ if (!params.status.openClawAvailable) {
574
+ return {
575
+ packageSpec: params.packageSpec,
576
+ localOpenClaw: false,
577
+ privateClawCommandAvailable: false,
578
+ introduction:
579
+ `[privateclaw-provider] ${formatBilingualInline(
580
+ "当前机器上未检测到 `openclaw`。请先在安装了 OpenClaw 的机器上执行下面这些命令:",
581
+ "Could not detect `openclaw` on this machine. Run these commands on the machine where OpenClaw is installed:",
582
+ )}`,
583
+ automaticSteps: [],
584
+ manualSteps: [installStep, enableStep, restartStep, pairingCommand],
585
+ selectionNotes,
586
+ verificationNotes,
587
+ pairingCommand,
588
+ };
589
+ }
590
+
591
+ if (params.status.privateClawCommandAvailable) {
592
+ return {
593
+ packageSpec: params.packageSpec,
594
+ localOpenClaw: true,
595
+ privateClawCommandAvailable: true,
596
+ introduction:
597
+ `[privateclaw-provider] ${formatBilingualInline(
598
+ "本机的 OpenClaw + PrivateClaw 已经可用,接下来直接开始配对:",
599
+ "OpenClaw + PrivateClaw are already available locally. Starting pairing next:",
600
+ )}`,
601
+ automaticSteps: [],
602
+ manualSteps: [pairingCommand],
603
+ selectionNotes,
604
+ verificationNotes,
605
+ pairingCommand,
606
+ };
607
+ }
608
+
609
+ return {
610
+ packageSpec: params.packageSpec,
611
+ localOpenClaw: true,
612
+ privateClawCommandAvailable: false,
613
+ introduction:
614
+ `[privateclaw-provider] ${formatBilingualInline(
615
+ params.status.privateClawPluginPresent
616
+ ? "检测到本机已经安装过 PrivateClaw 插件,但命令还没有生效。现在会更新、启用并重启 OpenClaw:"
617
+ : "检测到本机可以直接运行 OpenClaw。现在会安装、启用 PrivateClaw 插件并重启 OpenClaw:",
618
+ params.status.privateClawPluginPresent
619
+ ? "A local PrivateClaw plugin is already present, but the command is not active yet. Updating, enabling, and restarting OpenClaw now:"
620
+ : "OpenClaw is available locally. Installing, enabling, and restarting the PrivateClaw plugin now:",
621
+ )}`,
622
+ automaticSteps: [
623
+ ...(params.status.privateClawPluginPresent ? [updateStep] : [installStep]),
624
+ enableStep,
625
+ restartStep,
626
+ ],
627
+ manualSteps: [
628
+ ...(params.status.privateClawPluginPresent ? [updateStep] : [installStep]),
629
+ enableStep,
630
+ restartStep,
631
+ pairingCommand,
632
+ ],
633
+ selectionNotes,
634
+ verificationNotes,
635
+ pairingCommand,
636
+ };
637
+ }
638
+
639
+ export function renderPrivateClawSetupGuidance(
640
+ plan: PrivateClawSetupPlan,
641
+ ): string {
642
+ return [
643
+ plan.introduction,
644
+ ...plan.selectionNotes.map((line) => `[privateclaw-provider] ${line}`),
645
+ ...plan.manualSteps.map((step) => `[privateclaw-provider] ${step.display}`),
646
+ ...plan.verificationNotes,
647
+ ].join("\n");
648
+ }
649
+
650
+ async function promptForPrivateClawChoice(
651
+ question: string,
652
+ choices: readonly PrivateClawSetupChoice[],
653
+ defaultValue?: string,
654
+ ): Promise<string> {
655
+ if (!isInteractiveTerminal()) {
656
+ throw new Error(
657
+ formatBilingualInline(
658
+ "当前终端不是交互式终端;请改为显式传入 setup 参数。",
659
+ "The current terminal is not interactive; pass explicit setup flags instead.",
660
+ ),
661
+ );
662
+ }
663
+ const rl = createInterface({
664
+ input: stdin,
665
+ output: stdout,
666
+ });
667
+ try {
668
+ while (true) {
669
+ console.log(question);
670
+ for (const [index, choice] of choices.entries()) {
671
+ const isDefault = defaultValue === choice.value;
672
+ console.log(
673
+ `${index + 1}. ${choice.label}${isDefault ? ` ${formatBilingualInline("(默认)", "(default)")}` : ""}`,
674
+ );
675
+ }
676
+ const answer = await rl.question(
677
+ `${formatBilingualInline("请输入序号", "Enter a number")} [1-${choices.length}]${defaultValue ? ` ${formatBilingualInline("留空使用默认值", "press Enter for the default")}` : ""}: `,
678
+ );
679
+ const normalized = answer.trim().toLowerCase();
680
+ if (normalized === "" && defaultValue) {
681
+ return defaultValue;
682
+ }
683
+ const numeric = Number.parseInt(normalized, 10);
684
+ if (
685
+ Number.isInteger(numeric) &&
686
+ numeric >= 1 &&
687
+ numeric <= choices.length
688
+ ) {
689
+ return choices[numeric - 1]!.value;
690
+ }
691
+ const matchedChoice = choices.find(
692
+ (choice) => choice.value.toLowerCase() === normalized,
693
+ );
694
+ if (matchedChoice) {
695
+ return matchedChoice.value;
696
+ }
697
+ console.log(
698
+ formatBilingualInline(
699
+ "无效输入,请重新选择。",
700
+ "Invalid input. Please choose again.",
701
+ ),
702
+ );
703
+ }
704
+ } finally {
705
+ rl.close();
706
+ }
707
+ }
708
+
709
+ async function runPrivateClawSetupStep(
710
+ step: PrivateClawSetupStep,
711
+ ): Promise<void> {
712
+ await runStreamingCommand(step.command, step.args);
713
+ }
714
+
715
+ async function waitForPrivateClawCommandAvailability(
716
+ detectStatus: () => Promise<LocalOpenClawStatus>,
717
+ timeoutMs: number,
718
+ pollMs: number,
719
+ ): Promise<LocalOpenClawStatus> {
720
+ const deadline = Date.now() + timeoutMs;
721
+ let status = await detectStatus();
722
+ while (
723
+ status.openClawAvailable &&
724
+ !status.privateClawCommandAvailable &&
725
+ Date.now() < deadline
726
+ ) {
727
+ await delay(pollMs);
728
+ status = await detectStatus();
729
+ }
730
+ return status;
731
+ }
732
+
733
+ export async function runPrivateClawSetup(
734
+ options: RunPrivateClawSetupOptions = {},
735
+ ): Promise<void> {
736
+ const detectStatus =
737
+ options.detectLocalOpenClawStatus ?? detectLocalOpenClawStatus;
738
+ const packageSpec =
739
+ options.packageSpec ?? (await resolveCurrentPrivateClawPackageSpec());
740
+ const selection =
741
+ options.selection ??
742
+ (await resolvePrivateClawSetupSelection({
743
+ ...(typeof options.groupMode === "boolean"
744
+ ? { groupMode: options.groupMode }
745
+ : {}),
746
+ ...(typeof options.ttlMs === "number" ? { ttlMs: options.ttlMs } : {}),
747
+ ...(options.durationPreset ? { durationPreset: options.durationPreset } : {}),
748
+ ...(options.promptForChoice
749
+ ? { promptForChoice: options.promptForChoice }
750
+ : {}),
751
+ }));
752
+ const status = await detectStatus();
753
+ const plan = buildPrivateClawSetupPlan({
754
+ packageSpec,
755
+ status,
756
+ selection,
757
+ ...(options.relayBaseUrl ? { relayBaseUrl: options.relayBaseUrl } : {}),
758
+ ...(options.label ? { label: options.label } : {}),
759
+ ...(options.foreground ? { foreground: true } : {}),
760
+ ...(options.openInBrowser ? { openInBrowser: true } : {}),
761
+ ...(options.verbose ? { verbose: true } : {}),
762
+ });
763
+ const guidance = renderPrivateClawSetupGuidance(plan);
764
+ const log = options.onLog ?? ((line: string) => console.log(line));
765
+ for (const line of guidance.split("\n")) {
766
+ log(line);
767
+ }
768
+
769
+ if (!plan.localOpenClaw) {
770
+ throw new Error(
771
+ formatBilingualInline(
772
+ "当前机器上还没有可用的 `openclaw` 命令,无法继续自动安装 PrivateClaw 插件。",
773
+ "This machine does not have a working `openclaw` command yet, so the PrivateClaw plugin cannot be installed automatically.",
774
+ ),
775
+ );
776
+ }
777
+
778
+ const runStep = options.runStep ?? runPrivateClawSetupStep;
779
+ const runPairingCommand =
780
+ options.runPairingCommand ??
781
+ ((step: PrivateClawSetupStep) => runStreamingCommand(step.command, step.args));
782
+
783
+ for (const step of plan.automaticSteps) {
784
+ log(`[privateclaw-provider] ${formatBilingualInline("正在执行", "Running")}: ${step.display}`);
785
+ await runStep(step);
786
+ }
787
+
788
+ if (!plan.privateClawCommandAvailable) {
789
+ const refreshedStatus = await waitForPrivateClawCommandAvailability(
790
+ detectStatus,
791
+ options.verificationTimeoutMs ?? 15_000,
792
+ options.verificationPollMs ?? 1_000,
793
+ );
794
+ if (!refreshedStatus.privateClawCommandAvailable) {
795
+ throw new Error(
796
+ formatBilingualInline(
797
+ `OpenClaw 已重载,但 \`privateclaw\` 仍然无法响应 \`${PRIVATECLAW_VERIFICATION_COMMAND}\`。请确认 gateway 已正常重启后再试。`,
798
+ `OpenClaw reloaded, but \`privateclaw\` still does not respond to \`${PRIVATECLAW_VERIFICATION_COMMAND}\`. Confirm the gateway restarted cleanly, then try again.`,
799
+ ),
800
+ );
801
+ }
802
+ log(
803
+ `[privateclaw-provider] ${formatBilingualInline(
804
+ `已确认命令就绪:${PRIVATECLAW_VERIFICATION_COMMAND}`,
805
+ `Verified command availability with: ${PRIVATECLAW_VERIFICATION_COMMAND}`,
806
+ )}`,
807
+ );
808
+ }
809
+
810
+ log(
811
+ `[privateclaw-provider] ${formatBilingualInline("开始配对", "Starting pairing")}: ${plan.pairingCommand.display}`,
812
+ );
813
+ await runPairingCommand(plan.pairingCommand);
814
+ }