@privateclaw/privateclaw 0.1.13 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,15 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
3
- import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
3
+ import { access, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
4
4
  import { type AddressInfo } from "node:net";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
+ import { resolvePrivateClawMediaDir } from "./invite-qr-files.js";
7
8
  import { formatBilingualInline } from "./text.js";
8
- import type { PrivateClawManagedSession } from "./types.js";
9
+ import type {
10
+ PrivateClawInviteBundle,
11
+ PrivateClawManagedSession,
12
+ } from "./types.js";
9
13
 
10
14
  export type PrivateClawControlHostKind =
11
15
  | "plugin-service"
@@ -35,6 +39,24 @@ export interface PrivateClawDiscoveredSessionListing {
35
39
  sessions: PrivateClawManagedSession[];
36
40
  }
37
41
 
42
+ export interface PrivateClawManagedSessionQrBundleResult {
43
+ host: PrivateClawDiscoveredSessionHost;
44
+ session: PrivateClawManagedSession;
45
+ bundle: PrivateClawInviteBundle;
46
+ notifyParticipantsSupported: true;
47
+ }
48
+
49
+ export interface PrivateClawManagedSessionQrLegacyResult {
50
+ host: PrivateClawDiscoveredSessionHost;
51
+ session: PrivateClawManagedSession;
52
+ legacyPngPath: string;
53
+ notifyParticipantsSupported: false;
54
+ }
55
+
56
+ export type PrivateClawManagedSessionQrLookupResult =
57
+ | PrivateClawManagedSessionQrBundleResult
58
+ | PrivateClawManagedSessionQrLegacyResult;
59
+
38
60
  interface PrivateClawKickResult {
39
61
  sessionId: string;
40
62
  participant: {
@@ -43,8 +65,25 @@ interface PrivateClawKickResult {
43
65
  };
44
66
  }
45
67
 
68
+ interface PrivateClawSessionCloseResult {
69
+ sessionId: string;
70
+ }
71
+
72
+ interface PrivateClawSessionQrResult {
73
+ sessionId: string;
74
+ bundle: PrivateClawInviteBundle;
75
+ }
76
+
46
77
  interface PrivateClawSessionControlProvider {
47
78
  listManagedSessions(): PrivateClawManagedSession[];
79
+ getSessionQrBundle(
80
+ sessionId: string,
81
+ params?: { notifyParticipants?: boolean },
82
+ ): Promise<PrivateClawInviteBundle>;
83
+ closeManagedSession(
84
+ sessionId: string,
85
+ reason?: string,
86
+ ): Promise<PrivateClawManagedSession>;
48
87
  kickGroupParticipant(
49
88
  sessionId: string,
50
89
  appId: string,
@@ -179,14 +218,21 @@ async function requestDescriptorJson<T>(
179
218
  );
180
219
 
181
220
  if (!response.ok) {
182
- throw new Error(
183
- `Control request failed (${response.status} ${response.statusText})`,
184
- );
221
+ throw new PrivateClawControlRequestError(response.status, response.statusText);
185
222
  }
186
223
 
187
224
  return (await response.json()) as T;
188
225
  }
189
226
 
227
+ class PrivateClawControlRequestError extends Error {
228
+ constructor(
229
+ readonly status: number,
230
+ readonly statusText: string,
231
+ ) {
232
+ super(`Control request failed (${status} ${statusText})`);
233
+ }
234
+ }
235
+
190
236
  function formatHostKind(kind: PrivateClawControlHostKind): string {
191
237
  switch (kind) {
192
238
  case "plugin-service":
@@ -303,6 +349,28 @@ export class PrivateClawSessionControlServer {
303
349
  });
304
350
  return;
305
351
  }
352
+ if (
353
+ request.method === "POST" &&
354
+ url.pathname.startsWith("/sessions/") &&
355
+ url.pathname.endsWith("/qr")
356
+ ) {
357
+ const sessionId = decodeURIComponent(
358
+ url.pathname.slice("/sessions/".length, -"/qr".length),
359
+ );
360
+ const body = (await readJsonBody(request)) as Record<string, unknown>;
361
+ const bundle = await this.options.provider.getSessionQrBundle(
362
+ sessionId,
363
+ {
364
+ notifyParticipants:
365
+ body.notify === true || body.notifyParticipants === true,
366
+ },
367
+ );
368
+ writeJson(response, 200, {
369
+ sessionId,
370
+ bundle,
371
+ } satisfies PrivateClawSessionQrResult);
372
+ return;
373
+ }
306
374
  if (
307
375
  request.method === "POST" &&
308
376
  url.pathname.startsWith("/sessions/") &&
@@ -328,6 +396,25 @@ export class PrivateClawSessionControlServer {
328
396
  } satisfies PrivateClawKickResult);
329
397
  return;
330
398
  }
399
+ if (
400
+ request.method === "POST" &&
401
+ url.pathname.startsWith("/sessions/") &&
402
+ url.pathname.endsWith("/close")
403
+ ) {
404
+ const sessionId = decodeURIComponent(
405
+ url.pathname.slice("/sessions/".length, -"/close".length),
406
+ );
407
+ const body = (await readJsonBody(request)) as Record<string, unknown>;
408
+ const reason =
409
+ typeof body.reason === "string" && body.reason.trim() !== ""
410
+ ? body.reason
411
+ : undefined;
412
+ await this.options.provider.closeManagedSession(sessionId, reason);
413
+ writeJson(response, 200, {
414
+ sessionId,
415
+ } satisfies PrivateClawSessionCloseResult);
416
+ return;
417
+ }
331
418
 
332
419
  writeJson(response, 404, { error: "not_found" });
333
420
  } catch (error) {
@@ -419,20 +506,18 @@ export async function listManagedSessionsFromStateDir(
419
506
  );
420
507
  }
421
508
 
422
- export async function kickManagedParticipantFromStateDir(params: {
509
+ async function resolveManagedSessionDescriptor(params: {
423
510
  stateDir: string;
424
511
  sessionId: string;
425
- appId: string;
426
- reason?: string;
427
512
  }): Promise<{
428
- host: PrivateClawDiscoveredSessionHost;
513
+ listing: PrivateClawDiscoveredSessionListing;
429
514
  session: PrivateClawManagedSession;
430
- participant: {
431
- appId: string;
432
- displayName: string;
433
- };
515
+ descriptor: PrivateClawSessionControlDescriptor;
516
+ descriptorPath: string;
434
517
  }> {
435
518
  const listings = await listManagedSessionsFromStateDir(params.stateDir);
519
+ const descriptors = await loadDescriptors(params.stateDir);
520
+
436
521
  for (const listing of listings) {
437
522
  const session = listing.sessions.find(
438
523
  (candidate) => candidate.sessionId === params.sessionId,
@@ -441,7 +526,6 @@ export async function kickManagedParticipantFromStateDir(params: {
441
526
  continue;
442
527
  }
443
528
 
444
- const descriptors = await loadDescriptors(params.stateDir);
445
529
  const descriptor = descriptors.find(
446
530
  (candidate) => candidate.descriptor.controlId === listing.host.controlId,
447
531
  );
@@ -449,25 +533,297 @@ export async function kickManagedParticipantFromStateDir(params: {
449
533
  break;
450
534
  }
451
535
 
452
- const result = await requestDescriptorJson<PrivateClawKickResult>(
453
- descriptor.descriptor,
454
- `/sessions/${encodeURIComponent(params.sessionId)}/kick`,
536
+ return {
537
+ listing,
538
+ session,
539
+ descriptor: descriptor.descriptor,
540
+ descriptorPath: descriptor.descriptorPath,
541
+ };
542
+ }
543
+
544
+ throw new Error(
545
+ `Could not find session ${params.sessionId} in ${resolvePrivateClawStateDir(params.stateDir)}.`,
546
+ );
547
+ }
548
+
549
+ async function resolveLegacySessionQrPngPath(params: {
550
+ stateDir: string;
551
+ sessionId: string;
552
+ }): Promise<string | undefined> {
553
+ const pngPath = path.join(
554
+ resolvePrivateClawMediaDir(resolvePrivateClawStateDir(params.stateDir)),
555
+ `privateclaw-${params.sessionId}.png`,
556
+ );
557
+ try {
558
+ await access(pngPath);
559
+ return pngPath;
560
+ } catch {
561
+ return undefined;
562
+ }
563
+ }
564
+
565
+ export function isManagedSessionQrLegacyResult(
566
+ result: PrivateClawManagedSessionQrLookupResult,
567
+ ): result is PrivateClawManagedSessionQrLegacyResult {
568
+ return "legacyPngPath" in result;
569
+ }
570
+
571
+ export function buildManagedSessionQrLegacyLines(params: {
572
+ result: PrivateClawManagedSessionQrLegacyResult;
573
+ notifyParticipants?: boolean;
574
+ }): string[] {
575
+ const lines = [
576
+ formatBilingualInline(
577
+ `会话 ${params.result.session.sessionId} 由较旧的 PrivateClaw host 管理,当前 control API 还不能重新导出这张二维码。`,
578
+ `Session ${params.result.session.sessionId} is managed by an older PrivateClaw host, so its current control API cannot re-export this QR code yet.`,
579
+ ),
580
+ formatBilingualInline(
581
+ `已保留的二维码 PNG 路径: ${params.result.legacyPngPath}`,
582
+ `Saved QR PNG path: ${params.result.legacyPngPath}`,
583
+ ),
584
+ ];
585
+ if (params.notifyParticipants) {
586
+ lines.push(
587
+ formatBilingualInline(
588
+ "这次没有向参与者推送二维码。请让已连接参与者在会话里运行 /session-qr,或使用当前版本重新建立会话。",
589
+ "Participants were not notified. Ask a connected participant to run /session-qr inside the session, or recreate the session with the current provider build.",
590
+ ),
591
+ );
592
+ } else {
593
+ lines.push(
594
+ formatBilingualInline(
595
+ "如需直接打开这张已保存的二维码图片,可重试并追加 --open。",
596
+ "Re-run with --open to open the saved QR image directly.",
597
+ ),
598
+ );
599
+ }
600
+ return lines;
601
+ }
602
+
603
+ async function waitForPidExit(params: {
604
+ pid: number;
605
+ timeoutMs?: number;
606
+ }): Promise<void> {
607
+ const timeoutMs = params.timeoutMs ?? 5_000;
608
+ const startedAt = Date.now();
609
+ for (;;) {
610
+ try {
611
+ process.kill(params.pid, 0);
612
+ } catch (error) {
613
+ const code = (error as NodeJS.ErrnoException).code;
614
+ if (code === "ESRCH") {
615
+ return;
616
+ }
617
+ throw error;
618
+ }
619
+ if (Date.now() - startedAt >= timeoutMs) {
620
+ throw new Error(
621
+ `Timed out waiting for process ${params.pid} to exit after terminating the legacy PrivateClaw host.`,
622
+ );
623
+ }
624
+ await new Promise((resolve) => setTimeout(resolve, 150));
625
+ }
626
+ }
627
+
628
+ export async function kickManagedParticipantFromStateDir(params: {
629
+ stateDir: string;
630
+ sessionId: string;
631
+ appId: string;
632
+ reason?: string;
633
+ }): Promise<{
634
+ host: PrivateClawDiscoveredSessionHost;
635
+ session: PrivateClawManagedSession;
636
+ participant: {
637
+ appId: string;
638
+ displayName: string;
639
+ };
640
+ }> {
641
+ const resolved = await resolveManagedSessionDescriptor({
642
+ stateDir: params.stateDir,
643
+ sessionId: params.sessionId,
644
+ });
645
+ const result = await requestDescriptorJson<PrivateClawKickResult>(
646
+ resolved.descriptor,
647
+ `/sessions/${encodeURIComponent(params.sessionId)}/kick`,
648
+ {
649
+ method: "POST",
650
+ body: {
651
+ appId: params.appId,
652
+ ...(params.reason ? { reason: params.reason } : {}),
653
+ },
654
+ },
655
+ );
656
+ return {
657
+ host: resolved.listing.host,
658
+ session: resolved.session,
659
+ participant: result.participant,
660
+ };
661
+ }
662
+
663
+ export async function closeManagedSessionFromStateDir(params: {
664
+ stateDir: string;
665
+ sessionId: string;
666
+ reason?: string;
667
+ }): Promise<{
668
+ host: PrivateClawDiscoveredSessionHost;
669
+ session: PrivateClawManagedSession;
670
+ terminatedHost: boolean;
671
+ }> {
672
+ const resolved = await resolveManagedSessionDescriptor({
673
+ stateDir: params.stateDir,
674
+ sessionId: params.sessionId,
675
+ });
676
+ try {
677
+ await requestDescriptorJson<PrivateClawSessionCloseResult>(
678
+ resolved.descriptor,
679
+ `/sessions/${encodeURIComponent(params.sessionId)}/close`,
455
680
  {
456
681
  method: "POST",
457
682
  body: {
458
- appId: params.appId,
459
683
  ...(params.reason ? { reason: params.reason } : {}),
460
684
  },
461
685
  },
462
686
  );
463
687
  return {
464
- host: listing.host,
465
- session,
466
- participant: result.participant,
688
+ host: resolved.listing.host,
689
+ session: resolved.session,
690
+ terminatedHost: false,
467
691
  };
692
+ } catch (error) {
693
+ if (
694
+ error instanceof PrivateClawControlRequestError &&
695
+ error.status === 404 &&
696
+ resolved.listing.host.kind !== "plugin-service" &&
697
+ resolved.listing.sessions.length === 1
698
+ ) {
699
+ process.kill(resolved.listing.host.pid, "SIGTERM");
700
+ await waitForPidExit({
701
+ pid: resolved.listing.host.pid,
702
+ });
703
+ await rm(resolved.descriptorPath, { force: true });
704
+ return {
705
+ host: resolved.listing.host,
706
+ session: resolved.session,
707
+ terminatedHost: true,
708
+ };
709
+ }
710
+ throw error;
468
711
  }
712
+ }
469
713
 
470
- throw new Error(
471
- `Could not find session ${params.sessionId} in ${resolvePrivateClawStateDir(params.stateDir)}.`,
472
- );
714
+ export interface PrivateClawBulkClosedManagedSession {
715
+ host: PrivateClawDiscoveredSessionHost;
716
+ session: PrivateClawManagedSession;
717
+ terminatedHost: boolean;
718
+ }
719
+
720
+ export interface PrivateClawBulkCloseManagedSessionFailure {
721
+ host: PrivateClawDiscoveredSessionHost;
722
+ session: PrivateClawManagedSession;
723
+ error: string;
724
+ }
725
+
726
+ export async function closeManagedSessionsFromStateDir(params: {
727
+ stateDir: string;
728
+ hostKinds: PrivateClawControlHostKind[];
729
+ reason?: string;
730
+ }): Promise<{
731
+ closed: PrivateClawBulkClosedManagedSession[];
732
+ failed: PrivateClawBulkCloseManagedSessionFailure[];
733
+ }> {
734
+ const targetedHostKinds = new Set(params.hostKinds);
735
+ const skippedSessionIds = new Set<string>();
736
+ const closed: PrivateClawBulkClosedManagedSession[] = [];
737
+ const failed: PrivateClawBulkCloseManagedSessionFailure[] = [];
738
+
739
+ for (;;) {
740
+ const listings = await listManagedSessionsFromStateDir(params.stateDir);
741
+ const candidate = listings
742
+ .filter((listing) => targetedHostKinds.has(listing.host.kind))
743
+ .flatMap((listing) =>
744
+ listing.sessions.map((session) => ({
745
+ host: listing.host,
746
+ session,
747
+ })),
748
+ )
749
+ .find((entry) => !skippedSessionIds.has(entry.session.sessionId));
750
+
751
+ if (!candidate) {
752
+ return {
753
+ closed,
754
+ failed,
755
+ };
756
+ }
757
+
758
+ try {
759
+ closed.push(
760
+ await closeManagedSessionFromStateDir({
761
+ stateDir: params.stateDir,
762
+ sessionId: candidate.session.sessionId,
763
+ ...(params.reason ? { reason: params.reason } : {}),
764
+ }),
765
+ );
766
+ } catch (error) {
767
+ failed.push({
768
+ host: candidate.host,
769
+ session: candidate.session,
770
+ error: error instanceof Error ? error.message : String(error),
771
+ });
772
+ skippedSessionIds.add(candidate.session.sessionId);
773
+ }
774
+ }
775
+ }
776
+
777
+ export async function getManagedSessionQrBundleFromStateDir(params: {
778
+ stateDir: string;
779
+ sessionId: string;
780
+ notifyParticipants?: boolean;
781
+ }): Promise<PrivateClawManagedSessionQrLookupResult> {
782
+ const resolved = await resolveManagedSessionDescriptor({
783
+ stateDir: params.stateDir,
784
+ sessionId: params.sessionId,
785
+ });
786
+ try {
787
+ const result = await requestDescriptorJson<PrivateClawSessionQrResult>(
788
+ resolved.descriptor,
789
+ `/sessions/${encodeURIComponent(params.sessionId)}/qr`,
790
+ {
791
+ method: "POST",
792
+ body: {
793
+ ...(params.notifyParticipants ? { notify: true } : {}),
794
+ },
795
+ },
796
+ );
797
+ return {
798
+ host: resolved.listing.host,
799
+ session: resolved.session,
800
+ bundle: result.bundle,
801
+ notifyParticipantsSupported: true,
802
+ };
803
+ } catch (error) {
804
+ if (
805
+ error instanceof PrivateClawControlRequestError &&
806
+ error.status === 404
807
+ ) {
808
+ const legacyPngPath = await resolveLegacySessionQrPngPath({
809
+ stateDir: params.stateDir,
810
+ sessionId: params.sessionId,
811
+ });
812
+ if (legacyPngPath) {
813
+ return {
814
+ host: resolved.listing.host,
815
+ session: resolved.session,
816
+ legacyPngPath,
817
+ notifyParticipantsSupported: false,
818
+ };
819
+ }
820
+ throw new Error(
821
+ formatBilingualInline(
822
+ `会话 ${params.sessionId} 的当前 host 还不支持通过 control API 重新导出二维码。请让已连接参与者在会话内运行 /session-qr,或使用当前版本重新建立会话。`,
823
+ `The current host for session ${params.sessionId} does not support re-exporting QR codes through the control API yet. Ask a connected participant to run /session-qr inside the session, or recreate the session with the current provider build.`,
824
+ ),
825
+ );
826
+ }
827
+ throw error;
828
+ }
473
829
  }
package/src/text.ts CHANGED
@@ -52,6 +52,21 @@ export const PRIVATECLAW_CLI_SESSIONS_DESCRIPTION = formatBilingualInline(
52
52
  "List the active PrivateClaw sessions and their participants.",
53
53
  );
54
54
 
55
+ export const PRIVATECLAW_CLI_SESSIONS_QR_DESCRIPTION = formatBilingualInline(
56
+ "重新打印指定会话的二维码,可选地打开浏览器预览并通知当前参与者。",
57
+ "Print the QR code for a selected session, optionally open a browser preview, and optionally notify the current participants.",
58
+ );
59
+
60
+ export const PRIVATECLAW_CLI_SESSIONS_KILL_DESCRIPTION = formatBilingualInline(
61
+ "终止指定的活动会话;对于旧的后台 daemon,会回退为终止整个 daemon host。",
62
+ "Terminate a selected active session; for older background daemons, this falls back to terminating the whole daemon host.",
63
+ );
64
+
65
+ export const PRIVATECLAW_CLI_SESSIONS_KILLALL_DESCRIPTION = formatBilingualInline(
66
+ "终止全部由后台 daemon 托管的活动会话;不会影响前台 host 或 plugin-service 会话。",
67
+ "Terminate every active session managed by background daemons without affecting foreground hosts or plugin-service sessions.",
68
+ );
69
+
55
70
  export const PRIVATECLAW_CLI_KICK_DESCRIPTION = formatBilingualInline(
56
71
  "从群聊会话中移除指定参与者。",
57
72
  "Remove a participant from a group session.",
@@ -88,6 +103,11 @@ export const PRIVATECLAW_CLI_OPEN_OPTION_DESCRIPTION = formatBilingualInline(
88
103
  "Open a local browser preview after generating the QR code.",
89
104
  );
90
105
 
106
+ export const PRIVATECLAW_CLI_NOTIFY_OPTION_DESCRIPTION = formatBilingualInline(
107
+ "同时把这个会话二维码通知给当前会话中的所有参与者。",
108
+ "Also notify every current participant in this session with the session QR code.",
109
+ );
110
+
91
111
  export const PRIVATECLAW_CLI_FOREGROUND_OPTION_DESCRIPTION = formatBilingualInline(
92
112
  "保持当前命令在前台运行,直到会话结束或按 Ctrl+C;在支持的运行时里也可按 Ctrl+D 转入后台。",
93
113
  "Keep the current command in the foreground until the session ends or you press Ctrl+C; in supported runtimes you can also press Ctrl+D to move it into the background.",
@@ -113,6 +133,16 @@ export const PRIVATECLAW_WAITING_FOR_APP_WITH_BACKGROUND_MESSAGE = formatBilingu
113
133
  "Waiting for the PrivateClaw app to connect. Press Ctrl+C to stop or Ctrl+D to move it into the background.",
114
134
  );
115
135
 
136
+ export function buildPrivateClawBackgroundDaemonReminder(
137
+ commandPrefix: string,
138
+ sessionId: string,
139
+ ): string {
140
+ return formatBilingualInline(
141
+ `会话 ${sessionId} 现在由后台 daemon 托管;即使 OpenClaw 主进程重启,它也可能继续存活。可用 \`${commandPrefix} sessions\` 查看,必要时用 \`${commandPrefix} sessions kill ${sessionId}\` 终止。`,
142
+ `Session ${sessionId} is now owned by a background daemon and may survive OpenClaw main-process restarts. Use \`${commandPrefix} sessions\` to inspect it, and \`${commandPrefix} sessions kill ${sessionId}\` if you want to terminate it.`,
143
+ );
144
+ }
145
+
116
146
  export const PRIVATECLAW_SESSION_ENDED_MESSAGE = formatBilingualInline(
117
147
  "PrivateClaw 会话已结束。",
118
148
  "The PrivateClaw session has ended.",
package/src/types.ts CHANGED
@@ -10,6 +10,7 @@ export interface PrivateClawConversationTurn {
10
10
  role: "user" | "assistant" | "system";
11
11
  text: string;
12
12
  sentAt: string;
13
+ bridgeText?: string;
13
14
  appId?: string;
14
15
  participantLabel?: string;
15
16
  replyTo?: string;
@@ -31,6 +32,12 @@ export interface BridgeResponseEnvelope {
31
32
 
32
33
  export type BridgeResponse = string | BridgeResponseEnvelope;
33
34
 
35
+ export interface PrivateClawAudioTranscriptionRequest {
36
+ sessionId: string;
37
+ requestId: string;
38
+ attachments: ReadonlyArray<PrivateClawAttachment>;
39
+ }
40
+
34
41
  export interface PrivateClawAgentBridge {
35
42
  handleUserMessage(params: {
36
43
  sessionId: string;
@@ -39,6 +46,9 @@ export interface PrivateClawAgentBridge {
39
46
  attachments?: ReadonlyArray<PrivateClawAttachment>;
40
47
  history: ReadonlyArray<PrivateClawConversationTurn>;
41
48
  }): Promise<BridgeResponse>;
49
+ transcribeAudioAttachments?(
50
+ params: PrivateClawAudioTranscriptionRequest,
51
+ ): Promise<string>;
42
52
  }
43
53
 
44
54
  export interface PrivateClawProviderOptions {