@privateclaw/privateclaw 0.1.0 → 0.1.1

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.
Files changed (50) hide show
  1. package/README.md +88 -6
  2. package/dist/bridges/openclaw-agent-bridge.d.ts +5 -0
  3. package/dist/bridges/openclaw-agent-bridge.js +228 -15
  4. package/dist/bridges/openclaw-agent-bridge.js.map +1 -1
  5. package/dist/cli.js +11 -19
  6. package/dist/cli.js.map +1 -1
  7. package/dist/compat/openclaw.d.ts +18 -1
  8. package/dist/compat/openclaw.js +3 -1
  9. package/dist/compat/openclaw.js.map +1 -1
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.js +1 -0
  12. package/dist/index.js.map +1 -1
  13. package/dist/openclaw-plugin.js +90 -15
  14. package/dist/openclaw-plugin.js.map +1 -1
  15. package/dist/pair-session.d.ts +12 -0
  16. package/dist/pair-session.js +63 -0
  17. package/dist/pair-session.js.map +1 -0
  18. package/dist/provider.d.ts +22 -1
  19. package/dist/provider.js +613 -60
  20. package/dist/provider.js.map +1 -1
  21. package/dist/qr-options.d.ts +5 -0
  22. package/dist/qr-options.js +6 -0
  23. package/dist/qr-options.js.map +1 -0
  24. package/dist/relay-defaults.d.ts +1 -0
  25. package/dist/relay-defaults.js +2 -0
  26. package/dist/relay-defaults.js.map +1 -0
  27. package/dist/relay-provider-client.d.ts +2 -2
  28. package/dist/relay-provider-client.js +9 -3
  29. package/dist/relay-provider-client.js.map +1 -1
  30. package/dist/text.d.ts +22 -0
  31. package/dist/text.js +32 -0
  32. package/dist/text.js.map +1 -0
  33. package/dist/types.d.ts +14 -1
  34. package/openclaw.plugin.json +3 -2
  35. package/package.json +1 -1
  36. package/src/bridges/openclaw-agent-bridge.test.ts +141 -0
  37. package/src/bridges/openclaw-agent-bridge.ts +302 -16
  38. package/src/cli.ts +14 -22
  39. package/src/compat/openclaw.ts +30 -1
  40. package/src/index.ts +1 -0
  41. package/src/openclaw-plugin.test.ts +139 -0
  42. package/src/openclaw-plugin.ts +137 -15
  43. package/src/pair-session.ts +100 -0
  44. package/src/provider.test.ts +704 -1
  45. package/src/provider.ts +933 -60
  46. package/src/qr-options.ts +5 -0
  47. package/src/relay-defaults.ts +1 -0
  48. package/src/relay-provider-client.ts +13 -2
  49. package/src/text.ts +108 -0
  50. package/src/types.ts +15 -0
@@ -6,7 +6,11 @@ import test from "node:test";
6
6
  import { decodeInviteString } from "@privateclaw/protocol";
7
7
  import { createRelayServer } from "../../../services/relay-server/src/relay-server.js";
8
8
  import { EchoBridge } from "./bridges/echo-bridge.js";
