@privateclaw/privateclaw 0.1.11 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/provider.ts CHANGED
@@ -33,7 +33,10 @@ import type {
33
33
  BridgeResponse,
34
34
  PrivateClawConversationTurn,
35
35
  PrivateClawInviteBundle,
36
+ PrivateClawProviderHandoffState,
37
+ PrivateClawManagedSession,
36
38
  PrivateClawProviderOptions,
39
+ PrivateClawProviderSessionHandoff,
37
40
  ProviderParticipantState,
38
41
  ProviderSessionState,
39
42
  } from "./types.js";
@@ -162,6 +165,84 @@ function buildGeneratedParticipantLabel(
162
165
  }
163
166
  }
164
167
 
168
+ function cloneConversationTurn(
169
+ turn: PrivateClawConversationTurn,
170
+ ): PrivateClawConversationTurn {
171
+ return {
172
+ ...turn,
173
+ ...(turn.attachments
174
+ ? {
175
+ attachments: turn.attachments.map((attachment) => ({
176
+ ...attachment,
177
+ })),
178
+ }
179
+ : {}),
180
+ };
181
+ }
182
+
183
+ function buildRelayLabel(appWsUrl: string): string | undefined {
184
+ try {
185
+ const url = new URL(appWsUrl);
186
+ if (!url.hostname) {
187
+ return undefined;
188
+ }
189
+ const port = url.port;
190
+ const isDefaultPort =
191
+ port === "" ||
192
+ (url.protocol === "wss:" && port === "443") ||
193
+ (url.protocol === "ws:" && port === "80");
194
+ return isDefaultPort ? url.hostname : `${url.hostname}:${port}`;
195
+ } catch {
196
+ return undefined;
197
+ }
198
+ }
199
+
200
+ function toProviderSessionHandoff(
201
+ session: ProviderSessionState,
202
+ ): PrivateClawProviderSessionHandoff {
203
+ return {
204
+ invite: { ...session.invite },
205
+ ...(session.label ? { label: session.label } : {}),
206
+ history: session.history.map(cloneConversationTurn),
207
+ groupMode: session.groupMode,
208
+ botMuted: session.botMuted,
209
+ participants: [...session.participants.values()].map((participant) => ({
210
+ ...participant,
211
+ })),
212
+ removedParticipantAppIds: [...session.removedParticipantAppIds.values()],
213
+ state: session.state,
214
+ ...(session.pendingRenewal
215
+ ? { pendingRenewal: { ...session.pendingRenewal } }
216
+ : {}),
217
+ ...(session.renewalReminderSentAt
218
+ ? { renewalReminderSentAt: session.renewalReminderSentAt }
219
+ : {}),
220
+ };
221
+ }
222
+
223
+ function fromProviderSessionHandoff(
224
+ snapshot: PrivateClawProviderSessionHandoff,
225
+ ): ProviderSessionState {
226
+ return {
227
+ invite: { ...snapshot.invite },
228
+ ...(snapshot.label ? { label: snapshot.label } : {}),
229
+ history: snapshot.history.map(cloneConversationTurn),
230
+ groupMode: snapshot.groupMode,
231
+ botMuted: snapshot.botMuted,
232
+ participants: new Map(
233
+ snapshot.participants.map((participant) => [participant.appId, { ...participant }]),
234
+ ),
235
+ removedParticipantAppIds: new Set(snapshot.removedParticipantAppIds),
236
+ state: snapshot.state,
237
+ ...(snapshot.pendingRenewal
238
+ ? { pendingRenewal: { ...snapshot.pendingRenewal } }
239
+ : {}),
240
+ ...(snapshot.renewalReminderSentAt
241
+ ? { renewalReminderSentAt: snapshot.renewalReminderSentAt }
242
+ : {}),
243
+ };
244
+ }
245
+
165
246
  function buildRenewalReminderMessage(session: ProviderSessionState): string {
166
247
  const command = "/renew-session";
167
248
  if (session.groupMode) {
@@ -221,6 +302,26 @@ function toParticipantSnapshot(
221
302
  };
222
303
  }
223
304
 
305
+ function toManagedSessionSnapshot(
306
+ session: ProviderSessionState,
307
+ ): PrivateClawManagedSession {
308
+ const participants = [...session.participants.values()]
309
+ .sort((left, right) => left.joinedAt.localeCompare(right.joinedAt))
310
+ .map(toParticipantSnapshot);
311
+ return {
312
+ sessionId: session.invite.sessionId,
313
+ expiresAt: session.invite.expiresAt,
314
+ ...(session.invite.providerLabel
315
+ ? { providerLabel: session.invite.providerLabel }
316
+ : {}),
317
+ ...(session.label ? { label: session.label } : {}),
318
+ groupMode: session.groupMode,
319
+ participantCount: participants.length,
320
+ participants,
321
+ state: session.state,
322
+ };
323
+ }
324
+
224
325
  function buildWelcomeMessage(): string {
225
326
  return formatBilingualText(
226
327
  "PrivateClaw 已连接。从现在起,消息都会通过这个一次性的端到端加密会话进行保护。",
@@ -290,6 +391,15 @@ function buildParticipantLeftMessage(participantLabel: string): string {
290
391
  );
291
392
  }
292
393
 
394
+ function buildParticipantRemovedByOperatorMessage(
395
+ participantLabel: string,
396
+ ): string {
397
+ return formatBilingualInline(
398
+ `${participantLabel} 已被移出群聊。`,
399
+ `${participantLabel} was removed from the group chat.`,
400
+ );
401
+ }
402
+
293
403
  function buildHandshakeIncompleteMessage(): string {
294
404
  return formatBilingualInline(
295
405
  "PrivateClaw 握手尚未完成。请重新扫码或重试连接。",
@@ -379,6 +489,7 @@ export class PrivateClawProvider {
379
489
  constructor(private readonly options: PrivateClawProviderOptions) {
380
490
  this.relayClient = new RelayProviderClient({
381
491
  providerWsUrl: options.providerWsUrl,
492
+ ...(options.providerId ? { providerId: options.providerId } : {}),
382
493
  onFrame: async (sessionId, envelope) => {
383
494
  await this.handleRelayFrame(sessionId, envelope);
384
495
  },
@@ -396,16 +507,21 @@ export class PrivateClawProvider {
396
507
  await this.relayClient.connect();
397
508
  }
398
509
 
399
- async dispose(): Promise<void> {
510
+ async dispose(params?: { closeSessions?: boolean }): Promise<void> {
511
+ const closeSessions = params?.closeSessions !== false;
400
512
  const activeSessionIds = [...this.sessions.keys()];
401
513
  for (const sessionId of activeSessionIds) {
402
- try {
403
- await this.relayClient.closeSession(sessionId, "provider_shutdown");
404
- } catch (error) {
405
- this.options.onLog?.(
406
- `[provider] failed to close session ${sessionId} during shutdown: ${error instanceof Error ? error.message : String(error)}`,
407
- );
408
- } finally {
514
+ if (closeSessions) {
515
+ try {
516
+ await this.relayClient.closeSession(sessionId, "provider_shutdown");
517
+ } catch (error) {
518
+ this.options.onLog?.(
519
+ `[provider] failed to close session ${sessionId} during shutdown: ${error instanceof Error ? error.message : String(error)}`,
520
+ );
521
+ } finally {
522
+ this.deleteSession(sessionId);
523
+ }
524
+ } else {
409
525
  this.deleteSession(sessionId);
410
526
  }
411
527
  }
@@ -416,6 +532,77 @@ export class PrivateClawProvider {
416
532
  return [...this.sessions.values()].map((session) => session.invite);
417
533
  }
418
534
 
535
+ listManagedSessions(): PrivateClawManagedSession[] {
536
+ return [...this.sessions.values()].map(toManagedSessionSnapshot);
537
+ }
538
+
539
+ exportHandoffState(): PrivateClawProviderHandoffState {
540
+ return {
541
+ providerId: this.relayClient.getProviderId(),
542
+ sessions: [...this.sessions.values()].map(toProviderSessionHandoff),
543
+ };
544
+ }
545
+
546
+ importHandoffState(state: PrivateClawProviderHandoffState): void {
547
+ if (state.providerId !== this.relayClient.getProviderId()) {
548
+ throw new Error("Handoff providerId does not match this provider instance.");
549
+ }
550
+ for (const sessionId of [...this.sessions.keys()]) {
551
+ this.deleteSession(sessionId);
552
+ }
553
+ for (const snapshot of state.sessions) {
554
+ const session = fromProviderSessionHandoff(snapshot);
555
+ this.sessions.set(session.invite.sessionId, session);
556
+ this.scheduleRenewalReminder(session.invite.sessionId);
557
+ }
558
+ }
559
+
560
+ suppressReconnectsForHandoff(): void {
561
+ this.relayClient.suppressReconnects();
562
+ }
563
+
564
+ resumeReconnectsAfterHandoffFailure(): void {
565
+ this.relayClient.resumeReconnects();
566
+ }
567
+
568
+ async kickGroupParticipant(
569
+ sessionId: string,
570
+ appId: string,
571
+ reason = "participant_removed",
572
+ ): Promise<PrivateClawParticipant> {
573
+ const session = this.requireSession(sessionId);
574
+ if (!session.groupMode) {
575
+ throw new Error("Participant removal is only available for group sessions.");
576
+ }
577
+
578
+ const normalizedAppId = appId.trim();
579
+ if (normalizedAppId === "") {
580
+ throw new Error("Participant appId is required.");
581
+ }
582
+
583
+ const participant = session.participants.get(normalizedAppId);
584
+ if (!participant) {
585
+ throw new Error(
586
+ `Participant ${normalizedAppId} is not part of session ${sessionId}.`,
587
+ );
588
+ }
589
+
590
+ session.participants.delete(normalizedAppId);
591
+ session.removedParticipantAppIds.add(normalizedAppId);
592
+
593
+ await this.relayClient.closeApp(sessionId, normalizedAppId, reason);
594
+
595
+ if (session.participants.size > 0) {
596
+ await this.sendSystemMessageToGroupParticipants(
597
+ sessionId,
598
+ buildParticipantRemovedByOperatorMessage(participant.displayName),
599
+ );
600
+ await this.sendCapabilities(sessionId);
601
+ }
602
+
603
+ return toParticipantSnapshot(participant);
604
+ }
605
+
419
606
  private buildSessionAppUrl(sessionId: string): string {
420
607
  const url = new URL(this.options.appWsUrl);
421
608
  url.searchParams.set("sessionId", sessionId);
@@ -933,9 +1120,18 @@ export class PrivateClawProvider {
933
1120
 
934
1121
  switch (payload.kind) {
935
1122
  case "client_hello": {
1123
+ const normalizedAppId = payload.appId?.trim() || "legacy-app";
1124
+ if (session.removedParticipantAppIds.has(normalizedAppId)) {
1125
+ await this.relayClient.closeApp(
1126
+ sessionId,
1127
+ normalizedAppId,
1128
+ "participant_removed",
1129
+ );
1130
+ return;
1131
+ }
936
1132
  const participantState = await this.upsertParticipant(sessionId, {
937
1133
  sentAt: payload.sentAt,
938
- ...(payload.appId ? { appId: payload.appId } : {}),
1134
+ ...(payload.appId ? { appId: normalizedAppId } : {}),
939
1135
  ...(payload.deviceLabel
940
1136
  ? { deviceLabel: payload.deviceLabel }
941
1137
  : {}),
@@ -1351,6 +1547,7 @@ export class PrivateClawProvider {
1351
1547
  await this.connect();
1352
1548
 
1353
1549
  const groupMode = params?.groupMode === true;
1550
+ const relayLabel = buildRelayLabel(this.options.appWsUrl);
1354
1551
  const { sessionId, expiresAt } = await this.relayClient.createSession(
1355
1552
  params?.ttlMs ?? this.options.defaultTtlMs,
1356
1553
  params?.label,
@@ -1365,14 +1562,17 @@ export class PrivateClawProvider {
1365
1562
  expiresAt,
1366
1563
  ...(groupMode ? { groupMode: true } : {}),
1367
1564
  ...(this.options.providerLabel ? { providerLabel: this.options.providerLabel } : {}),
1565
+ ...(relayLabel ? { relayLabel } : {}),
1368
1566
  };
1369
1567
 
1370
1568
  this.sessions.set(sessionId, {
1371
1569
  invite,
1570
+ ...(params?.label ? { label: params.label } : {}),
1372
1571
  history: [],
1373
1572
  groupMode,
1374
1573
  botMuted: false,
1375
1574
  participants: new Map<string, ProviderParticipantState>(),
1575
+ removedParticipantAppIds: new Set<string>(),
1376
1576
  state: "awaiting_hello",
1377
1577
  });
1378
1578
  this.scheduleRenewalReminder(sessionId);
@@ -13,6 +13,7 @@ const MAX_RECONNECT_DELAY_MS = 30_000;
13
13
 
14
14
  interface RelayProviderClientOptions {
15
15
  providerWsUrl: string;
16
+ providerId?: string;
16
17
  onFrame?: (sessionId: string, envelope: EncryptedEnvelope) => Promise<void> | void;
17
18
  onSessionClosed?: (sessionId: string, reason: string) => Promise<void> | void;
18
19
  onError?: (message: string) => void;
@@ -37,14 +38,17 @@ export class RelayProviderClient {
37
38
  private readyPromise: Promise<void> | undefined;
38
39
  private readonly pendingSessionCreations = new Map<string, PendingSessionCreation>();
39
40
  private readonly pendingSessionRenewals = new Map<string, PendingSessionRenewal>();
40
- private readonly providerId = randomUUID();
41
+ private readonly providerId: string;
41
42
  private reconnectTimer: NodeJS.Timeout | undefined;
42
43
  private heartbeatTimer: NodeJS.Timeout | undefined;
43
44
  private reconnectDelayMs = INITIAL_RECONNECT_DELAY_MS;
44
45
  private lastPongAt = 0;
45
46
  private disposed = false;
47
+ private reconnectsSuppressed = false;
46
48
 
47
- constructor(private readonly options: RelayProviderClientOptions) {}
49
+ constructor(private readonly options: RelayProviderClientOptions) {
50
+ this.providerId = options.providerId?.trim() || randomUUID();
51
+ }
48
52
 
49
53
  private buildProviderUrl(): string {
50
54
  const url = new URL(this.options.providerWsUrl);
@@ -123,7 +127,7 @@ export class RelayProviderClient {
123
127
  if (!ready) {
124
128
  rejectIfUnsettled(new Error("Relay provider socket closed before ready."));
125
129
  }
126
- if (!this.disposed) {
130
+ if (!this.disposed && !this.reconnectsSuppressed) {
127
131
  this.scheduleReconnect();
128
132
  }
129
133
  });
@@ -158,7 +162,7 @@ export class RelayProviderClient {
158
162
  }
159
163
 
160
164
  private scheduleReconnect(): void {
161
- if (this.reconnectTimer || this.disposed) {
165
+ if (this.reconnectTimer || this.disposed || this.reconnectsSuppressed) {
162
166
  return;
163
167
  }
164
168
  const delayMs = this.reconnectDelayMs;
@@ -321,6 +325,39 @@ export class RelayProviderClient {
321
325
  });
322
326
  }
323
327
 
328
+ async closeApp(
329
+ sessionId: string,
330
+ appId: string,
331
+ reason?: string,
332
+ ): Promise<void> {
333
+ await this.connect();
334
+ this.send({
335
+ type: "provider:close_app",
336
+ sessionId,
337
+ appId,
338
+ ...(reason ? { reason } : {}),
339
+ });
340
+ }
341
+
342
+ getProviderId(): string {
343
+ return this.providerId;
344
+ }
345
+
346
+ suppressReconnects(): void {
347
+ this.reconnectsSuppressed = true;
348
+ if (this.reconnectTimer) {
349
+ clearTimeout(this.reconnectTimer);
350
+ this.reconnectTimer = undefined;
351
+ }
352
+ }
353
+
354
+ resumeReconnects(): void {
355
+ if (this.disposed) {
356
+ return;
357
+ }
358
+ this.reconnectsSuppressed = false;
359
+ }
360
+
324
361
  async dispose(): Promise<void> {
325
362
  this.disposed = true;
326
363
  this.rejectPending(new Error("Relay provider client disposed."));