@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.
- package/README.md +88 -6
- package/dist/bridges/openclaw-agent-bridge.d.ts +5 -0
- package/dist/bridges/openclaw-agent-bridge.js +228 -15
- package/dist/bridges/openclaw-agent-bridge.js.map +1 -1
- package/dist/cli.js +11 -19
- package/dist/cli.js.map +1 -1
- package/dist/compat/openclaw.d.ts +18 -1
- package/dist/compat/openclaw.js +3 -1
- package/dist/compat/openclaw.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/openclaw-plugin.js +90 -15
- package/dist/openclaw-plugin.js.map +1 -1
- package/dist/pair-session.d.ts +12 -0
- package/dist/pair-session.js +63 -0
- package/dist/pair-session.js.map +1 -0
- package/dist/provider.d.ts +22 -1
- package/dist/provider.js +613 -60
- package/dist/provider.js.map +1 -1
- package/dist/qr-options.d.ts +5 -0
- package/dist/qr-options.js +6 -0
- package/dist/qr-options.js.map +1 -0
- package/dist/relay-defaults.d.ts +1 -0
- package/dist/relay-defaults.js +2 -0
- package/dist/relay-defaults.js.map +1 -0
- package/dist/relay-provider-client.d.ts +2 -2
- package/dist/relay-provider-client.js +9 -3
- package/dist/relay-provider-client.js.map +1 -1
- package/dist/text.d.ts +22 -0
- package/dist/text.js +32 -0
- package/dist/text.js.map +1 -0
- package/dist/types.d.ts +14 -1
- package/openclaw.plugin.json +3 -2
- package/package.json +1 -1
- package/src/bridges/openclaw-agent-bridge.test.ts +141 -0
- package/src/bridges/openclaw-agent-bridge.ts +302 -16
- package/src/cli.ts +14 -22
- package/src/compat/openclaw.ts +30 -1
- package/src/index.ts +1 -0
- package/src/openclaw-plugin.test.ts +139 -0
- package/src/openclaw-plugin.ts +137 -15
- package/src/pair-session.ts +100 -0
- package/src/provider.test.ts +704 -1
- package/src/provider.ts +933 -60
- package/src/qr-options.ts +5 -0
- package/src/relay-defaults.ts +1 -0
- package/src/relay-provider-client.ts +13 -2
- package/src/text.ts +108 -0
- package/src/types.ts +15 -0
package/src/provider.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
1
2
|
import {
|
|
2
3
|
decodeInviteString,
|
|
3
4
|
decryptPayload,
|
|
@@ -6,20 +7,58 @@ import {
|
|
|
6
7
|
generateSessionKey,
|
|
7
8
|
type PrivateClawAttachment,
|
|
8
9
|
type PrivateClawInvite,
|
|
10
|
+
type PrivateClawParticipant,
|
|
9
11
|
type PrivateClawSlashCommand,
|
|
10
12
|
} from "@privateclaw/protocol";
|
|
11
13
|
import QRCode from "qrcode";
|
|
14
|
+
import {
|
|
15
|
+
PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL,
|
|
16
|
+
PRIVATECLAW_QR_SVG_MARGIN,
|
|
17
|
+
PRIVATECLAW_QR_TERMINAL_MARGIN,
|
|
18
|
+
} from "./qr-options.js";
|
|
12
19
|
import { RelayProviderClient } from "./relay-provider-client.js";
|
|
20
|
+
import {
|
|
21
|
+
buildInviteAnnouncementText,
|
|
22
|
+
formatBilingualInline,
|
|
23
|
+
formatBilingualText,
|
|
24
|
+
PRIVATECLAW_MUTE_BOT_DESCRIPTION,
|
|
25
|
+
PRIVATECLAW_RENEW_SESSION_DESCRIPTION,
|
|
26
|
+
PRIVATECLAW_UNMUTE_BOT_DESCRIPTION,
|
|
27
|
+
} from "./text.js";
|
|
13
28
|
import type {
|
|
14
29
|
BridgeMessage,
|
|
15
30
|
BridgeResponse,
|
|
16
31
|
PrivateClawConversationTurn,
|
|
17
32
|
PrivateClawInviteBundle,
|
|
18
33
|
PrivateClawProviderOptions,
|
|
34
|
+
ProviderParticipantState,
|
|
19
35
|
ProviderSessionState,
|
|
20
36
|
} from "./types.js";
|
|
21
37
|
|
|
22
|
-
const
|
|
38
|
+
export const DEFAULT_SESSION_TTL_MS = 8 * 60 * 60 * 1000;
|
|
39
|
+
const RENEW_SESSION_TTL_MS = DEFAULT_SESSION_TTL_MS;
|
|
40
|
+
const SESSION_RENEWAL_REMINDER_WINDOW_MS = 30 * 60 * 1000;
|
|
41
|
+
const PARTICIPANT_LABEL_MAX_CHARS = 12;
|
|
42
|
+
const PARTICIPANT_FALLBACK_PREFIXES = [
|
|
43
|
+
"流萤",
|
|
44
|
+
"星河",
|
|
45
|
+
"青柠",
|
|
46
|
+
"雾岚",
|
|
47
|
+
"松果",
|
|
48
|
+
"电光",
|
|
49
|
+
"夜航",
|
|
50
|
+
"珊瑚",
|
|
51
|
+
] as const;
|
|
52
|
+
const PARTICIPANT_FALLBACK_SUFFIXES = [
|
|
53
|
+
"狐",
|
|
54
|
+
"猫",
|
|
55
|
+
"鲸",
|
|
56
|
+
"鹿",
|
|
57
|
+
"狸",
|
|
58
|
+
"鹭",
|
|
59
|
+
"狼",
|
|
60
|
+
"鸮",
|
|
61
|
+
] as const;
|
|
23
62
|
|
|
24
63
|
function normalizeBridgeMessages(
|
|
25
64
|
response: BridgeResponse,
|
|
@@ -39,6 +78,273 @@ function nowIso(): string {
|
|
|
39
78
|
return new Date().toISOString();
|
|
40
79
|
}
|
|
41
80
|
|
|
81
|
+
function buildMessageId(prefix: string): string {
|
|
82
|
+
return `${prefix}-${randomUUID()}`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function sanitizeParticipantLabel(raw: string | undefined): string | undefined {
|
|
86
|
+
if (!raw) {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const normalized = raw
|
|
91
|
+
.replace(/\s+/g, " ")
|
|
92
|
+
.trim()
|
|
93
|
+
.replace(/^["'`]+|["'`]+$/g, "");
|
|
94
|
+
if (normalized === "") {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const cleaned = normalized
|
|
99
|
+
.replace(/[^\p{Letter}\p{Number}\s_-]/gu, "")
|
|
100
|
+
.trim();
|
|
101
|
+
if (cleaned === "") {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return [...cleaned].slice(0, PARTICIPANT_LABEL_MAX_CHARS).join("");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function deterministicHash(input: string): number {
|
|
109
|
+
let hash = 0;
|
|
110
|
+
for (const char of input) {
|
|
111
|
+
hash = (hash * 31 + char.codePointAt(0)!) >>> 0;
|
|
112
|
+
}
|
|
113
|
+
return hash;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function buildFallbackParticipantLabel(appId: string): string {
|
|
117
|
+
const prefix =
|
|
118
|
+
PARTICIPANT_FALLBACK_PREFIXES[
|
|
119
|
+
deterministicHash(`prefix:${appId}`) % PARTICIPANT_FALLBACK_PREFIXES.length
|
|
120
|
+
];
|
|
121
|
+
const suffix =
|
|
122
|
+
PARTICIPANT_FALLBACK_SUFFIXES[
|
|
123
|
+
deterministicHash(`suffix:${appId}`) % PARTICIPANT_FALLBACK_SUFFIXES.length
|
|
124
|
+
];
|
|
125
|
+
return `${prefix}${suffix}`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function buildDerivedBridgeSessionId(
|
|
129
|
+
sessionId: string,
|
|
130
|
+
scope: string,
|
|
131
|
+
): string {
|
|
132
|
+
const hex = createHash("sha256")
|
|
133
|
+
.update(`${sessionId}:${scope}`)
|
|
134
|
+
.digest("hex")
|
|
135
|
+
.slice(0, 32)
|
|
136
|
+
.split("");
|
|
137
|
+
|
|
138
|
+
hex[12] = "5";
|
|
139
|
+
const variant = Number.parseInt(hex[16]!, 16);
|
|
140
|
+
hex[16] = ((variant & 0x3) | 0x8).toString(16);
|
|
141
|
+
|
|
142
|
+
return `${hex.slice(0, 8).join("")}-${hex.slice(8, 12).join("")}-${hex.slice(12, 16).join("")}-${hex.slice(16, 20).join("")}-${hex.slice(20, 32).join("")}`;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function buildRenewalReminderMessage(session: ProviderSessionState): string {
|
|
146
|
+
const command = "/renew-session";
|
|
147
|
+
if (session.groupMode) {
|
|
148
|
+
return formatBilingualText(
|
|
149
|
+
`这个 PrivateClaw 群聊会话将在 30 分钟内过期(${session.invite.expiresAt})。任意参与者都可以发送 ${command} 将它延长 8 小时。`,
|
|
150
|
+
`This PrivateClaw group session will expire in less than 30 minutes (at ${session.invite.expiresAt}). Any participant can send ${command} to extend it by 8 hours.`,
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
return formatBilingualText(
|
|
154
|
+
`这个 PrivateClaw 会话将在 30 分钟内过期(${session.invite.expiresAt})。发送 ${command} 可将它延长 8 小时。`,
|
|
155
|
+
`This PrivateClaw session will expire in less than 30 minutes (at ${session.invite.expiresAt}). Send ${command} to extend it by 8 hours.`,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function normalizeBridgeText(response: BridgeResponse): string {
|
|
160
|
+
if (typeof response === "string") {
|
|
161
|
+
return response;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return response.messages
|
|
165
|
+
.map((message: BridgeMessage) =>
|
|
166
|
+
typeof message === "string" ? message : message.text,
|
|
167
|
+
)
|
|
168
|
+
.find((message) => message.trim() !== "") ?? "";
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function formatBridgeHistoryTurn(
|
|
172
|
+
turn: PrivateClawConversationTurn,
|
|
173
|
+
): PrivateClawConversationTurn {
|
|
174
|
+
if (turn.role !== "user" || !turn.participantLabel) {
|
|
175
|
+
return turn;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
...turn,
|
|
180
|
+
text: `${turn.participantLabel}: ${turn.text}`,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function toParticipantSnapshot(
|
|
185
|
+
participant: ProviderParticipantState,
|
|
186
|
+
): PrivateClawParticipant {
|
|
187
|
+
return {
|
|
188
|
+
appId: participant.appId,
|
|
189
|
+
displayName: participant.displayName,
|
|
190
|
+
...(participant.deviceLabel ? { deviceLabel: participant.deviceLabel } : {}),
|
|
191
|
+
joinedAt: participant.joinedAt,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function buildParticipantNamingPrompt(deviceLabel?: string): string {
|
|
196
|
+
return [
|
|
197
|
+
"Generate one playful nickname for a PrivateClaw group participant.",
|
|
198
|
+
"Rules:",
|
|
199
|
+
"- return the nickname only",
|
|
200
|
+
"- no quotes, emoji, punctuation, or explanation",
|
|
201
|
+
"- maximum 6 Chinese characters or 12 ASCII characters",
|
|
202
|
+
"- make it short, memorable, and cute",
|
|
203
|
+
...(deviceLabel
|
|
204
|
+
? [`The participant's device label is: ${deviceLabel}`]
|
|
205
|
+
: []),
|
|
206
|
+
].join("\n");
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function buildWelcomeMessage(): string {
|
|
210
|
+
return formatBilingualText(
|
|
211
|
+
"PrivateClaw 已连接。从现在起,消息都会通过这个一次性的端到端加密会话进行保护。",
|
|
212
|
+
"PrivateClaw connected. Messages from now on are protected by this one-time end-to-end encrypted session.",
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function buildCommandDoesNotAcceptAttachmentsMessage(command: string): string {
|
|
217
|
+
return formatBilingualInline(
|
|
218
|
+
`${command} 命令不接受附件。`,
|
|
219
|
+
`The ${command} command does not accept attachments.`,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function buildCommandDoesNotAcceptArgumentsMessage(command: string): string {
|
|
224
|
+
return formatBilingualInline(
|
|
225
|
+
`${command} 命令不接受参数。`,
|
|
226
|
+
`The ${command} command does not accept arguments.`,
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function buildRenewalAlreadyInProgressMessage(): string {
|
|
231
|
+
return formatBilingualInline(
|
|
232
|
+
"会话续期已经在进行中。请等待重新握手完成后再重试。",
|
|
233
|
+
"A session renewal is already in progress. Wait for the reconnect handshake to finish and try again.",
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function buildRenewalPayloadMessage(): string {
|
|
238
|
+
return formatBilingualInline("会话已续期。", "Session renewed.");
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function buildRenewalInitiatedMessage(expiresAt: string): string {
|
|
242
|
+
return formatBilingualInline(
|
|
243
|
+
`PrivateClaw 会话续期已开始,新过期时间为 ${expiresAt}。`,
|
|
244
|
+
`PrivateClaw session renewal initiated until ${expiresAt}.`,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function buildSessionKeyRotationCompletedMessage(
|
|
249
|
+
participantLabel: string,
|
|
250
|
+
): string {
|
|
251
|
+
return formatBilingualInline(
|
|
252
|
+
`${participantLabel} 已完成会话密钥轮换。`,
|
|
253
|
+
`${participantLabel} completed session key rotation.`,
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function buildSingleSessionConnectedMessage(participantLabel: string): string {
|
|
258
|
+
return formatBilingualInline(
|
|
259
|
+
`${participantLabel} 已连接。`,
|
|
260
|
+
`${participantLabel} connected.`,
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function buildParticipantJoinedMessage(participantLabel: string): string {
|
|
265
|
+
return formatBilingualInline(
|
|
266
|
+
`${participantLabel} 加入了群聊。`,
|
|
267
|
+
`${participantLabel} joined the group chat.`,
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function buildParticipantLeftMessage(participantLabel: string): string {
|
|
272
|
+
return formatBilingualInline(
|
|
273
|
+
`${participantLabel} 离开了群聊。`,
|
|
274
|
+
`${participantLabel} left the group chat.`,
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function buildHandshakeIncompleteMessage(): string {
|
|
279
|
+
return formatBilingualInline(
|
|
280
|
+
"PrivateClaw 握手尚未完成。请重新扫码或重试连接。",
|
|
281
|
+
"The PrivateClaw handshake is not complete yet. Scan the QR code again or retry the connection.",
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function buildMissingParticipantIdentityMessage(): string {
|
|
286
|
+
return formatBilingualInline(
|
|
287
|
+
"当前群成员缺少稳定的应用身份。请从 PrivateClaw App 重新加入会话。",
|
|
288
|
+
"This group participant is missing a stable app identity. Rejoin the session from the PrivateClaw app.",
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function buildRenewSessionFailureMessage(details: string): string {
|
|
293
|
+
return formatBilingualInline(
|
|
294
|
+
`PrivateClaw 会话续期失败:${details}`,
|
|
295
|
+
`Failed to renew the PrivateClaw session: ${details}`,
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function buildBridgeErrorMessage(details: string): string {
|
|
300
|
+
return formatBilingualInline(
|
|
301
|
+
`OpenClaw bridge 错误:${details}`,
|
|
302
|
+
`OpenClaw bridge error: ${details}`,
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function buildUnsupportedPayloadMessage(kind: string): string {
|
|
307
|
+
return formatBilingualInline(
|
|
308
|
+
`不支持的 PrivateClaw 负载类型:${kind}`,
|
|
309
|
+
`Unsupported PrivateClaw payload: ${kind}`,
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function buildGroupOnlyCommandMessage(command: string): string {
|
|
314
|
+
return formatBilingualInline(
|
|
315
|
+
`${command} 只能在群聊会话中使用。`,
|
|
316
|
+
`${command} is only available in group sessions.`,
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function buildBotMutedMessage(participantLabel: string): string {
|
|
321
|
+
return formatBilingualInline(
|
|
322
|
+
`${participantLabel} 已暂停机器人参与群聊。`,
|
|
323
|
+
`${participantLabel} paused bot replies for this group chat.`,
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function buildBotUnmutedMessage(participantLabel: string): string {
|
|
328
|
+
return formatBilingualInline(
|
|
329
|
+
`${participantLabel} 已恢复机器人参与群聊。`,
|
|
330
|
+
`${participantLabel} resumed bot replies for this group chat.`,
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function buildBotAlreadyMutedMessage(): string {
|
|
335
|
+
return formatBilingualInline(
|
|
336
|
+
"机器人目前已经处于静默状态。",
|
|
337
|
+
"Bot replies are already muted.",
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function buildBotAlreadyUnmutedMessage(): string {
|
|
342
|
+
return formatBilingualInline(
|
|
343
|
+
"机器人目前已经处于可回复状态。",
|
|
344
|
+
"Bot replies are already enabled.",
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
|
|
42
348
|
function dedupeCommands(
|
|
43
349
|
commands: ReadonlyArray<PrivateClawSlashCommand>,
|
|
44
350
|
): PrivateClawSlashCommand[] {
|
|
@@ -62,7 +368,7 @@ export class PrivateClawProvider {
|
|
|
62
368
|
await this.handleRelayFrame(sessionId, envelope);
|
|
63
369
|
},
|
|
64
370
|
onSessionClosed: async (sessionId, reason) => {
|
|
65
|
-
this.
|
|
371
|
+
this.deleteSession(sessionId);
|
|
66
372
|
this.options.onLog?.(`Session ${sessionId} closed by relay: ${reason}`);
|
|
67
373
|
},
|
|
68
374
|
onError: (message) => {
|
|
@@ -82,11 +388,12 @@ export class PrivateClawProvider {
|
|
|
82
388
|
await this.relayClient.closeSession(sessionId, "provider_shutdown");
|
|
83
389
|
} catch (error) {
|
|
84
390
|
this.options.onLog?.(
|
|
85
|
-
|
|
86
|
-
|
|
391
|
+
`[provider] failed to close session ${sessionId} during shutdown: ${error instanceof Error ? error.message : String(error)}`,
|
|
392
|
+
);
|
|
393
|
+
} finally {
|
|
394
|
+
this.deleteSession(sessionId);
|
|
87
395
|
}
|
|
88
396
|
}
|
|
89
|
-
this.sessions.clear();
|
|
90
397
|
await this.relayClient.dispose();
|
|
91
398
|
}
|
|
92
399
|
|
|
@@ -108,10 +415,170 @@ export class PrivateClawProvider {
|
|
|
108
415
|
return session;
|
|
109
416
|
}
|
|
110
417
|
|
|
418
|
+
private deleteSession(sessionId: string): ProviderSessionState | undefined {
|
|
419
|
+
const session = this.sessions.get(sessionId);
|
|
420
|
+
if (!session) {
|
|
421
|
+
return undefined;
|
|
422
|
+
}
|
|
423
|
+
if (session.renewalReminderTimer) {
|
|
424
|
+
clearTimeout(session.renewalReminderTimer);
|
|
425
|
+
delete session.renewalReminderTimer;
|
|
426
|
+
}
|
|
427
|
+
this.sessions.delete(sessionId);
|
|
428
|
+
return session;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
private buildBridgeHistory(
|
|
432
|
+
session: ProviderSessionState,
|
|
433
|
+
): PrivateClawConversationTurn[] {
|
|
434
|
+
return session.history.map(formatBridgeHistoryTurn);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private listParticipants(
|
|
438
|
+
session: ProviderSessionState,
|
|
439
|
+
): PrivateClawParticipant[] {
|
|
440
|
+
return [...session.participants.values()]
|
|
441
|
+
.sort((left, right) => left.joinedAt.localeCompare(right.joinedAt))
|
|
442
|
+
.map(toParticipantSnapshot);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
private scheduleRenewalReminder(sessionId: string): void {
|
|
446
|
+
const session = this.sessions.get(sessionId);
|
|
447
|
+
if (!session) {
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
if (session.renewalReminderTimer) {
|
|
452
|
+
clearTimeout(session.renewalReminderTimer);
|
|
453
|
+
}
|
|
454
|
+
delete session.renewalReminderTimer;
|
|
455
|
+
delete session.renewalReminderSentAt;
|
|
456
|
+
|
|
457
|
+
const renewAtMs =
|
|
458
|
+
new Date(session.invite.expiresAt).getTime() -
|
|
459
|
+
SESSION_RENEWAL_REMINDER_WINDOW_MS;
|
|
460
|
+
const delayMs = Math.max(0, renewAtMs - Date.now());
|
|
461
|
+
|
|
462
|
+
session.renewalReminderTimer = setTimeout(() => {
|
|
463
|
+
void this.sendRenewalReminder(sessionId).catch((error) => {
|
|
464
|
+
this.options.onLog?.(
|
|
465
|
+
`[provider] failed to send renewal reminder for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
466
|
+
);
|
|
467
|
+
});
|
|
468
|
+
}, delayMs);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
private async sendRenewalReminder(sessionId: string): Promise<void> {
|
|
472
|
+
const session = this.sessions.get(sessionId);
|
|
473
|
+
if (!session) {
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
delete session.renewalReminderTimer;
|
|
478
|
+
|
|
479
|
+
if (session.pendingRenewal || session.renewalReminderSentAt) {
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const remainingMs = new Date(session.invite.expiresAt).getTime() - Date.now();
|
|
484
|
+
if (remainingMs > SESSION_RENEWAL_REMINDER_WINDOW_MS) {
|
|
485
|
+
this.scheduleRenewalReminder(sessionId);
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const sentAt = nowIso();
|
|
490
|
+
session.renewalReminderSentAt = sentAt;
|
|
491
|
+
await this.sendSystemMessage(
|
|
492
|
+
sessionId,
|
|
493
|
+
buildRenewalReminderMessage(session),
|
|
494
|
+
"info",
|
|
495
|
+
undefined,
|
|
496
|
+
{ sentAt },
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
private async generateParticipantLabel(
|
|
501
|
+
sessionId: string,
|
|
502
|
+
appId: string,
|
|
503
|
+
deviceLabel?: string,
|
|
504
|
+
): Promise<string> {
|
|
505
|
+
const session = this.requireSession(sessionId);
|
|
506
|
+
const bridgeSessionId = buildDerivedBridgeSessionId(
|
|
507
|
+
sessionId,
|
|
508
|
+
`participant:${appId}`,
|
|
509
|
+
);
|
|
510
|
+
try {
|
|
511
|
+
const bridgeResponse = await this.options.bridge.handleUserMessage({
|
|
512
|
+
sessionId: bridgeSessionId,
|
|
513
|
+
invite: {
|
|
514
|
+
...session.invite,
|
|
515
|
+
sessionId: bridgeSessionId,
|
|
516
|
+
},
|
|
517
|
+
message: buildParticipantNamingPrompt(deviceLabel),
|
|
518
|
+
history: [],
|
|
519
|
+
});
|
|
520
|
+
const generated = sanitizeParticipantLabel(
|
|
521
|
+
normalizeBridgeText(bridgeResponse),
|
|
522
|
+
);
|
|
523
|
+
if (generated) {
|
|
524
|
+
return generated;
|
|
525
|
+
}
|
|
526
|
+
throw new Error("nickname generation returned an empty label");
|
|
527
|
+
} catch (error) {
|
|
528
|
+
this.options.onLog?.(
|
|
529
|
+
`[provider] participant nickname fallback for ${appId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
530
|
+
);
|
|
531
|
+
return buildFallbackParticipantLabel(appId);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
private async upsertParticipant(
|
|
536
|
+
sessionId: string,
|
|
537
|
+
params: {
|
|
538
|
+
appId?: string;
|
|
539
|
+
deviceLabel?: string;
|
|
540
|
+
displayName?: string;
|
|
541
|
+
sentAt: string;
|
|
542
|
+
},
|
|
543
|
+
): Promise<{ participant: ProviderParticipantState; isNew: boolean }> {
|
|
544
|
+
const session = this.requireSession(sessionId);
|
|
545
|
+
const normalizedAppId = params.appId?.trim() || "legacy-app";
|
|
546
|
+
const existing = session.participants.get(normalizedAppId);
|
|
547
|
+
const requestedDisplayName = sanitizeParticipantLabel(params.displayName);
|
|
548
|
+
|
|
549
|
+
if (existing) {
|
|
550
|
+
const participant: ProviderParticipantState = {
|
|
551
|
+
...existing,
|
|
552
|
+
...(params.deviceLabel ? { deviceLabel: params.deviceLabel } : {}),
|
|
553
|
+
...(requestedDisplayName ? { displayName: requestedDisplayName } : {}),
|
|
554
|
+
lastSeenAt: params.sentAt,
|
|
555
|
+
};
|
|
556
|
+
session.participants.set(normalizedAppId, participant);
|
|
557
|
+
return { participant, isNew: false };
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
const participant: ProviderParticipantState = {
|
|
561
|
+
appId: normalizedAppId,
|
|
562
|
+
displayName:
|
|
563
|
+
requestedDisplayName ??
|
|
564
|
+
(await this.generateParticipantLabel(
|
|
565
|
+
sessionId,
|
|
566
|
+
normalizedAppId,
|
|
567
|
+
params.deviceLabel,
|
|
568
|
+
)),
|
|
569
|
+
...(params.deviceLabel ? { deviceLabel: params.deviceLabel } : {}),
|
|
570
|
+
joinedAt: params.sentAt,
|
|
571
|
+
lastSeenAt: params.sentAt,
|
|
572
|
+
};
|
|
573
|
+
session.participants.set(normalizedAppId, participant);
|
|
574
|
+
return { participant, isNew: true };
|
|
575
|
+
}
|
|
576
|
+
|
|
111
577
|
private async sendPayloadWithSessionKey(
|
|
112
578
|
sessionId: string,
|
|
113
579
|
sessionKey: string,
|
|
114
580
|
payload: Parameters<typeof encryptPayload>[0]["payload"],
|
|
581
|
+
targetAppId?: string,
|
|
115
582
|
): Promise<void> {
|
|
116
583
|
await this.relayClient.sendFrame(
|
|
117
584
|
sessionId,
|
|
@@ -120,18 +587,21 @@ export class PrivateClawProvider {
|
|
|
120
587
|
sessionKey,
|
|
121
588
|
payload,
|
|
122
589
|
}),
|
|
590
|
+
targetAppId,
|
|
123
591
|
);
|
|
124
592
|
}
|
|
125
593
|
|
|
126
594
|
private async sendPayload(
|
|
127
595
|
sessionId: string,
|
|
128
596
|
payload: Parameters<typeof encryptPayload>[0]["payload"],
|
|
597
|
+
targetAppId?: string,
|
|
129
598
|
): Promise<void> {
|
|
130
599
|
const session = this.requireSession(sessionId);
|
|
131
600
|
await this.sendPayloadWithSessionKey(
|
|
132
601
|
sessionId,
|
|
133
602
|
session.invite.sessionKey,
|
|
134
603
|
payload,
|
|
604
|
+
targetAppId,
|
|
135
605
|
);
|
|
136
606
|
}
|
|
137
607
|
|
|
@@ -141,23 +611,33 @@ export class PrivateClawProvider {
|
|
|
141
611
|
text: string;
|
|
142
612
|
replyTo?: string;
|
|
143
613
|
attachments?: PrivateClawAttachment[];
|
|
614
|
+
messageId?: string;
|
|
615
|
+
sentAt?: string;
|
|
616
|
+
targetAppId?: string;
|
|
617
|
+
storeHistory?: boolean;
|
|
144
618
|
},
|
|
145
619
|
): Promise<void> {
|
|
146
|
-
const sentAt = nowIso();
|
|
620
|
+
const sentAt = params.sentAt ?? nowIso();
|
|
621
|
+
const messageId = params.messageId ?? buildMessageId("assistant");
|
|
147
622
|
const session = this.requireSession(sessionId);
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
623
|
+
if (params.storeHistory !== false) {
|
|
624
|
+
session.history.push({
|
|
625
|
+
messageId,
|
|
626
|
+
role: "assistant",
|
|
627
|
+
text: params.text,
|
|
628
|
+
sentAt,
|
|
629
|
+
...(params.replyTo ? { replyTo: params.replyTo } : {}),
|
|
630
|
+
...(params.attachments ? { attachments: params.attachments } : {}),
|
|
631
|
+
});
|
|
632
|
+
}
|
|
154
633
|
await this.sendPayload(sessionId, {
|
|
155
634
|
kind: "assistant_message",
|
|
635
|
+
messageId,
|
|
156
636
|
text: params.text,
|
|
157
637
|
sentAt,
|
|
158
638
|
...(params.replyTo ? { replyTo: params.replyTo } : {}),
|
|
159
639
|
...(params.attachments ? { attachments: params.attachments } : {}),
|
|
160
|
-
});
|
|
640
|
+
}, params.targetAppId);
|
|
161
641
|
}
|
|
162
642
|
|
|
163
643
|
async sendSystemMessage(
|
|
@@ -165,56 +645,243 @@ export class PrivateClawProvider {
|
|
|
165
645
|
message: string,
|
|
166
646
|
severity: "info" | "error" = "info",
|
|
167
647
|
replyTo?: string,
|
|
648
|
+
params?: {
|
|
649
|
+
messageId?: string;
|
|
650
|
+
sentAt?: string;
|
|
651
|
+
targetAppId?: string;
|
|
652
|
+
storeHistory?: boolean;
|
|
653
|
+
},
|
|
168
654
|
): Promise<void> {
|
|
169
|
-
const sentAt = nowIso();
|
|
655
|
+
const sentAt = params?.sentAt ?? nowIso();
|
|
656
|
+
const messageId = params?.messageId ?? buildMessageId("system");
|
|
170
657
|
const session = this.requireSession(sessionId);
|
|
171
|
-
|
|
658
|
+
if (params?.storeHistory !== false) {
|
|
659
|
+
session.history.push({
|
|
660
|
+
messageId,
|
|
661
|
+
role: "system",
|
|
662
|
+
text: message,
|
|
663
|
+
sentAt,
|
|
664
|
+
...(replyTo ? { replyTo } : {}),
|
|
665
|
+
severity,
|
|
666
|
+
});
|
|
667
|
+
}
|
|
172
668
|
await this.sendPayload(sessionId, {
|
|
173
669
|
kind: "system_message",
|
|
670
|
+
messageId,
|
|
174
671
|
message,
|
|
175
672
|
severity,
|
|
176
673
|
sentAt,
|
|
177
674
|
...(replyTo ? { replyTo } : {}),
|
|
675
|
+
}, params?.targetAppId);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
private async sendSystemMessageToGroupParticipants(
|
|
679
|
+
sessionId: string,
|
|
680
|
+
message: string,
|
|
681
|
+
params?: {
|
|
682
|
+
excludeAppId?: string;
|
|
683
|
+
severity?: "info" | "error";
|
|
684
|
+
sentAt?: string;
|
|
685
|
+
},
|
|
686
|
+
): Promise<void> {
|
|
687
|
+
const session = this.requireSession(sessionId);
|
|
688
|
+
const sentAt = params?.sentAt ?? nowIso();
|
|
689
|
+
const severity = params?.severity ?? "info";
|
|
690
|
+
const messageId = buildMessageId("system");
|
|
691
|
+
const targetAppIds = [...session.participants.keys()].filter(
|
|
692
|
+
(appId) => appId !== params?.excludeAppId,
|
|
693
|
+
);
|
|
694
|
+
|
|
695
|
+
if (targetAppIds.length === 0) {
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
session.history.push({
|
|
700
|
+
messageId,
|
|
701
|
+
role: "system",
|
|
702
|
+
text: message,
|
|
703
|
+
sentAt,
|
|
704
|
+
severity,
|
|
178
705
|
});
|
|
706
|
+
|
|
707
|
+
await Promise.all(
|
|
708
|
+
targetAppIds.map((targetAppId) =>
|
|
709
|
+
this.sendPayload(
|
|
710
|
+
sessionId,
|
|
711
|
+
{
|
|
712
|
+
kind: "system_message",
|
|
713
|
+
messageId,
|
|
714
|
+
message,
|
|
715
|
+
severity,
|
|
716
|
+
sentAt,
|
|
717
|
+
},
|
|
718
|
+
targetAppId,
|
|
719
|
+
),
|
|
720
|
+
),
|
|
721
|
+
);
|
|
179
722
|
}
|
|
180
723
|
|
|
181
|
-
private async
|
|
724
|
+
private async sendParticipantMessage(
|
|
725
|
+
sessionId: string,
|
|
726
|
+
params: {
|
|
727
|
+
text: string;
|
|
728
|
+
senderAppId: string;
|
|
729
|
+
senderDisplayName: string;
|
|
730
|
+
clientMessageId: string;
|
|
731
|
+
sentAt?: string;
|
|
732
|
+
attachments?: PrivateClawAttachment[];
|
|
733
|
+
targetAppId?: string;
|
|
734
|
+
storeHistory?: boolean;
|
|
735
|
+
},
|
|
736
|
+
): Promise<void> {
|
|
737
|
+
const sentAt = params.sentAt ?? nowIso();
|
|
738
|
+
const session = this.requireSession(sessionId);
|
|
739
|
+
if (params.storeHistory !== false) {
|
|
740
|
+
session.history.push({
|
|
741
|
+
messageId: params.clientMessageId,
|
|
742
|
+
role: "user",
|
|
743
|
+
text: params.text,
|
|
744
|
+
sentAt,
|
|
745
|
+
appId: params.senderAppId,
|
|
746
|
+
participantLabel: params.senderDisplayName,
|
|
747
|
+
...(params.attachments ? { attachments: params.attachments } : {}),
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
await this.sendPayload(sessionId, {
|
|
751
|
+
kind: "participant_message",
|
|
752
|
+
messageId: params.clientMessageId,
|
|
753
|
+
senderAppId: params.senderAppId,
|
|
754
|
+
senderDisplayName: params.senderDisplayName,
|
|
755
|
+
text: params.text,
|
|
756
|
+
clientMessageId: params.clientMessageId,
|
|
757
|
+
sentAt,
|
|
758
|
+
...(params.attachments ? { attachments: params.attachments } : {}),
|
|
759
|
+
}, params.targetAppId);
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
private async sendWelcomeMessage(
|
|
763
|
+
sessionId: string,
|
|
764
|
+
targetAppId?: string,
|
|
765
|
+
): Promise<void> {
|
|
182
766
|
const sentAt = nowIso();
|
|
183
|
-
const message =
|
|
184
|
-
this.options.welcomeMessage ??
|
|
185
|
-
"PrivateClaw connected. Messages from now on are protected by this one-time end-to-end encrypted session.";
|
|
767
|
+
const message = this.options.welcomeMessage ?? buildWelcomeMessage();
|
|
186
768
|
await this.sendPayload(sessionId, {
|
|
187
769
|
kind: "server_welcome",
|
|
188
770
|
message,
|
|
189
771
|
sentAt,
|
|
190
|
-
});
|
|
772
|
+
}, targetAppId);
|
|
191
773
|
}
|
|
192
774
|
|
|
193
|
-
private async listAvailableCommands(
|
|
775
|
+
private async listAvailableCommands(
|
|
776
|
+
session: ProviderSessionState,
|
|
777
|
+
): Promise<PrivateClawSlashCommand[]> {
|
|
194
778
|
const discovered = (await this.options.commandsProvider?.()) ?? [];
|
|
195
|
-
|
|
779
|
+
const commands: PrivateClawSlashCommand[] = [
|
|
196
780
|
...discovered,
|
|
197
781
|
{
|
|
198
782
|
slash: "/renew-session",
|
|
199
|
-
description:
|
|
200
|
-
"Rotate the current PrivateClaw session key and extend this session by 8 hours.",
|
|
783
|
+
description: PRIVATECLAW_RENEW_SESSION_DESCRIPTION,
|
|
201
784
|
acceptsArgs: false,
|
|
202
785
|
source: "privateclaw",
|
|
203
786
|
},
|
|
204
|
-
]
|
|
787
|
+
];
|
|
788
|
+
|
|
789
|
+
if (session.groupMode) {
|
|
790
|
+
commands.push({
|
|
791
|
+
slash: session.botMuted ? "/unmute-bot" : "/mute-bot",
|
|
792
|
+
description: session.botMuted
|
|
793
|
+
? PRIVATECLAW_UNMUTE_BOT_DESCRIPTION
|
|
794
|
+
: PRIVATECLAW_MUTE_BOT_DESCRIPTION,
|
|
795
|
+
acceptsArgs: false,
|
|
796
|
+
source: "privateclaw",
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
return dedupeCommands(commands);
|
|
205
801
|
}
|
|
206
802
|
|
|
207
|
-
private async sendCapabilities(
|
|
803
|
+
private async sendCapabilities(
|
|
804
|
+
sessionId: string,
|
|
805
|
+
params?: {
|
|
806
|
+
targetAppId?: string;
|
|
807
|
+
includeCurrentIdentity?: boolean;
|
|
808
|
+
},
|
|
809
|
+
): Promise<void> {
|
|
208
810
|
const session = this.requireSession(sessionId);
|
|
811
|
+
const currentParticipant = params?.targetAppId
|
|
812
|
+
? session.participants.get(params.targetAppId)
|
|
813
|
+
: undefined;
|
|
209
814
|
await this.sendPayload(sessionId, {
|
|
210
815
|
kind: "provider_capabilities",
|
|
211
816
|
sentAt: nowIso(),
|
|
212
817
|
expiresAt: session.invite.expiresAt,
|
|
213
|
-
|
|
818
|
+
...(session.groupMode ? { groupMode: true } : {}),
|
|
819
|
+
...(session.groupMode ? { botMuted: session.botMuted } : {}),
|
|
820
|
+
commands: await this.listAvailableCommands(session),
|
|
821
|
+
...(session.groupMode
|
|
822
|
+
? { participants: this.listParticipants(session) }
|
|
823
|
+
: {}),
|
|
214
824
|
...(session.invite.providerLabel
|
|
215
825
|
? { providerLabel: session.invite.providerLabel }
|
|
216
826
|
: {}),
|
|
217
|
-
|
|
827
|
+
...(params?.includeCurrentIdentity && currentParticipant
|
|
828
|
+
? {
|
|
829
|
+
currentAppId: currentParticipant.appId,
|
|
830
|
+
currentDisplayName: currentParticipant.displayName,
|
|
831
|
+
}
|
|
832
|
+
: {}),
|
|
833
|
+
}, params?.targetAppId);
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
private async sendHistorySnapshot(
|
|
837
|
+
sessionId: string,
|
|
838
|
+
targetAppId: string,
|
|
839
|
+
): Promise<void> {
|
|
840
|
+
const session = this.requireSession(sessionId);
|
|
841
|
+
for (const turn of session.history) {
|
|
842
|
+
switch (turn.role) {
|
|
843
|
+
case "assistant":
|
|
844
|
+
await this.sendAssistantMessage(sessionId, {
|
|
845
|
+
messageId: turn.messageId,
|
|
846
|
+
text: turn.text,
|
|
847
|
+
sentAt: turn.sentAt,
|
|
848
|
+
targetAppId,
|
|
849
|
+
storeHistory: false,
|
|
850
|
+
...(turn.replyTo ? { replyTo: turn.replyTo } : {}),
|
|
851
|
+
...(turn.attachments ? { attachments: turn.attachments } : {}),
|
|
852
|
+
});
|
|
853
|
+
break;
|
|
854
|
+
case "system":
|
|
855
|
+
await this.sendSystemMessage(
|
|
856
|
+
sessionId,
|
|
857
|
+
turn.text,
|
|
858
|
+
turn.severity ?? "info",
|
|
859
|
+
turn.replyTo,
|
|
860
|
+
{
|
|
861
|
+
messageId: turn.messageId,
|
|
862
|
+
sentAt: turn.sentAt,
|
|
863
|
+
targetAppId,
|
|
864
|
+
storeHistory: false,
|
|
865
|
+
},
|
|
866
|
+
);
|
|
867
|
+
break;
|
|
868
|
+
case "user":
|
|
869
|
+
if (!session.groupMode || !turn.appId || !turn.participantLabel) {
|
|
870
|
+
break;
|
|
871
|
+
}
|
|
872
|
+
await this.sendParticipantMessage(sessionId, {
|
|
873
|
+
text: turn.text,
|
|
874
|
+
senderAppId: turn.appId,
|
|
875
|
+
senderDisplayName: turn.participantLabel,
|
|
876
|
+
clientMessageId: turn.messageId,
|
|
877
|
+
sentAt: turn.sentAt,
|
|
878
|
+
targetAppId,
|
|
879
|
+
storeHistory: false,
|
|
880
|
+
...(turn.attachments ? { attachments: turn.attachments } : {}),
|
|
881
|
+
});
|
|
882
|
+
break;
|
|
883
|
+
}
|
|
884
|
+
}
|
|
218
885
|
}
|
|
219
886
|
|
|
220
887
|
private async renewSession(sessionId: string, replyTo?: string): Promise<void> {
|
|
@@ -222,7 +889,7 @@ export class PrivateClawProvider {
|
|
|
222
889
|
if (session.pendingRenewal) {
|
|
223
890
|
await this.sendSystemMessage(
|
|
224
891
|
sessionId,
|
|
225
|
-
|
|
892
|
+
buildRenewalAlreadyInProgressMessage(),
|
|
226
893
|
"error",
|
|
227
894
|
replyTo,
|
|
228
895
|
);
|
|
@@ -239,7 +906,7 @@ export class PrivateClawProvider {
|
|
|
239
906
|
|
|
240
907
|
await this.sendPayloadWithSessionKey(sessionId, previousSessionKey, {
|
|
241
908
|
kind: "session_renewed",
|
|
242
|
-
message:
|
|
909
|
+
message: buildRenewalPayloadMessage(),
|
|
243
910
|
newSessionKey: nextSessionKey,
|
|
244
911
|
expiresAt,
|
|
245
912
|
sentAt,
|
|
@@ -252,11 +919,14 @@ export class PrivateClawProvider {
|
|
|
252
919
|
expiresAt,
|
|
253
920
|
};
|
|
254
921
|
session.pendingRenewal = { expiresAt, sentAt };
|
|
922
|
+
this.scheduleRenewalReminder(sessionId);
|
|
255
923
|
session.state = "awaiting_hello";
|
|
256
924
|
session.history.push({
|
|
925
|
+
messageId: buildMessageId("system"),
|
|
257
926
|
role: "system",
|
|
258
|
-
text:
|
|
927
|
+
text: buildRenewalInitiatedMessage(expiresAt),
|
|
259
928
|
sentAt,
|
|
929
|
+
severity: "info",
|
|
260
930
|
});
|
|
261
931
|
}
|
|
262
932
|
|
|
@@ -273,54 +943,108 @@ export class PrivateClawProvider {
|
|
|
273
943
|
|
|
274
944
|
switch (payload.kind) {
|
|
275
945
|
case "client_hello": {
|
|
946
|
+
const participantState = await this.upsertParticipant(sessionId, {
|
|
947
|
+
sentAt: payload.sentAt,
|
|
948
|
+
...(payload.appId ? { appId: payload.appId } : {}),
|
|
949
|
+
...(payload.deviceLabel
|
|
950
|
+
? { deviceLabel: payload.deviceLabel }
|
|
951
|
+
: {}),
|
|
952
|
+
...(payload.displayName
|
|
953
|
+
? { displayName: payload.displayName }
|
|
954
|
+
: {}),
|
|
955
|
+
});
|
|
956
|
+
const participant = participantState.participant;
|
|
276
957
|
const wasAwaitingHello = session.state !== "active";
|
|
277
958
|
const wasRenewing = Boolean(session.pendingRenewal);
|
|
278
959
|
session.state = "active";
|
|
279
960
|
if (wasRenewing) {
|
|
280
961
|
session.history.push({
|
|
962
|
+
messageId: buildMessageId("system"),
|
|
281
963
|
role: "system",
|
|
282
|
-
text:
|
|
964
|
+
text: buildSessionKeyRotationCompletedMessage(
|
|
965
|
+
participant.displayName,
|
|
966
|
+
),
|
|
283
967
|
sentAt: payload.sentAt,
|
|
968
|
+
severity: "info",
|
|
284
969
|
});
|
|
285
970
|
delete session.pendingRenewal;
|
|
286
|
-
} else if (wasAwaitingHello) {
|
|
971
|
+
} else if (!session.groupMode && wasAwaitingHello) {
|
|
287
972
|
session.history.push({
|
|
973
|
+
messageId: buildMessageId("system"),
|
|
288
974
|
role: "system",
|
|
289
|
-
text:
|
|
975
|
+
text: buildSingleSessionConnectedMessage(participant.displayName),
|
|
290
976
|
sentAt: payload.sentAt,
|
|
977
|
+
severity: "info",
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
if (session.groupMode) {
|
|
982
|
+
await this.sendHistorySnapshot(sessionId, participant.appId);
|
|
983
|
+
await this.sendWelcomeMessage(sessionId, participant.appId);
|
|
984
|
+
await this.sendCapabilities(sessionId, {
|
|
985
|
+
targetAppId: participant.appId,
|
|
986
|
+
includeCurrentIdentity: true,
|
|
291
987
|
});
|
|
988
|
+
if (participantState.isNew && session.participants.size > 1) {
|
|
989
|
+
await this.sendSystemMessageToGroupParticipants(
|
|
990
|
+
sessionId,
|
|
991
|
+
buildParticipantJoinedMessage(participant.displayName),
|
|
992
|
+
{
|
|
993
|
+
excludeAppId: participant.appId,
|
|
994
|
+
sentAt: payload.sentAt,
|
|
995
|
+
},
|
|
996
|
+
);
|
|
997
|
+
}
|
|
998
|
+
await this.sendCapabilities(sessionId);
|
|
999
|
+
return;
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
if (wasAwaitingHello && !wasRenewing) {
|
|
292
1003
|
await this.sendWelcomeMessage(sessionId);
|
|
293
1004
|
}
|
|
294
|
-
await this.sendCapabilities(sessionId
|
|
1005
|
+
await this.sendCapabilities(sessionId, {
|
|
1006
|
+
targetAppId: participant.appId,
|
|
1007
|
+
includeCurrentIdentity: true,
|
|
1008
|
+
});
|
|
295
1009
|
return;
|
|
296
1010
|
}
|
|
297
1011
|
case "user_message": {
|
|
298
1012
|
if (session.state !== "active") {
|
|
299
1013
|
await this.sendSystemMessage(
|
|
300
1014
|
sessionId,
|
|
301
|
-
|
|
1015
|
+
buildHandshakeIncompleteMessage(),
|
|
302
1016
|
"error",
|
|
303
1017
|
payload.clientMessageId,
|
|
304
1018
|
);
|
|
305
1019
|
return;
|
|
306
1020
|
}
|
|
307
1021
|
|
|
308
|
-
session.history.push({
|
|
309
|
-
role: "user",
|
|
310
|
-
text: payload.text,
|
|
311
|
-
sentAt: payload.sentAt,
|
|
312
|
-
...(payload.attachments ? { attachments: payload.attachments } : {}),
|
|
313
|
-
});
|
|
314
1022
|
this.options.onLog?.(
|
|
315
1023
|
`[provider] user_message session=${sessionId} textChars=${payload.text.length} attachments=${payload.attachments?.length ?? 0}`,
|
|
316
1024
|
);
|
|
317
1025
|
|
|
1026
|
+
const participant =
|
|
1027
|
+
(payload.appId ? session.participants.get(payload.appId) : undefined) ??
|
|
1028
|
+
(session.participants.size === 1
|
|
1029
|
+
? [...session.participants.values()][0]
|
|
1030
|
+
: undefined);
|
|
1031
|
+
|
|
318
1032
|
const normalizedCommand = payload.text.trim().toLowerCase();
|
|
319
|
-
|
|
1033
|
+
const isRenewCommand =
|
|
1034
|
+
normalizedCommand === "/renew-session" ||
|
|
1035
|
+
normalizedCommand === "/session_renew";
|
|
1036
|
+
const hasRenewCommandArgs =
|
|
1037
|
+
normalizedCommand.startsWith("/renew-session ") ||
|
|
1038
|
+
normalizedCommand.startsWith("/session_renew ");
|
|
1039
|
+
const isMuteBotCommand = normalizedCommand === "/mute-bot";
|
|
1040
|
+
const hasMuteBotArgs = normalizedCommand.startsWith("/mute-bot ");
|
|
1041
|
+
const isUnmuteBotCommand = normalizedCommand === "/unmute-bot";
|
|
1042
|
+
const hasUnmuteBotArgs = normalizedCommand.startsWith("/unmute-bot ");
|
|
1043
|
+
if (isRenewCommand) {
|
|
320
1044
|
if ((payload.attachments?.length ?? 0) > 0) {
|
|
321
1045
|
await this.sendSystemMessage(
|
|
322
1046
|
sessionId,
|
|
323
|
-
"
|
|
1047
|
+
buildCommandDoesNotAcceptAttachmentsMessage("/renew-session"),
|
|
324
1048
|
"error",
|
|
325
1049
|
payload.clientMessageId,
|
|
326
1050
|
);
|
|
@@ -331,30 +1055,134 @@ export class PrivateClawProvider {
|
|
|
331
1055
|
} catch (error) {
|
|
332
1056
|
await this.sendSystemMessage(
|
|
333
1057
|
sessionId,
|
|
334
|
-
|
|
1058
|
+
buildRenewSessionFailureMessage(
|
|
1059
|
+
error instanceof Error ? error.message : String(error),
|
|
1060
|
+
),
|
|
1061
|
+
"error",
|
|
1062
|
+
payload.clientMessageId,
|
|
1063
|
+
);
|
|
1064
|
+
}
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
if (hasRenewCommandArgs) {
|
|
1068
|
+
await this.sendSystemMessage(
|
|
1069
|
+
sessionId,
|
|
1070
|
+
buildCommandDoesNotAcceptArgumentsMessage("/renew-session"),
|
|
1071
|
+
"error",
|
|
1072
|
+
payload.clientMessageId,
|
|
1073
|
+
);
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
if (isMuteBotCommand || isUnmuteBotCommand) {
|
|
1078
|
+
const command = isMuteBotCommand ? "/mute-bot" : "/unmute-bot";
|
|
1079
|
+
if ((payload.attachments?.length ?? 0) > 0) {
|
|
1080
|
+
await this.sendSystemMessage(
|
|
1081
|
+
sessionId,
|
|
1082
|
+
buildCommandDoesNotAcceptAttachmentsMessage(command),
|
|
1083
|
+
"error",
|
|
1084
|
+
payload.clientMessageId,
|
|
1085
|
+
);
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
if (!session.groupMode) {
|
|
1089
|
+
await this.sendSystemMessage(
|
|
1090
|
+
sessionId,
|
|
1091
|
+
buildGroupOnlyCommandMessage(command),
|
|
1092
|
+
"error",
|
|
1093
|
+
payload.clientMessageId,
|
|
1094
|
+
);
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
if (!participant) {
|
|
1098
|
+
await this.sendSystemMessage(
|
|
1099
|
+
sessionId,
|
|
1100
|
+
buildMissingParticipantIdentityMessage(),
|
|
335
1101
|
"error",
|
|
336
1102
|
payload.clientMessageId,
|
|
337
1103
|
);
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
const shouldMute = isMuteBotCommand;
|
|
1108
|
+
if (session.botMuted === shouldMute) {
|
|
1109
|
+
await this.sendSystemMessage(
|
|
1110
|
+
sessionId,
|
|
1111
|
+
shouldMute
|
|
1112
|
+
? buildBotAlreadyMutedMessage()
|
|
1113
|
+
: buildBotAlreadyUnmutedMessage(),
|
|
1114
|
+
"info",
|
|
1115
|
+
payload.clientMessageId,
|
|
1116
|
+
);
|
|
1117
|
+
return;
|
|
338
1118
|
}
|
|
1119
|
+
|
|
1120
|
+
session.botMuted = shouldMute;
|
|
1121
|
+
await this.sendSystemMessageToGroupParticipants(
|
|
1122
|
+
sessionId,
|
|
1123
|
+
shouldMute
|
|
1124
|
+
? buildBotMutedMessage(participant.displayName)
|
|
1125
|
+
: buildBotUnmutedMessage(participant.displayName),
|
|
1126
|
+
{ sentAt: payload.sentAt },
|
|
1127
|
+
);
|
|
1128
|
+
await this.sendCapabilities(sessionId);
|
|
339
1129
|
return;
|
|
340
1130
|
}
|
|
341
|
-
|
|
1131
|
+
|
|
1132
|
+
if (hasMuteBotArgs || hasUnmuteBotArgs) {
|
|
1133
|
+
const command = hasMuteBotArgs ? "/mute-bot" : "/unmute-bot";
|
|
342
1134
|
await this.sendSystemMessage(
|
|
343
1135
|
sessionId,
|
|
344
|
-
|
|
1136
|
+
buildCommandDoesNotAcceptArgumentsMessage(command),
|
|
345
1137
|
"error",
|
|
346
1138
|
payload.clientMessageId,
|
|
347
1139
|
);
|
|
348
1140
|
return;
|
|
349
1141
|
}
|
|
350
1142
|
|
|
1143
|
+
if (session.groupMode) {
|
|
1144
|
+
if (!participant) {
|
|
1145
|
+
await this.sendSystemMessage(
|
|
1146
|
+
sessionId,
|
|
1147
|
+
buildMissingParticipantIdentityMessage(),
|
|
1148
|
+
"error",
|
|
1149
|
+
payload.clientMessageId,
|
|
1150
|
+
);
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
await this.sendParticipantMessage(sessionId, {
|
|
1154
|
+
text: payload.text,
|
|
1155
|
+
senderAppId: participant.appId,
|
|
1156
|
+
senderDisplayName: participant.displayName,
|
|
1157
|
+
clientMessageId: payload.clientMessageId,
|
|
1158
|
+
sentAt: payload.sentAt,
|
|
1159
|
+
...(payload.attachments ? { attachments: payload.attachments } : {}),
|
|
1160
|
+
});
|
|
1161
|
+
} else {
|
|
1162
|
+
session.history.push({
|
|
1163
|
+
messageId: payload.clientMessageId,
|
|
1164
|
+
role: "user",
|
|
1165
|
+
text: payload.text,
|
|
1166
|
+
sentAt: payload.sentAt,
|
|
1167
|
+
...(payload.attachments ? { attachments: payload.attachments } : {}),
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
if (session.groupMode && session.botMuted) {
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
351
1175
|
try {
|
|
1176
|
+
const bridgeMessage =
|
|
1177
|
+
session.groupMode && participant
|
|
1178
|
+
? `${participant.displayName}: ${payload.text}`
|
|
1179
|
+
: payload.text;
|
|
352
1180
|
const bridgeResponse = await this.options.bridge.handleUserMessage({
|
|
353
1181
|
sessionId,
|
|
354
1182
|
invite: session.invite,
|
|
355
|
-
message:
|
|
1183
|
+
message: bridgeMessage,
|
|
356
1184
|
...(payload.attachments ? { attachments: payload.attachments } : {}),
|
|
357
|
-
history:
|
|
1185
|
+
history: this.buildBridgeHistory(session),
|
|
358
1186
|
});
|
|
359
1187
|
|
|
360
1188
|
for (const message of normalizeBridgeMessages(bridgeResponse)) {
|
|
@@ -367,18 +1195,47 @@ export class PrivateClawProvider {
|
|
|
367
1195
|
} catch (error) {
|
|
368
1196
|
await this.sendSystemMessage(
|
|
369
1197
|
sessionId,
|
|
370
|
-
|
|
1198
|
+
buildBridgeErrorMessage(
|
|
1199
|
+
error instanceof Error ? error.message : String(error),
|
|
1200
|
+
),
|
|
371
1201
|
"error",
|
|
372
1202
|
payload.clientMessageId,
|
|
373
1203
|
);
|
|
374
1204
|
}
|
|
375
1205
|
return;
|
|
376
1206
|
}
|
|
377
|
-
case "session_close":
|
|
378
|
-
|
|
379
|
-
|
|
1207
|
+
case "session_close": {
|
|
1208
|
+
if (!session.groupMode) {
|
|
1209
|
+
this.deleteSession(sessionId);
|
|
1210
|
+
await this.relayClient.closeSession(sessionId, payload.reason);
|
|
1211
|
+
return;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
const participantAppId =
|
|
1215
|
+
payload.appId?.trim() ||
|
|
1216
|
+
(session.participants.size === 1
|
|
1217
|
+
? [...session.participants.keys()][0]
|
|
1218
|
+
: undefined);
|
|
1219
|
+
if (!participantAppId) {
|
|
1220
|
+
return;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
const participant = session.participants.get(participantAppId);
|
|
1224
|
+
session.participants.delete(participantAppId);
|
|
1225
|
+
if (participant && session.participants.size > 0) {
|
|
1226
|
+
await this.sendSystemMessageToGroupParticipants(
|
|
1227
|
+
sessionId,
|
|
1228
|
+
buildParticipantLeftMessage(participant.displayName),
|
|
1229
|
+
{ sentAt: payload.sentAt },
|
|
1230
|
+
);
|
|
1231
|
+
}
|
|
1232
|
+
if (session.participants.size > 0) {
|
|
1233
|
+
await this.sendCapabilities(sessionId);
|
|
1234
|
+
}
|
|
380
1235
|
return;
|
|
1236
|
+
}
|
|
381
1237
|
case "assistant_message":
|
|
1238
|
+
case "participant_message":
|
|
382
1239
|
case "server_welcome":
|
|
383
1240
|
case "provider_capabilities":
|
|
384
1241
|
case "session_renewed":
|
|
@@ -387,18 +1244,26 @@ export class PrivateClawProvider {
|
|
|
387
1244
|
default:
|
|
388
1245
|
await this.sendSystemMessage(
|
|
389
1246
|
sessionId,
|
|
390
|
-
|
|
1247
|
+
buildUnsupportedPayloadMessage(
|
|
1248
|
+
(payload as { kind?: string }).kind ?? "unknown",
|
|
1249
|
+
),
|
|
391
1250
|
"error",
|
|
392
1251
|
);
|
|
393
1252
|
}
|
|
394
1253
|
}
|
|
395
1254
|
|
|
396
|
-
async createInviteBundle(params?: {
|
|
1255
|
+
async createInviteBundle(params?: {
|
|
1256
|
+
ttlMs?: number;
|
|
1257
|
+
label?: string;
|
|
1258
|
+
groupMode?: boolean;
|
|
1259
|
+
}): Promise<PrivateClawInviteBundle> {
|
|
397
1260
|
await this.connect();
|
|
398
1261
|
|
|
1262
|
+
const groupMode = params?.groupMode === true;
|
|
399
1263
|
const { sessionId, expiresAt } = await this.relayClient.createSession(
|
|
400
1264
|
params?.ttlMs ?? this.options.defaultTtlMs,
|
|
401
1265
|
params?.label,
|
|
1266
|
+
groupMode,
|
|
402
1267
|
);
|
|
403
1268
|
|
|
404
1269
|
const invite: PrivateClawInvite = {
|
|
@@ -407,23 +1272,29 @@ export class PrivateClawProvider {
|
|
|
407
1272
|
sessionKey: generateSessionKey(),
|
|
408
1273
|
appWsUrl: this.buildSessionAppUrl(sessionId),
|
|
409
1274
|
expiresAt,
|
|
1275
|
+
...(groupMode ? { groupMode: true } : {}),
|
|
410
1276
|
...(this.options.providerLabel ? { providerLabel: this.options.providerLabel } : {}),
|
|
411
1277
|
};
|
|
412
1278
|
|
|
413
1279
|
this.sessions.set(sessionId, {
|
|
414
1280
|
invite,
|
|
415
1281
|
history: [],
|
|
1282
|
+
groupMode,
|
|
1283
|
+
botMuted: false,
|
|
1284
|
+
participants: new Map<string, ProviderParticipantState>(),
|
|
416
1285
|
state: "awaiting_hello",
|
|
417
1286
|
});
|
|
1287
|
+
this.scheduleRenewalReminder(sessionId);
|
|
418
1288
|
|
|
419
1289
|
const inviteUri = encodeInviteToUri(invite);
|
|
420
1290
|
const qrSvg = await QRCode.toString(inviteUri, {
|
|
421
1291
|
type: "svg",
|
|
422
|
-
errorCorrectionLevel:
|
|
423
|
-
margin:
|
|
1292
|
+
errorCorrectionLevel: PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL,
|
|
1293
|
+
margin: PRIVATECLAW_QR_SVG_MARGIN,
|
|
424
1294
|
});
|
|
425
1295
|
const qrTerminal = await QRCode.toString(inviteUri, {
|
|
426
1296
|
type: "terminal",
|
|
1297
|
+
margin: PRIVATECLAW_QR_TERMINAL_MARGIN,
|
|
427
1298
|
small: true,
|
|
428
1299
|
});
|
|
429
1300
|
|
|
@@ -432,9 +1303,11 @@ export class PrivateClawProvider {
|
|
|
432
1303
|
inviteUri,
|
|
433
1304
|
qrSvg,
|
|
434
1305
|
qrTerminal,
|
|
435
|
-
announcementText:
|
|
436
|
-
|
|
437
|
-
|
|
1306
|
+
announcementText: buildInviteAnnouncementText({
|
|
1307
|
+
sessionId,
|
|
1308
|
+
expiresAt,
|
|
1309
|
+
groupMode,
|
|
1310
|
+
}),
|
|
438
1311
|
};
|
|
439
1312
|
}
|
|
440
1313
|
|