9
+ import { privateClawConfigSchema } from "./compat/openclaw.js";
10
+ import { DEFAULT_SESSION_TTL_MS } from "./provider.js";
11
+ import { DEFAULT_RELAY_BASE_URL } from "./relay-defaults.js";
9
12
  import type {
13
+ OpenClawPluginCliRegistrarCompat,
10
14
  OpenClawPluginApiCompat,
11
15
  OpenClawPluginCommandDefinitionCompat,
12
16
  OpenClawPluginServiceCompat,
@@ -17,10 +21,17 @@ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0
17
21
 
18
22
  function createMockApi(): {
19
23
  api: OpenClawPluginApiCompat;
24
+ getCli(): { registrar: OpenClawPluginCliRegistrarCompat; commands: string[] };
20
25
  getCommand(): OpenClawPluginCommandDefinitionCompat;
21
26
  getService(): OpenClawPluginServiceCompat;
22
27
  } {
23
28
  let command: OpenClawPluginCommandDefinitionCompat | undefined;
29
+ let cli:
30
+ | {
31
+ registrar: OpenClawPluginCliRegistrarCompat;
32
+ commands: string[];
33
+ }
34
+ | undefined;
24
35
  let service: OpenClawPluginServiceCompat | undefined;
25
36
  const logger = {
26
37
  info: (_message: string) => undefined,
@@ -35,10 +46,20 @@ function createMockApi(): {
35
46
  registerCommand(registeredCommand) {
36
47
  command = registeredCommand;
37
48
  },
49
+ registerCli(registrar, opts) {
50
+ cli = {
51
+ registrar,
52
+ commands: opts?.commands ?? [],
53
+ };
54
+ },
38
55
  registerService(registeredService) {
39
56
  service = registeredService;
40
57
  },
41
58
  },
59
+ getCli() {
60
+ assert.ok(cli, "plugin should register the local privateclaw CLI");
61
+ return cli;
62
+ },
42
63
  getCommand() {
43
64
  assert.ok(command, "plugin should register the /privateclaw command");
44
65
  return command;
@@ -50,6 +71,39 @@ function createMockApi(): {
50
71
  };
51
72
  }
52
73
 
74
+ class FakeCliCommand {
75
+ readonly children = new Map<string, FakeCliCommand>();
76
+ actionHandler: ((...args: unknown[]) => void | Promise<void>) | undefined;
77
+
78
+ constructor(readonly name: string) {}
79
+
80
+ command(name: string): FakeCliCommand {
81
+ const child = new FakeCliCommand(name);
82
+ this.children.set(name, child);
83
+ return child;
84
+ }
85
+
86
+ description(_text: string): FakeCliCommand {
87
+ return this;
88
+ }
89
+
90
+ option(_flags: string, _description?: string, _defaultValue?: string | boolean): FakeCliCommand {
91
+ return this;
92
+ }
93
+
94
+ action(handler: (...args: unknown[]) => void | Promise<void>): FakeCliCommand {
95
+ this.actionHandler = handler;
96
+ return this;
97
+ }
98
+ }
99
+
100
+ test("privateclaw schema advertises the public relay default", () => {
101
+ assert.equal(
102
+ privateClawConfigSchema.properties.relayBaseUrl.default,
103
+ DEFAULT_RELAY_BASE_URL,
104
+ );
105
+ });
106
+
53
107
  test("privateclaw command writes QR media into the OpenClaw state media directory", async (t) => {
54
108
  const relay = createRelayServer({
55
109
  host: "127.0.0.1",
@@ -100,11 +154,18 @@ test("privateclaw command writes QR media into the OpenClaw state media director
100
154
  assert.equal(reply.isError, undefined);
101
155
  assert.ok(reply.text);
102
156
  assert.ok(reply.mediaUrl);
157
+ assert.match(reply.text, /邀请链接 \/ Invite URI/);
158
+ assert.match(reply.text, /PrivateClaw 会话|PrivateClaw session/);
103
159
 
104
160
  const inviteUri = reply.text.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
105
161
  assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
106
162
 
107
163
  const invite = decodeInviteString(inviteUri);
164
+ const remainingMs = new Date(invite.expiresAt).getTime() - Date.now();
165
+ assert.ok(
166
+ remainingMs > DEFAULT_SESSION_TTL_MS - 60_000,
167
+ "new sessions should default to roughly 8 hours even when relay default TTL is shorter",
168
+ );
108
169
  const expectedMediaDir = path.join(stateDir, "media", "privateclaw");
109
170
  assert.equal(path.dirname(reply.mediaUrl), expectedMediaDir);
110
171
  assert.equal(path.basename(reply.mediaUrl), `privateclaw-${invite.sessionId}.png`);
@@ -112,3 +173,81 @@ test("privateclaw command writes QR media into the OpenClaw state media director
112
173
  const qrPng = await readFile(reply.mediaUrl);
113
174
  assert.deepEqual(qrPng.subarray(0, PNG_SIGNATURE.length), PNG_SIGNATURE);
114
175
  });
176
+
177
+ test("privateclaw plugin local pair CLI defaults to the long session TTL", async (t) => {
178
+ const relay = createRelayServer({
179
+ host: "127.0.0.1",
180
+ port: 0,
181
+ sessionTtlMs: 60_000,
182
+ frameCacheSize: 8,
183
+ });
184
+ const { port } = await relay.start();
185
+
186
+ t.after(async () => {
187
+ await relay.stop();
188
+ });
189
+
190
+ const plugin = createOpenClawCompatiblePlugin({
191
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
192
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
193
+ bridge: new EchoBridge("OpenClaw bridge"),
194
+ });
195
+ const { api, getCli } = createMockApi();
196
+ plugin.register(api);
197
+
198
+ const cli = getCli();
199
+ assert.deepEqual(cli.commands, ["privateclaw"]);
200
+
201
+ const root = new FakeCliCommand("root");
202
+ await cli.registrar({
203
+ program: root,
204
+ config: {},
205
+ logger: api.logger,
206
+ });
207
+
208
+ const privateclaw = root.children.get("privateclaw");
209
+ assert.ok(privateclaw, "plugin should register a top-level privateclaw command");
210
+
211
+ const pair = privateclaw.children.get("pair");
212
+ assert.ok(pair?.actionHandler, "plugin should register the privateclaw pair subcommand");
213
+
214
+ const printed: string[] = [];
215
+ const originalLog = console.log;
216
+ console.log = (message?: unknown, ...optionalParams: unknown[]) => {
217
+ printed.push([message, ...optionalParams].map(String).join(" "));
218
+ };
219
+ t.after(() => {
220
+ console.log = originalLog;
221
+ });
222
+
223
+ await pair.actionHandler({
224
+ label: "CLI pairing session",
225
+ printOnly: true,
226
+ });
227
+
228
+ assert.ok(
229
+ printed.some(
230
+ (line) =>
231
+ line.includes("PrivateClaw 会话") || line.includes("PrivateClaw session"),
232
+ ),
233
+ "pair command should print the invite announcement",
234
+ );
235
+ assert.ok(
236
+ printed.some((line) =>
237
+ line.startsWith("邀请链接 / Invite URI: privateclaw://connect?payload="),
238
+ ),
239
+ "pair command should print the invite URI",
240
+ );
241
+ const inviteUri = printed.find((line) =>
242
+ line.startsWith("邀请链接 / Invite URI: privateclaw://connect?payload="),
243
+ );
244
+ assert.ok(inviteUri, "pair command should print a PrivateClaw invite URI");
245
+ const invite = decodeInviteString(
246
+ inviteUri.replace("邀请链接 / Invite URI: ", ""),
247
+ );
248
+ const remainingMs = new Date(invite.expiresAt).getTime() - Date.now();
249
+ assert.ok(
250
+ remainingMs > DEFAULT_SESSION_TTL_MS - 60_000,
251
+ "local pair sessions should default to roughly 8 hours even when relay default TTL is shorter",
252
+ );
253
+ });
@@ -8,6 +8,12 @@ import {
8
8
  type OpenClawAgentBridgeOptions,
9
9
  } from "./bridges/openclaw-agent-bridge.js";
10
10
  import { loadAvailableOpenClawCommands } from "./openclaw-command-discovery.js";
11
+ import { parsePositiveIntegerFlag, runPairSession } from "./pair-session.js";
12
+ import {
13
+ PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL,
14
+ PRIVATECLAW_QR_IMAGE_MARGIN,
15
+ PRIVATECLAW_QR_PNG_WIDTH,
16
+ } from "./qr-options.js";
11
17
  import { WebhookBridge } from "./bridges/webhook-bridge.js";
12
18
  import {
13
19
  type OpenClawExtensionPluginCompat,
@@ -16,8 +22,21 @@ import {
16
22
  type ReplyPayloadCompat,
17
23
  privateClawConfigSchema,
18
24
  } from "./compat/openclaw.js";
19
- import { PrivateClawProvider } from "./provider.js";
25
+ import { DEFAULT_SESSION_TTL_MS, PrivateClawProvider } from "./provider.js";
26
+ import { DEFAULT_RELAY_BASE_URL } from "./relay-defaults.js";
20
27
  import { resolveRelayEndpoints } from "./relay-endpoints.js";
28
+ import {
29
+ buildPrivateClawCommandErrorMessage,
30
+ PRIVATECLAW_CLI_GROUP_OPTION_DESCRIPTION,
31
+ PRIVATECLAW_CLI_LABEL_OPTION_DESCRIPTION,
32
+ PRIVATECLAW_CLI_PAIR_DESCRIPTION,
33
+ PRIVATECLAW_CLI_PRINT_ONLY_OPTION_DESCRIPTION,
34
+ PRIVATECLAW_CLI_ROOT_DESCRIPTION,
35
+ PRIVATECLAW_CLI_TTL_OPTION_DESCRIPTION,
36
+ PRIVATECLAW_COMMAND_DESCRIPTION,
37
+ PRIVATECLAW_INVITE_URI_LABEL,
38
+ PRIVATECLAW_PLUGIN_DESCRIPTION,
39
+ } from "./text.js";
21
40
  import type {
22
41
  PrivateClawAgentBridge,
23
42
  PrivateClawInviteBundle,
@@ -67,7 +86,13 @@ interface ResolvedPrivateClawPluginConfig {
67
86
  openclawAgentTimeoutSeconds?: number;
68
87
  }
69
88
 
70
- const DEFAULT_RELAY_BASE_URL = "ws://127.0.0.1:8787";
89
+ interface PrivateClawPairCliOptions {
90
+ ttlMs?: string;
91
+ label?: string;
92
+ printOnly?: boolean;
93
+ group?: boolean;
94
+ }
95
+
71
96
  const DEFAULT_PROVIDER_LABEL = "PrivateClaw";
72
97
  const DEFAULT_BRIDGE_MODE: PrivateClawBridgeMode = "openclaw-agent";
73
98
  const ALLOWED_THINKING_LEVELS = new Set<OpenClawThinkingLevel>([
@@ -159,7 +184,8 @@ function resolvePluginConfig(
159
184
 
160
185
  const sessionTtlMs =
161
186
  readNumber(pluginConfig?.sessionTtlMs) ??
162
- readNumber(process.env.PRIVATECLAW_SESSION_TTL_MS);
187
+ readNumber(process.env.PRIVATECLAW_SESSION_TTL_MS) ??
188
+ DEFAULT_SESSION_TTL_MS;
163
189
  const welcomeMessage =
164
190
  readString(pluginConfig?.welcomeMessage) ??
165
191
  readString(process.env.PRIVATECLAW_WELCOME_MESSAGE);
@@ -259,6 +285,36 @@ function buildBridge(config: ResolvedPrivateClawPluginConfig): PrivateClawAgentB
259
285
  });
260
286
  }
261
287
 
288
+ function normalizePairCliOptions(raw: unknown): PrivateClawPairCliOptions {
289
+ if (!raw || typeof raw !== "object") {
290
+ return {};
291
+ }
292
+
293
+ const options = raw as Record<string, unknown>;
294
+ const ttlMs = readString(options.ttlMs);
295
+ const label = readString(options.label);
296
+ return {
297
+ ...(ttlMs ? { ttlMs } : {}),
298
+ ...(label ? { label } : {}),
299
+ ...(typeof options.printOnly === "boolean" ? { printOnly: options.printOnly } : {}),
300
+ ...(typeof options.group === "boolean" ? { group: options.group } : {}),
301
+ };
302
+ }
303
+
304
+ function parsePrivateClawCommandArgs(raw: string | undefined): {
305
+ groupMode?: boolean;
306
+ } {
307
+ const normalizedArgs = (raw ?? "")
308
+ .split(/\s+/)
309
+ .map((token) => token.trim().toLowerCase())
310
+ .filter((token) => token !== "");
311
+ return normalizedArgs.some(
312
+ (token) => token === "group" || token === "--group" || token === "-g",
313
+ )
314
+ ? { groupMode: true }
315
+ : {};
316
+ }
317
+
262
318
  function buildProviderOptions(
263
319
  pluginConfig: ResolvedPrivateClawPluginConfig,
264
320
  api: Pick<OpenClawPluginApiCompat, "logger">,
@@ -295,7 +351,7 @@ class PrivateClawPluginRuntime {
295
351
 
296
352
  constructor(
297
353
  private readonly providerOptions: PrivateClawProviderOptions,
298
- private readonly defaultTtlMs?: number,
354
+ private readonly defaultTtlMs: number = DEFAULT_SESSION_TTL_MS,
299
355
  ) {}
300
356
 
301
357
  setStateDir(stateDir: string): void {
@@ -318,14 +374,26 @@ class PrivateClawPluginRuntime {
318
374
  return this.provider;
319
375
  }
320
376
 
321
- async createInviteBundle(): Promise<PrivateClawInviteBundle> {
377
+ async createInviteBundle(params?: {
378
+ ttlMs?: number;
379
+ label?: string;
380
+ groupMode?: boolean;
381
+ }): Promise<PrivateClawInviteBundle> {
322
382
  return this.getProvider().createInviteBundle(
323
- typeof this.defaultTtlMs === "number" ? { ttlMs: this.defaultTtlMs } : undefined,
383
+ {
384
+ ...(typeof params?.ttlMs === "number"
385
+ ? { ttlMs: params.ttlMs }
386
+ : typeof this.defaultTtlMs === "number"
387
+ ? { ttlMs: this.defaultTtlMs }
388
+ : {}),
389
+ ...(params?.label ? { label: params.label } : {}),
390
+ ...(params?.groupMode === true ? { groupMode: true } : {}),
391
+ },
324
392
  );
325
393
  }
326
394
 
327
395
  async buildCommandReply(bundle: PrivateClawInviteBundle): Promise<ReplyPayloadCompat> {
328
- const text = `${bundle.announcementText}\n\nOpen invite:\n${bundle.inviteUri}`;
396
+ const text = `${bundle.announcementText}\n\n${PRIVATECLAW_INVITE_URI_LABEL}:\n${bundle.inviteUri}`;
329
397
  const qrPngPath = await writeInviteQrPng(bundle, this.getMediaDir());
330
398
  return {
331
399
  text,
@@ -333,6 +401,25 @@ class PrivateClawPluginRuntime {
333
401
  };
334
402
  }
335
403
 
404
+ async runPairSession(params?: {
405
+ ttlMs?: number;
406
+ label?: string;
407
+ printOnly?: boolean;
408
+ groupMode?: boolean;
409
+ writeLine?: (line: string) => void;
410
+ }): Promise<PrivateClawInviteBundle> {
411
+ return runPairSession({
412
+ provider: this.getProvider(),
413
+ ...(typeof params?.ttlMs === "number"
414
+ ? { ttlMs: params.ttlMs }
415
+ : { ttlMs: this.defaultTtlMs }),
416
+ ...(params?.label ? { label: params.label } : {}),
417
+ ...(typeof params?.printOnly === "boolean" ? { printOnly: params.printOnly } : {}),
418
+ ...(params?.groupMode === true ? { groupMode: true } : {}),
419
+ ...(params?.writeLine ? { writeLine: params.writeLine } : {}),
420
+ });
421
+ }
422
+
336
423
  async dispose(): Promise<void> {
337
424
  if (!this.provider) {
338
425
  return;
@@ -349,9 +436,9 @@ async function writeInviteQrPng(
349
436
  ): Promise<string> {
350
437
  const pngBuffer = await QRCode.toBuffer(bundle.inviteUri, {
351
438
  type: "png",
352
- errorCorrectionLevel: "M",
353
- margin: 1,
354
- width: 512,
439
+ errorCorrectionLevel: PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL,
440
+ margin: PRIVATECLAW_QR_IMAGE_MARGIN,
441
+ width: PRIVATECLAW_QR_PNG_WIDTH,
355
442
  });
356
443
  await mkdir(mediaDir, { recursive: true });
357
444
  const qrPath = path.join(mediaDir, `privateclaw-${bundle.invite.sessionId}.png`);
@@ -369,7 +456,7 @@ function createPluginDefinition(
369
456
  return {
370
457
  id: "privateclaw",
371
458
  name: "PrivateClaw",
372
- description: "Ephemeral end-to-end encrypted private session plugin for OpenClaw.",
459
+ description: PRIVATECLAW_PLUGIN_DESCRIPTION,
373
460
  configSchema: privateClawConfigSchema,
374
461
  register(api: OpenClawPluginApiCompat) {
375
462
  const runtime = runtimeFactory(api);
@@ -386,15 +473,17 @@ function createPluginDefinition(
386
473
 
387
474
  api.registerCommand({
388
475
  name: "privateclaw",
389
- description: "Create a one-time encrypted PrivateClaw session QR code.",
390
- acceptsArgs: false,
476
+ description: PRIVATECLAW_COMMAND_DESCRIPTION,
477
+ acceptsArgs: true,
391
478
  requireAuth: true,
392
479
  handler: async (ctx: OpenClawPluginCommandContextCompat) => {
393
480
  try {
394
481
  api.logger.info(
395
482
  `[privateclaw] /privateclaw invoked via ${ctx.channel}${ctx.senderId ? ` by ${ctx.senderId}` : ""}`,
396
483
  );
397
- const bundle = await runtime.createInviteBundle();
484
+ const bundle = await runtime.createInviteBundle(
485
+ parsePrivateClawCommandArgs(ctx.args),
486
+ );
398
487
  api.logger.info(
399
488
  `[privateclaw] invite created for session ${bundle.invite.sessionId} on ${ctx.channel}`,
400
489
  );
@@ -408,12 +497,45 @@ function createPluginDefinition(
408
497
  `[privateclaw] Failed to create invite bundle: ${formatCommandError(error)}`,
409
498
  );
410
499
  return {
411
- text: `Failed to create a PrivateClaw session: ${formatCommandError(error)}`,
500
+ text: buildPrivateClawCommandErrorMessage(formatCommandError(error)),
412
501
  isError: true,
413
502
  };
414
503
  }
415
504
  },
416
505
  });
506
+
507
+ api.registerCli?.(
508
+ ({ program }) => {
509
+ const privateclaw = program
510
+ .command("privateclaw")
511
+ .description(PRIVATECLAW_CLI_ROOT_DESCRIPTION);
512
+
513
+ privateclaw
514
+ .command("pair")
515
+ .description(PRIVATECLAW_CLI_PAIR_DESCRIPTION)
516
+ .option("--ttl-ms <ms>", PRIVATECLAW_CLI_TTL_OPTION_DESCRIPTION)
517
+ .option("--label <label>", PRIVATECLAW_CLI_LABEL_OPTION_DESCRIPTION)
518
+ .option("--group", PRIVATECLAW_CLI_GROUP_OPTION_DESCRIPTION)
519
+ .option("--print-only", PRIVATECLAW_CLI_PRINT_ONLY_OPTION_DESCRIPTION)
520
+ .action(async (rawOptions: unknown) => {
521
+ const options = normalizePairCliOptions(rawOptions);
522
+ const ttlMs = parsePositiveIntegerFlag(options.ttlMs, "--ttl-ms");
523
+ const label = readString(options.label);
524
+ await runtime.runPairSession({
525
+ ...(typeof ttlMs === "number" ? { ttlMs } : {}),
526
+ ...(label ? { label } : {}),
527
+ ...(options.group ? { groupMode: true } : {}),
528
+ ...(typeof options.printOnly === "boolean"
529
+ ? { printOnly: options.printOnly }
530
+ : {}),
531
+ writeLine: (line) => {
532
+ console.log(line);
533
+ },
534
+ });
535
+ });
536
+ },
537
+ { commands: ["privateclaw"] },
538
+ );
417
539
  },
418
540
  };
419
541
  }
@@ -0,0 +1,100 @@
1
+ import type { PrivateClawProvider } from "./provider.js";
2
+ import {
3
+ buildPrivateClawShutdownMessage,
4
+ formatBilingualInline,
5
+ PRIVATECLAW_INVITE_URI_LABEL,
6
+ PRIVATECLAW_WAITING_FOR_APP_MESSAGE,
7
+ } from "./text.js";
8
+ import type { PrivateClawInviteBundle } from "./types.js";
9
+
10
+ export interface PairSessionOptions {
11
+ provider: PrivateClawProvider;
12
+ ttlMs?: number;
13
+ label?: string;
14
+ groupMode?: boolean;
15
+ printOnly?: boolean;
16
+ writeLine?: (line: string) => void;
17
+ }
18
+
19
+ export function parsePositiveIntegerFlag(
20
+ value: string | undefined,
21
+ label: string,
22
+ ): number | undefined {
23
+ if (!value || value.trim() === "") {
24
+ return undefined;
25
+ }
26
+
27
+ const parsed = Number.parseInt(value, 10);
28
+ if (!Number.isInteger(parsed) || parsed <= 0) {
29
+ throw new Error(
30
+ formatBilingualInline(
31
+ `${label} 必须是正整数。`,
32
+ `${label} must be a positive integer.`,
33
+ ),
34
+ );
35
+ }
36
+
37
+ return parsed;
38
+ }
39
+
40
+ async function waitForShutdownSignal(): Promise<NodeJS.Signals> {
41
+ return new Promise((resolve) => {
42
+ const handleSigint = () => {
43
+ cleanup();
44
+ resolve("SIGINT");
45
+ };
46
+ const handleSigterm = () => {
47
+ cleanup();
48
+ resolve("SIGTERM");
49
+ };
50
+ const cleanup = () => {
51
+ process.off("SIGINT", handleSigint);
52
+ process.off("SIGTERM", handleSigterm);
53
+ };
54
+
55
+ process.once("SIGINT", handleSigint);
56
+ process.once("SIGTERM", handleSigterm);
57
+ });
58
+ }
59
+
60
+ export async function runPairSession({
61
+ provider,
62
+ ttlMs,
63
+ label,
64
+ groupMode = false,
65
+ printOnly = false,
66
+ writeLine = (line) => {
67
+ console.log(line);
68
+ },
69
+ }: PairSessionOptions): Promise<PrivateClawInviteBundle> {
70
+ try {
71
+ const bundle = await provider.createInviteBundle({
72
+ ...(typeof ttlMs === "number" ? { ttlMs } : {}),
73
+ ...(label ? { label: label.trim() } : {}),
74
+ ...(groupMode ? { groupMode: true } : {}),
75
+ });
76
+
77
+ writeLine(bundle.announcementText);
78
+ writeLine(`${PRIVATECLAW_INVITE_URI_LABEL}: ${bundle.inviteUri}`);
79
+ writeLine(bundle.qrTerminal);
80
+
81
+ if (printOnly) {
82
+ await provider.dispose();
83
+ return bundle;
84
+ }
85
+
86
+ writeLine(PRIVATECLAW_WAITING_FOR_APP_MESSAGE);
87
+ process.stdin.resume();
88
+ try {
89
+ const signal = await waitForShutdownSignal();
90
+ writeLine(buildPrivateClawShutdownMessage(signal));
91
+ await provider.dispose();
92
+ return bundle;
93
+ } finally {
94
+ process.stdin.pause();
95
+ }
96
+ } catch (error) {
97
+ await provider.dispose();
98
+ throw error;
99
+ }
100
+ }