@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/dist/provider.js
CHANGED
|
@@ -1,7 +1,33 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
1
2
|
import { decodeInviteString, decryptPayload, encodeInviteToUri, encryptPayload, generateSessionKey, } from "@privateclaw/protocol";
|
|
2
3
|
import QRCode from "qrcode";
|
|
4
|
+
import { PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL, PRIVATECLAW_QR_SVG_MARGIN, PRIVATECLAW_QR_TERMINAL_MARGIN, } from "./qr-options.js";
|
|
3
5
|
import { RelayProviderClient } from "./relay-provider-client.js";
|
|
4
|
-
|
|
6
|
+
import { buildInviteAnnouncementText, formatBilingualInline, formatBilingualText, PRIVATECLAW_MUTE_BOT_DESCRIPTION, PRIVATECLAW_RENEW_SESSION_DESCRIPTION, PRIVATECLAW_UNMUTE_BOT_DESCRIPTION, } from "./text.js";
|
|
7
|
+
export const DEFAULT_SESSION_TTL_MS = 8 * 60 * 60 * 1000;
|
|
8
|
+
const RENEW_SESSION_TTL_MS = DEFAULT_SESSION_TTL_MS;
|
|
9
|
+
const SESSION_RENEWAL_REMINDER_WINDOW_MS = 30 * 60 * 1000;
|
|
10
|
+
const PARTICIPANT_LABEL_MAX_CHARS = 12;
|
|
11
|
+
const PARTICIPANT_FALLBACK_PREFIXES = [
|
|
12
|
+
"流萤",
|
|
13
|
+
"星河",
|
|
14
|
+
"青柠",
|
|
15
|
+
"雾岚",
|
|
16
|
+
"松果",
|
|
17
|
+
"电光",
|
|
18
|
+
"夜航",
|
|
19
|
+
"珊瑚",
|
|
20
|
+
];
|
|
21
|
+
const PARTICIPANT_FALLBACK_SUFFIXES = [
|
|
22
|
+
"狐",
|
|
23
|
+
"猫",
|
|
24
|
+
"鲸",
|
|
25
|
+
"鹿",
|
|
26
|
+
"狸",
|
|
27
|
+
"鹭",
|
|
28
|
+
"狼",
|
|
29
|
+
"鸮",
|
|
30
|
+
];
|
|
5
31
|
function normalizeBridgeMessages(response) {
|
|
6
32
|
if (typeof response === "string") {
|
|
7
33
|
return [{ text: response }];
|
|
@@ -13,6 +39,156 @@ function normalizeBridgeMessages(response) {
|
|
|
13
39
|
function nowIso() {
|
|
14
40
|
return new Date().toISOString();
|
|
15
41
|
}
|
|
42
|
+
function buildMessageId(prefix) {
|
|
43
|
+
return `${prefix}-${randomUUID()}`;
|
|
44
|
+
}
|
|
45
|
+
function sanitizeParticipantLabel(raw) {
|
|
46
|
+
if (!raw) {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
const normalized = raw
|
|
50
|
+
.replace(/\s+/g, " ")
|
|
51
|
+
.trim()
|
|
52
|
+
.replace(/^["'`]+|["'`]+$/g, "");
|
|
53
|
+
if (normalized === "") {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
const cleaned = normalized
|
|
57
|
+
.replace(/[^\p{Letter}\p{Number}\s_-]/gu, "")
|
|
58
|
+
.trim();
|
|
59
|
+
if (cleaned === "") {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
return [...cleaned].slice(0, PARTICIPANT_LABEL_MAX_CHARS).join("");
|
|
63
|
+
}
|
|
64
|
+
function deterministicHash(input) {
|
|
65
|
+
let hash = 0;
|
|
66
|
+
for (const char of input) {
|
|
67
|
+
hash = (hash * 31 + char.codePointAt(0)) >>> 0;
|
|
68
|
+
}
|
|
69
|
+
return hash;
|
|
70
|
+
}
|
|
71
|
+
function buildFallbackParticipantLabel(appId) {
|
|
72
|
+
const prefix = PARTICIPANT_FALLBACK_PREFIXES[deterministicHash(`prefix:${appId}`) % PARTICIPANT_FALLBACK_PREFIXES.length];
|
|
73
|
+
const suffix = PARTICIPANT_FALLBACK_SUFFIXES[deterministicHash(`suffix:${appId}`) % PARTICIPANT_FALLBACK_SUFFIXES.length];
|
|
74
|
+
return `${prefix}${suffix}`;
|
|
75
|
+
}
|
|
76
|
+
function buildDerivedBridgeSessionId(sessionId, scope) {
|
|
77
|
+
const hex = createHash("sha256")
|
|
78
|
+
.update(`${sessionId}:${scope}`)
|
|
79
|
+
.digest("hex")
|
|
80
|
+
.slice(0, 32)
|
|
81
|
+
.split("");
|
|
82
|
+
hex[12] = "5";
|
|
83
|
+
const variant = Number.parseInt(hex[16], 16);
|
|
84
|
+
hex[16] = ((variant & 0x3) | 0x8).toString(16);
|
|
85
|
+
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("")}`;
|
|
86
|
+
}
|
|
87
|
+
function buildRenewalReminderMessage(session) {
|
|
88
|
+
const command = "/renew-session";
|
|
89
|
+
if (session.groupMode) {
|
|
90
|
+
return formatBilingualText(`这个 PrivateClaw 群聊会话将在 30 分钟内过期(${session.invite.expiresAt})。任意参与者都可以发送 ${command} 将它延长 8 小时。`, `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.`);
|
|
91
|
+
}
|
|
92
|
+
return formatBilingualText(`这个 PrivateClaw 会话将在 30 分钟内过期(${session.invite.expiresAt})。发送 ${command} 可将它延长 8 小时。`, `This PrivateClaw session will expire in less than 30 minutes (at ${session.invite.expiresAt}). Send ${command} to extend it by 8 hours.`);
|
|
93
|
+
}
|
|
94
|
+
function normalizeBridgeText(response) {
|
|
95
|
+
if (typeof response === "string") {
|
|
96
|
+
return response;
|
|
97
|
+
}
|
|
98
|
+
return response.messages
|
|
99
|
+
.map((message) => typeof message === "string" ? message : message.text)
|
|
100
|
+
.find((message) => message.trim() !== "") ?? "";
|
|
101
|
+
}
|
|
102
|
+
function formatBridgeHistoryTurn(turn) {
|
|
103
|
+
if (turn.role !== "user" || !turn.participantLabel) {
|
|
104
|
+
return turn;
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
...turn,
|
|
108
|
+
text: `${turn.participantLabel}: ${turn.text}`,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function toParticipantSnapshot(participant) {
|
|
112
|
+
return {
|
|
113
|
+
appId: participant.appId,
|
|
114
|
+
displayName: participant.displayName,
|
|
115
|
+
...(participant.deviceLabel ? { deviceLabel: participant.deviceLabel } : {}),
|
|
116
|
+
joinedAt: participant.joinedAt,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function buildParticipantNamingPrompt(deviceLabel) {
|
|
120
|
+
return [
|
|
121
|
+
"Generate one playful nickname for a PrivateClaw group participant.",
|
|
122
|
+
"Rules:",
|
|
123
|
+
"- return the nickname only",
|
|
124
|
+
"- no quotes, emoji, punctuation, or explanation",
|
|
125
|
+
"- maximum 6 Chinese characters or 12 ASCII characters",
|
|
126
|
+
"- make it short, memorable, and cute",
|
|
127
|
+
...(deviceLabel
|
|
128
|
+
? [`The participant's device label is: ${deviceLabel}`]
|
|
129
|
+
: []),
|
|
130
|
+
].join("\n");
|
|
131
|
+
}
|
|
132
|
+
function buildWelcomeMessage() {
|
|
133
|
+
return formatBilingualText("PrivateClaw 已连接。从现在起,消息都会通过这个一次性的端到端加密会话进行保护。", "PrivateClaw connected. Messages from now on are protected by this one-time end-to-end encrypted session.");
|
|
134
|
+
}
|
|
135
|
+
function buildCommandDoesNotAcceptAttachmentsMessage(command) {
|
|
136
|
+
return formatBilingualInline(`${command} 命令不接受附件。`, `The ${command} command does not accept attachments.`);
|
|
137
|
+
}
|
|
138
|
+
function buildCommandDoesNotAcceptArgumentsMessage(command) {
|
|
139
|
+
return formatBilingualInline(`${command} 命令不接受参数。`, `The ${command} command does not accept arguments.`);
|
|
140
|
+
}
|
|
141
|
+
function buildRenewalAlreadyInProgressMessage() {
|
|
142
|
+
return formatBilingualInline("会话续期已经在进行中。请等待重新握手完成后再重试。", "A session renewal is already in progress. Wait for the reconnect handshake to finish and try again.");
|
|
143
|
+
}
|
|
144
|
+
function buildRenewalPayloadMessage() {
|
|
145
|
+
return formatBilingualInline("会话已续期。", "Session renewed.");
|
|
146
|
+
}
|
|
147
|
+
function buildRenewalInitiatedMessage(expiresAt) {
|
|
148
|
+
return formatBilingualInline(`PrivateClaw 会话续期已开始,新过期时间为 ${expiresAt}。`, `PrivateClaw session renewal initiated until ${expiresAt}.`);
|
|
149
|
+
}
|
|
150
|
+
function buildSessionKeyRotationCompletedMessage(participantLabel) {
|
|
151
|
+
return formatBilingualInline(`${participantLabel} 已完成会话密钥轮换。`, `${participantLabel} completed session key rotation.`);
|
|
152
|
+
}
|
|
153
|
+
function buildSingleSessionConnectedMessage(participantLabel) {
|
|
154
|
+
return formatBilingualInline(`${participantLabel} 已连接。`, `${participantLabel} connected.`);
|
|
155
|
+
}
|
|
156
|
+
function buildParticipantJoinedMessage(participantLabel) {
|
|
157
|
+
return formatBilingualInline(`${participantLabel} 加入了群聊。`, `${participantLabel} joined the group chat.`);
|
|
158
|
+
}
|
|
159
|
+
function buildParticipantLeftMessage(participantLabel) {
|
|
160
|
+
return formatBilingualInline(`${participantLabel} 离开了群聊。`, `${participantLabel} left the group chat.`);
|
|
161
|
+
}
|
|
162
|
+
function buildHandshakeIncompleteMessage() {
|
|
163
|
+
return formatBilingualInline("PrivateClaw 握手尚未完成。请重新扫码或重试连接。", "The PrivateClaw handshake is not complete yet. Scan the QR code again or retry the connection.");
|
|
164
|
+
}
|
|
165
|
+
function buildMissingParticipantIdentityMessage() {
|
|
166
|
+
return formatBilingualInline("当前群成员缺少稳定的应用身份。请从 PrivateClaw App 重新加入会话。", "This group participant is missing a stable app identity. Rejoin the session from the PrivateClaw app.");
|
|
167
|
+
}
|
|
168
|
+
function buildRenewSessionFailureMessage(details) {
|
|
169
|
+
return formatBilingualInline(`PrivateClaw 会话续期失败:${details}`, `Failed to renew the PrivateClaw session: ${details}`);
|
|
170
|
+
}
|
|
171
|
+
function buildBridgeErrorMessage(details) {
|
|
172
|
+
return formatBilingualInline(`OpenClaw bridge 错误:${details}`, `OpenClaw bridge error: ${details}`);
|
|
173
|
+
}
|
|
174
|
+
function buildUnsupportedPayloadMessage(kind) {
|
|
175
|
+
return formatBilingualInline(`不支持的 PrivateClaw 负载类型:${kind}`, `Unsupported PrivateClaw payload: ${kind}`);
|
|
176
|
+
}
|
|
177
|
+
function buildGroupOnlyCommandMessage(command) {
|
|
178
|
+
return formatBilingualInline(`${command} 只能在群聊会话中使用。`, `${command} is only available in group sessions.`);
|
|
179
|
+
}
|
|
180
|
+
function buildBotMutedMessage(participantLabel) {
|
|
181
|
+
return formatBilingualInline(`${participantLabel} 已暂停机器人参与群聊。`, `${participantLabel} paused bot replies for this group chat.`);
|
|
182
|
+
}
|
|
183
|
+
function buildBotUnmutedMessage(participantLabel) {
|
|
184
|
+
return formatBilingualInline(`${participantLabel} 已恢复机器人参与群聊。`, `${participantLabel} resumed bot replies for this group chat.`);
|
|
185
|
+
}
|
|
186
|
+
function buildBotAlreadyMutedMessage() {
|
|
187
|
+
return formatBilingualInline("机器人目前已经处于静默状态。", "Bot replies are already muted.");
|
|
188
|
+
}
|
|
189
|
+
function buildBotAlreadyUnmutedMessage() {
|
|
190
|
+
return formatBilingualInline("机器人目前已经处于可回复状态。", "Bot replies are already enabled.");
|
|
191
|
+
}
|
|
16
192
|
function dedupeCommands(commands) {
|
|
17
193
|
const unique = new Map();
|
|
18
194
|
for (const command of commands) {
|
|
@@ -32,7 +208,7 @@ export class PrivateClawProvider {
|
|
|
32
208
|
await this.handleRelayFrame(sessionId, envelope);
|
|
33
209
|
},
|
|
34
210
|
onSessionClosed: async (sessionId, reason) => {
|
|
35
|
-
this.
|
|
211
|
+
this.deleteSession(sessionId);
|
|
36
212
|
this.options.onLog?.(`Session ${sessionId} closed by relay: ${reason}`);
|
|
37
213
|
},
|
|
38
214
|
onError: (message) => {
|
|
@@ -52,8 +228,10 @@ export class PrivateClawProvider {
|
|
|
52
228
|
catch (error) {
|
|
53
229
|
this.options.onLog?.(`[provider] failed to close session ${sessionId} during shutdown: ${error instanceof Error ? error.message : String(error)}`);
|
|
54
230
|
}
|
|
231
|
+
finally {
|
|
232
|
+
this.deleteSession(sessionId);
|
|
233
|
+
}
|
|
55
234
|
}
|
|
56
|
-
this.sessions.clear();
|
|
57
235
|
await this.relayClient.dispose();
|
|
58
236
|
}
|
|
59
237
|
listActiveSessions() {
|
|
@@ -71,84 +249,322 @@ export class PrivateClawProvider {
|
|
|
71
249
|
}
|
|
72
250
|
return session;
|
|
73
251
|
}
|
|
74
|
-
|
|
252
|
+
deleteSession(sessionId) {
|
|
253
|
+
const session = this.sessions.get(sessionId);
|
|
254
|
+
if (!session) {
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
if (session.renewalReminderTimer) {
|
|
258
|
+
clearTimeout(session.renewalReminderTimer);
|
|
259
|
+
delete session.renewalReminderTimer;
|
|
260
|
+
}
|
|
261
|
+
this.sessions.delete(sessionId);
|
|
262
|
+
return session;
|
|
263
|
+
}
|
|
264
|
+
buildBridgeHistory(session) {
|
|
265
|
+
return session.history.map(formatBridgeHistoryTurn);
|
|
266
|
+
}
|
|
267
|
+
listParticipants(session) {
|
|
268
|
+
return [...session.participants.values()]
|
|
269
|
+
.sort((left, right) => left.joinedAt.localeCompare(right.joinedAt))
|
|
270
|
+
.map(toParticipantSnapshot);
|
|
271
|
+
}
|
|
272
|
+
scheduleRenewalReminder(sessionId) {
|
|
273
|
+
const session = this.sessions.get(sessionId);
|
|
274
|
+
if (!session) {
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (session.renewalReminderTimer) {
|
|
278
|
+
clearTimeout(session.renewalReminderTimer);
|
|
279
|
+
}
|
|
280
|
+
delete session.renewalReminderTimer;
|
|
281
|
+
delete session.renewalReminderSentAt;
|
|
282
|
+
const renewAtMs = new Date(session.invite.expiresAt).getTime() -
|
|
283
|
+
SESSION_RENEWAL_REMINDER_WINDOW_MS;
|
|
284
|
+
const delayMs = Math.max(0, renewAtMs - Date.now());
|
|
285
|
+
session.renewalReminderTimer = setTimeout(() => {
|
|
286
|
+
void this.sendRenewalReminder(sessionId).catch((error) => {
|
|
287
|
+
this.options.onLog?.(`[provider] failed to send renewal reminder for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
288
|
+
});
|
|
289
|
+
}, delayMs);
|
|
290
|
+
}
|
|
291
|
+
async sendRenewalReminder(sessionId) {
|
|
292
|
+
const session = this.sessions.get(sessionId);
|
|
293
|
+
if (!session) {
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
delete session.renewalReminderTimer;
|
|
297
|
+
if (session.pendingRenewal || session.renewalReminderSentAt) {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
const remainingMs = new Date(session.invite.expiresAt).getTime() - Date.now();
|
|
301
|
+
if (remainingMs > SESSION_RENEWAL_REMINDER_WINDOW_MS) {
|
|
302
|
+
this.scheduleRenewalReminder(sessionId);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
const sentAt = nowIso();
|
|
306
|
+
session.renewalReminderSentAt = sentAt;
|
|
307
|
+
await this.sendSystemMessage(sessionId, buildRenewalReminderMessage(session), "info", undefined, { sentAt });
|
|
308
|
+
}
|
|
309
|
+
async generateParticipantLabel(sessionId, appId, deviceLabel) {
|
|
310
|
+
const session = this.requireSession(sessionId);
|
|
311
|
+
const bridgeSessionId = buildDerivedBridgeSessionId(sessionId, `participant:${appId}`);
|
|
312
|
+
try {
|
|
313
|
+
const bridgeResponse = await this.options.bridge.handleUserMessage({
|
|
314
|
+
sessionId: bridgeSessionId,
|
|
315
|
+
invite: {
|
|
316
|
+
...session.invite,
|
|
317
|
+
sessionId: bridgeSessionId,
|
|
318
|
+
},
|
|
319
|
+
message: buildParticipantNamingPrompt(deviceLabel),
|
|
320
|
+
history: [],
|
|
321
|
+
});
|
|
322
|
+
const generated = sanitizeParticipantLabel(normalizeBridgeText(bridgeResponse));
|
|
323
|
+
if (generated) {
|
|
324
|
+
return generated;
|
|
325
|
+
}
|
|
326
|
+
throw new Error("nickname generation returned an empty label");
|
|
327
|
+
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
this.options.onLog?.(`[provider] participant nickname fallback for ${appId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
330
|
+
return buildFallbackParticipantLabel(appId);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
async upsertParticipant(sessionId, params) {
|
|
334
|
+
const session = this.requireSession(sessionId);
|
|
335
|
+
const normalizedAppId = params.appId?.trim() || "legacy-app";
|
|
336
|
+
const existing = session.participants.get(normalizedAppId);
|
|
337
|
+
const requestedDisplayName = sanitizeParticipantLabel(params.displayName);
|
|
338
|
+
if (existing) {
|
|
339
|
+
const participant = {
|
|
340
|
+
...existing,
|
|
341
|
+
...(params.deviceLabel ? { deviceLabel: params.deviceLabel } : {}),
|
|
342
|
+
...(requestedDisplayName ? { displayName: requestedDisplayName } : {}),
|
|
343
|
+
lastSeenAt: params.sentAt,
|
|
344
|
+
};
|
|
345
|
+
session.participants.set(normalizedAppId, participant);
|
|
346
|
+
return { participant, isNew: false };
|
|
347
|
+
}
|
|
348
|
+
const participant = {
|
|
349
|
+
appId: normalizedAppId,
|
|
350
|
+
displayName: requestedDisplayName ??
|
|
351
|
+
(await this.generateParticipantLabel(sessionId, normalizedAppId, params.deviceLabel)),
|
|
352
|
+
...(params.deviceLabel ? { deviceLabel: params.deviceLabel } : {}),
|
|
353
|
+
joinedAt: params.sentAt,
|
|
354
|
+
lastSeenAt: params.sentAt,
|
|
355
|
+
};
|
|
356
|
+
session.participants.set(normalizedAppId, participant);
|
|
357
|
+
return { participant, isNew: true };
|
|
358
|
+
}
|
|
359
|
+
async sendPayloadWithSessionKey(sessionId, sessionKey, payload, targetAppId) {
|
|
75
360
|
await this.relayClient.sendFrame(sessionId, encryptPayload({
|
|
76
361
|
sessionId,
|
|
77
362
|
sessionKey,
|
|
78
363
|
payload,
|
|
79
|
-
}));
|
|
364
|
+
}), targetAppId);
|
|
80
365
|
}
|
|
81
|
-
async sendPayload(sessionId, payload) {
|
|
366
|
+
async sendPayload(sessionId, payload, targetAppId) {
|
|
82
367
|
const session = this.requireSession(sessionId);
|
|
83
|
-
await this.sendPayloadWithSessionKey(sessionId, session.invite.sessionKey, payload);
|
|
368
|
+
await this.sendPayloadWithSessionKey(sessionId, session.invite.sessionKey, payload, targetAppId);
|
|
84
369
|
}
|
|
85
370
|
async sendAssistantMessage(sessionId, params) {
|
|
86
|
-
const sentAt = nowIso();
|
|
371
|
+
const sentAt = params.sentAt ?? nowIso();
|
|
372
|
+
const messageId = params.messageId ?? buildMessageId("assistant");
|
|
87
373
|
const session = this.requireSession(sessionId);
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
374
|
+
if (params.storeHistory !== false) {
|
|
375
|
+
session.history.push({
|
|
376
|
+
messageId,
|
|
377
|
+
role: "assistant",
|
|
378
|
+
text: params.text,
|
|
379
|
+
sentAt,
|
|
380
|
+
...(params.replyTo ? { replyTo: params.replyTo } : {}),
|
|
381
|
+
...(params.attachments ? { attachments: params.attachments } : {}),
|
|
382
|
+
});
|
|
383
|
+
}
|
|
94
384
|
await this.sendPayload(sessionId, {
|
|
95
385
|
kind: "assistant_message",
|
|
386
|
+
messageId,
|
|
96
387
|
text: params.text,
|
|
97
388
|
sentAt,
|
|
98
389
|
...(params.replyTo ? { replyTo: params.replyTo } : {}),
|
|
99
390
|
...(params.attachments ? { attachments: params.attachments } : {}),
|
|
100
|
-
});
|
|
391
|
+
}, params.targetAppId);
|
|
101
392
|
}
|
|
102
|
-
async sendSystemMessage(sessionId, message, severity = "info", replyTo) {
|
|
103
|
-
const sentAt = nowIso();
|
|
393
|
+
async sendSystemMessage(sessionId, message, severity = "info", replyTo, params) {
|
|
394
|
+
const sentAt = params?.sentAt ?? nowIso();
|
|
395
|
+
const messageId = params?.messageId ?? buildMessageId("system");
|
|
104
396
|
const session = this.requireSession(sessionId);
|
|
105
|
-
|
|
397
|
+
if (params?.storeHistory !== false) {
|
|
398
|
+
session.history.push({
|
|
399
|
+
messageId,
|
|
400
|
+
role: "system",
|
|
401
|
+
text: message,
|
|
402
|
+
sentAt,
|
|
403
|
+
...(replyTo ? { replyTo } : {}),
|
|
404
|
+
severity,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
106
407
|
await this.sendPayload(sessionId, {
|
|
107
408
|
kind: "system_message",
|
|
409
|
+
messageId,
|
|
108
410
|
message,
|
|
109
411
|
severity,
|
|
110
412
|
sentAt,
|
|
111
413
|
...(replyTo ? { replyTo } : {}),
|
|
414
|
+
}, params?.targetAppId);
|
|
415
|
+
}
|
|
416
|
+
async sendSystemMessageToGroupParticipants(sessionId, message, params) {
|
|
417
|
+
const session = this.requireSession(sessionId);
|
|
418
|
+
const sentAt = params?.sentAt ?? nowIso();
|
|
419
|
+
const severity = params?.severity ?? "info";
|
|
420
|
+
const messageId = buildMessageId("system");
|
|
421
|
+
const targetAppIds = [...session.participants.keys()].filter((appId) => appId !== params?.excludeAppId);
|
|
422
|
+
if (targetAppIds.length === 0) {
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
session.history.push({
|
|
426
|
+
messageId,
|
|
427
|
+
role: "system",
|
|
428
|
+
text: message,
|
|
429
|
+
sentAt,
|
|
430
|
+
severity,
|
|
112
431
|
});
|
|
432
|
+
await Promise.all(targetAppIds.map((targetAppId) => this.sendPayload(sessionId, {
|
|
433
|
+
kind: "system_message",
|
|
434
|
+
messageId,
|
|
435
|
+
message,
|
|
436
|
+
severity,
|
|
437
|
+
sentAt,
|
|
438
|
+
}, targetAppId)));
|
|
439
|
+
}
|
|
440
|
+
async sendParticipantMessage(sessionId, params) {
|
|
441
|
+
const sentAt = params.sentAt ?? nowIso();
|
|
442
|
+
const session = this.requireSession(sessionId);
|
|
443
|
+
if (params.storeHistory !== false) {
|
|
444
|
+
session.history.push({
|
|
445
|
+
messageId: params.clientMessageId,
|
|
446
|
+
role: "user",
|
|
447
|
+
text: params.text,
|
|
448
|
+
sentAt,
|
|
449
|
+
appId: params.senderAppId,
|
|
450
|
+
participantLabel: params.senderDisplayName,
|
|
451
|
+
...(params.attachments ? { attachments: params.attachments } : {}),
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
await this.sendPayload(sessionId, {
|
|
455
|
+
kind: "participant_message",
|
|
456
|
+
messageId: params.clientMessageId,
|
|
457
|
+
senderAppId: params.senderAppId,
|
|
458
|
+
senderDisplayName: params.senderDisplayName,
|
|
459
|
+
text: params.text,
|
|
460
|
+
clientMessageId: params.clientMessageId,
|
|
461
|
+
sentAt,
|
|
462
|
+
...(params.attachments ? { attachments: params.attachments } : {}),
|
|
463
|
+
}, params.targetAppId);
|
|
113
464
|
}
|
|
114
|
-
async sendWelcomeMessage(sessionId) {
|
|
465
|
+
async sendWelcomeMessage(sessionId, targetAppId) {
|
|
115
466
|
const sentAt = nowIso();
|
|
116
|
-
const message = this.options.welcomeMessage ??
|
|
117
|
-
"PrivateClaw connected. Messages from now on are protected by this one-time end-to-end encrypted session.";
|
|
467
|
+
const message = this.options.welcomeMessage ?? buildWelcomeMessage();
|
|
118
468
|
await this.sendPayload(sessionId, {
|
|
119
469
|
kind: "server_welcome",
|
|
120
470
|
message,
|
|
121
471
|
sentAt,
|
|
122
|
-
});
|
|
472
|
+
}, targetAppId);
|
|
123
473
|
}
|
|
124
|
-
async listAvailableCommands() {
|
|
474
|
+
async listAvailableCommands(session) {
|
|
125
475
|
const discovered = (await this.options.commandsProvider?.()) ?? [];
|
|
126
|
-
|
|
476
|
+
const commands = [
|
|
127
477
|
...discovered,
|
|
128
478
|
{
|
|
129
479
|
slash: "/renew-session",
|
|
130
|
-
description:
|
|
480
|
+
description: PRIVATECLAW_RENEW_SESSION_DESCRIPTION,
|
|
131
481
|
acceptsArgs: false,
|
|
132
482
|
source: "privateclaw",
|
|
133
483
|
},
|
|
134
|
-
]
|
|
484
|
+
];
|
|
485
|
+
if (session.groupMode) {
|
|
486
|
+
commands.push({
|
|
487
|
+
slash: session.botMuted ? "/unmute-bot" : "/mute-bot",
|
|
488
|
+
description: session.botMuted
|
|
489
|
+
? PRIVATECLAW_UNMUTE_BOT_DESCRIPTION
|
|
490
|
+
: PRIVATECLAW_MUTE_BOT_DESCRIPTION,
|
|
491
|
+
acceptsArgs: false,
|
|
492
|
+
source: "privateclaw",
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
return dedupeCommands(commands);
|
|
135
496
|
}
|
|
136
|
-
async sendCapabilities(sessionId) {
|
|
497
|
+
async sendCapabilities(sessionId, params) {
|
|
137
498
|
const session = this.requireSession(sessionId);
|
|
499
|
+
const currentParticipant = params?.targetAppId
|
|
500
|
+
? session.participants.get(params.targetAppId)
|
|
501
|
+
: undefined;
|
|
138
502
|
await this.sendPayload(sessionId, {
|
|
139
503
|
kind: "provider_capabilities",
|
|
140
504
|
sentAt: nowIso(),
|
|
141
505
|
expiresAt: session.invite.expiresAt,
|
|
142
|
-
|
|
506
|
+
...(session.groupMode ? { groupMode: true } : {}),
|
|
507
|
+
...(session.groupMode ? { botMuted: session.botMuted } : {}),
|
|
508
|
+
commands: await this.listAvailableCommands(session),
|
|
509
|
+
...(session.groupMode
|
|
510
|
+
? { participants: this.listParticipants(session) }
|
|
511
|
+
: {}),
|
|
143
512
|
...(session.invite.providerLabel
|
|
144
513
|
? { providerLabel: session.invite.providerLabel }
|
|
145
514
|
: {}),
|
|
146
|
-
|
|
515
|
+
...(params?.includeCurrentIdentity && currentParticipant
|
|
516
|
+
? {
|
|
517
|
+
currentAppId: currentParticipant.appId,
|
|
518
|
+
currentDisplayName: currentParticipant.displayName,
|
|
519
|
+
}
|
|
520
|
+
: {}),
|
|
521
|
+
}, params?.targetAppId);
|
|
522
|
+
}
|
|
523
|
+
async sendHistorySnapshot(sessionId, targetAppId) {
|
|
524
|
+
const session = this.requireSession(sessionId);
|
|
525
|
+
for (const turn of session.history) {
|
|
526
|
+
switch (turn.role) {
|
|
527
|
+
case "assistant":
|
|
528
|
+
await this.sendAssistantMessage(sessionId, {
|
|
529
|
+
messageId: turn.messageId,
|
|
530
|
+
text: turn.text,
|
|
531
|
+
sentAt: turn.sentAt,
|
|
532
|
+
targetAppId,
|
|
533
|
+
storeHistory: false,
|
|
534
|
+
...(turn.replyTo ? { replyTo: turn.replyTo } : {}),
|
|
535
|
+
...(turn.attachments ? { attachments: turn.attachments } : {}),
|
|
536
|
+
});
|
|
537
|
+
break;
|
|
538
|
+
case "system":
|
|
539
|
+
await this.sendSystemMessage(sessionId, turn.text, turn.severity ?? "info", turn.replyTo, {
|
|
540
|
+
messageId: turn.messageId,
|
|
541
|
+
sentAt: turn.sentAt,
|
|
542
|
+
targetAppId,
|
|
543
|
+
storeHistory: false,
|
|
544
|
+
});
|
|
545
|
+
break;
|
|
546
|
+
case "user":
|
|
547
|
+
if (!session.groupMode || !turn.appId || !turn.participantLabel) {
|
|
548
|
+
break;
|
|
549
|
+
}
|
|
550
|
+
await this.sendParticipantMessage(sessionId, {
|
|
551
|
+
text: turn.text,
|
|
552
|
+
senderAppId: turn.appId,
|
|
553
|
+
senderDisplayName: turn.participantLabel,
|
|
554
|
+
clientMessageId: turn.messageId,
|
|
555
|
+
sentAt: turn.sentAt,
|
|
556
|
+
targetAppId,
|
|
557
|
+
storeHistory: false,
|
|
558
|
+
...(turn.attachments ? { attachments: turn.attachments } : {}),
|
|
559
|
+
});
|
|
560
|
+
break;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
147
563
|
}
|
|
148
564
|
async renewSession(sessionId, replyTo) {
|
|
149
565
|
const session = this.requireSession(sessionId);
|
|
150
566
|
if (session.pendingRenewal) {
|
|
151
|
-
await this.sendSystemMessage(sessionId,
|
|
567
|
+
await this.sendSystemMessage(sessionId, buildRenewalAlreadyInProgressMessage(), "error", replyTo);
|
|
152
568
|
return;
|
|
153
569
|
}
|
|
154
570
|
const { expiresAt } = await this.relayClient.renewSession(sessionId, RENEW_SESSION_TTL_MS);
|
|
@@ -157,7 +573,7 @@ export class PrivateClawProvider {
|
|
|
157
573
|
const nextSessionKey = generateSessionKey();
|
|
158
574
|
await this.sendPayloadWithSessionKey(sessionId, previousSessionKey, {
|
|
159
575
|
kind: "session_renewed",
|
|
160
|
-
message:
|
|
576
|
+
message: buildRenewalPayloadMessage(),
|
|
161
577
|
newSessionKey: nextSessionKey,
|
|
162
578
|
expiresAt,
|
|
163
579
|
sentAt,
|
|
@@ -169,11 +585,14 @@ export class PrivateClawProvider {
|
|
|
169
585
|
expiresAt,
|
|
170
586
|
};
|
|
171
587
|
session.pendingRenewal = { expiresAt, sentAt };
|
|
588
|
+
this.scheduleRenewalReminder(sessionId);
|
|
172
589
|
session.state = "awaiting_hello";
|
|
173
590
|
session.history.push({
|
|
591
|
+
messageId: buildMessageId("system"),
|
|
174
592
|
role: "system",
|
|
175
|
-
text:
|
|
593
|
+
text: buildRenewalInitiatedMessage(expiresAt),
|
|
176
594
|
sentAt,
|
|
595
|
+
severity: "info",
|
|
177
596
|
});
|
|
178
597
|
}
|
|
179
598
|
async handleRelayFrame(sessionId, envelope) {
|
|
@@ -185,65 +604,169 @@ export class PrivateClawProvider {
|
|
|
185
604
|
});
|
|
186
605
|
switch (payload.kind) {
|
|
187
606
|
case "client_hello": {
|
|
607
|
+
const participantState = await this.upsertParticipant(sessionId, {
|
|
608
|
+
sentAt: payload.sentAt,
|
|
609
|
+
...(payload.appId ? { appId: payload.appId } : {}),
|
|
610
|
+
...(payload.deviceLabel
|
|
611
|
+
? { deviceLabel: payload.deviceLabel }
|
|
612
|
+
: {}),
|
|
613
|
+
...(payload.displayName
|
|
614
|
+
? { displayName: payload.displayName }
|
|
615
|
+
: {}),
|
|
616
|
+
});
|
|
617
|
+
const participant = participantState.participant;
|
|
188
618
|
const wasAwaitingHello = session.state !== "active";
|
|
189
619
|
const wasRenewing = Boolean(session.pendingRenewal);
|
|
190
620
|
session.state = "active";
|
|
191
621
|
if (wasRenewing) {
|
|
192
622
|
session.history.push({
|
|
623
|
+
messageId: buildMessageId("system"),
|
|
193
624
|
role: "system",
|
|
194
|
-
text:
|
|
625
|
+
text: buildSessionKeyRotationCompletedMessage(participant.displayName),
|
|
195
626
|
sentAt: payload.sentAt,
|
|
627
|
+
severity: "info",
|
|
196
628
|
});
|
|
197
629
|
delete session.pendingRenewal;
|
|
198
630
|
}
|
|
199
|
-
else if (wasAwaitingHello) {
|
|
631
|
+
else if (!session.groupMode && wasAwaitingHello) {
|
|
200
632
|
session.history.push({
|
|
633
|
+
messageId: buildMessageId("system"),
|
|
201
634
|
role: "system",
|
|
202
|
-
text:
|
|
635
|
+
text: buildSingleSessionConnectedMessage(participant.displayName),
|
|
203
636
|
sentAt: payload.sentAt,
|
|
637
|
+
severity: "info",
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
if (session.groupMode) {
|
|
641
|
+
await this.sendHistorySnapshot(sessionId, participant.appId);
|
|
642
|
+
await this.sendWelcomeMessage(sessionId, participant.appId);
|
|
643
|
+
await this.sendCapabilities(sessionId, {
|
|
644
|
+
targetAppId: participant.appId,
|
|
645
|
+
includeCurrentIdentity: true,
|
|
204
646
|
});
|
|
647
|
+
if (participantState.isNew && session.participants.size > 1) {
|
|
648
|
+
await this.sendSystemMessageToGroupParticipants(sessionId, buildParticipantJoinedMessage(participant.displayName), {
|
|
649
|
+
excludeAppId: participant.appId,
|
|
650
|
+
sentAt: payload.sentAt,
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
await this.sendCapabilities(sessionId);
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
if (wasAwaitingHello && !wasRenewing) {
|
|
205
657
|
await this.sendWelcomeMessage(sessionId);
|
|
206
658
|
}
|
|
207
|
-
await this.sendCapabilities(sessionId
|
|
659
|
+
await this.sendCapabilities(sessionId, {
|
|
660
|
+
targetAppId: participant.appId,
|
|
661
|
+
includeCurrentIdentity: true,
|
|
662
|
+
});
|
|
208
663
|
return;
|
|
209
664
|
}
|
|
210
665
|
case "user_message": {
|
|
211
666
|
if (session.state !== "active") {
|
|
212
|
-
await this.sendSystemMessage(sessionId,
|
|
667
|
+
await this.sendSystemMessage(sessionId, buildHandshakeIncompleteMessage(), "error", payload.clientMessageId);
|
|
213
668
|
return;
|
|
214
669
|
}
|
|
215
|
-
session.history.push({
|
|
216
|
-
role: "user",
|
|
217
|
-
text: payload.text,
|
|
218
|
-
sentAt: payload.sentAt,
|
|
219
|
-
...(payload.attachments ? { attachments: payload.attachments } : {}),
|
|
220
|
-
});
|
|
221
670
|
this.options.onLog?.(`[provider] user_message session=${sessionId} textChars=${payload.text.length} attachments=${payload.attachments?.length ?? 0}`);
|
|
671
|
+
const participant = (payload.appId ? session.participants.get(payload.appId) : undefined) ??
|
|
672
|
+
(session.participants.size === 1
|
|
673
|
+
? [...session.participants.values()][0]
|
|
674
|
+
: undefined);
|
|
222
675
|
const normalizedCommand = payload.text.trim().toLowerCase();
|
|
223
|
-
|
|
676
|
+
const isRenewCommand = normalizedCommand === "/renew-session" ||
|
|
677
|
+
normalizedCommand === "/session_renew";
|
|
678
|
+
const hasRenewCommandArgs = normalizedCommand.startsWith("/renew-session ") ||
|
|
679
|
+
normalizedCommand.startsWith("/session_renew ");
|
|
680
|
+
const isMuteBotCommand = normalizedCommand === "/mute-bot";
|
|
681
|
+
const hasMuteBotArgs = normalizedCommand.startsWith("/mute-bot ");
|
|
682
|
+
const isUnmuteBotCommand = normalizedCommand === "/unmute-bot";
|
|
683
|
+
const hasUnmuteBotArgs = normalizedCommand.startsWith("/unmute-bot ");
|
|
684
|
+
if (isRenewCommand) {
|
|
224
685
|
if ((payload.attachments?.length ?? 0) > 0) {
|
|
225
|
-
await this.sendSystemMessage(sessionId, "
|
|
686
|
+
await this.sendSystemMessage(sessionId, buildCommandDoesNotAcceptAttachmentsMessage("/renew-session"), "error", payload.clientMessageId);
|
|
226
687
|
return;
|
|
227
688
|
}
|
|
228
689
|
try {
|
|
229
690
|
await this.renewSession(sessionId, payload.clientMessageId);
|
|
230
691
|
}
|
|
231
692
|
catch (error) {
|
|
232
|
-
await this.sendSystemMessage(sessionId,
|
|
693
|
+
await this.sendSystemMessage(sessionId, buildRenewSessionFailureMessage(error instanceof Error ? error.message : String(error)), "error", payload.clientMessageId);
|
|
694
|
+
}
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
if (hasRenewCommandArgs) {
|
|
698
|
+
await this.sendSystemMessage(sessionId, buildCommandDoesNotAcceptArgumentsMessage("/renew-session"), "error", payload.clientMessageId);
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
if (isMuteBotCommand || isUnmuteBotCommand) {
|
|
702
|
+
const command = isMuteBotCommand ? "/mute-bot" : "/unmute-bot";
|
|
703
|
+
if ((payload.attachments?.length ?? 0) > 0) {
|
|
704
|
+
await this.sendSystemMessage(sessionId, buildCommandDoesNotAcceptAttachmentsMessage(command), "error", payload.clientMessageId);
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
if (!session.groupMode) {
|
|
708
|
+
await this.sendSystemMessage(sessionId, buildGroupOnlyCommandMessage(command), "error", payload.clientMessageId);
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
if (!participant) {
|
|
712
|
+
await this.sendSystemMessage(sessionId, buildMissingParticipantIdentityMessage(), "error", payload.clientMessageId);
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
const shouldMute = isMuteBotCommand;
|
|
716
|
+
if (session.botMuted === shouldMute) {
|
|
717
|
+
await this.sendSystemMessage(sessionId, shouldMute
|
|
718
|
+
? buildBotAlreadyMutedMessage()
|
|
719
|
+
: buildBotAlreadyUnmutedMessage(), "info", payload.clientMessageId);
|
|
720
|
+
return;
|
|
233
721
|
}
|
|
722
|
+
session.botMuted = shouldMute;
|
|
723
|
+
await this.sendSystemMessageToGroupParticipants(sessionId, shouldMute
|
|
724
|
+
? buildBotMutedMessage(participant.displayName)
|
|
725
|
+
: buildBotUnmutedMessage(participant.displayName), { sentAt: payload.sentAt });
|
|
726
|
+
await this.sendCapabilities(sessionId);
|
|
234
727
|
return;
|
|
235
728
|
}
|
|
236
|
-
if (
|
|
237
|
-
|
|
729
|
+
if (hasMuteBotArgs || hasUnmuteBotArgs) {
|
|
730
|
+
const command = hasMuteBotArgs ? "/mute-bot" : "/unmute-bot";
|
|
731
|
+
await this.sendSystemMessage(sessionId, buildCommandDoesNotAcceptArgumentsMessage(command), "error", payload.clientMessageId);
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
if (session.groupMode) {
|
|
735
|
+
if (!participant) {
|
|
736
|
+
await this.sendSystemMessage(sessionId, buildMissingParticipantIdentityMessage(), "error", payload.clientMessageId);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
await this.sendParticipantMessage(sessionId, {
|
|
740
|
+
text: payload.text,
|
|
741
|
+
senderAppId: participant.appId,
|
|
742
|
+
senderDisplayName: participant.displayName,
|
|
743
|
+
clientMessageId: payload.clientMessageId,
|
|
744
|
+
sentAt: payload.sentAt,
|
|
745
|
+
...(payload.attachments ? { attachments: payload.attachments } : {}),
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
else {
|
|
749
|
+
session.history.push({
|
|
750
|
+
messageId: payload.clientMessageId,
|
|
751
|
+
role: "user",
|
|
752
|
+
text: payload.text,
|
|
753
|
+
sentAt: payload.sentAt,
|
|
754
|
+
...(payload.attachments ? { attachments: payload.attachments } : {}),
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
if (session.groupMode && session.botMuted) {
|
|
238
758
|
return;
|
|
239
759
|
}
|
|
240
760
|
try {
|
|
761
|
+
const bridgeMessage = session.groupMode && participant
|
|
762
|
+
? `${participant.displayName}: ${payload.text}`
|
|
763
|
+
: payload.text;
|
|
241
764
|
const bridgeResponse = await this.options.bridge.handleUserMessage({
|
|
242
765
|
sessionId,
|
|
243
766
|
invite: session.invite,
|
|
244
|
-
message:
|
|
767
|
+
message: bridgeMessage,
|
|
245
768
|
...(payload.attachments ? { attachments: payload.attachments } : {}),
|
|
246
|
-
history:
|
|
769
|
+
history: this.buildBridgeHistory(session),
|
|
247
770
|
});
|
|
248
771
|
for (const message of normalizeBridgeMessages(bridgeResponse)) {
|
|
249
772
|
await this.sendAssistantMessage(sessionId, {
|
|
@@ -254,48 +777,75 @@ export class PrivateClawProvider {
|
|
|
254
777
|
}
|
|
255
778
|
}
|
|
256
779
|
catch (error) {
|
|
257
|
-
await this.sendSystemMessage(sessionId,
|
|
780
|
+
await this.sendSystemMessage(sessionId, buildBridgeErrorMessage(error instanceof Error ? error.message : String(error)), "error", payload.clientMessageId);
|
|
258
781
|
}
|
|
259
782
|
return;
|
|
260
783
|
}
|
|
261
|
-
case "session_close":
|
|
262
|
-
|
|
263
|
-
|
|
784
|
+
case "session_close": {
|
|
785
|
+
if (!session.groupMode) {
|
|
786
|
+
this.deleteSession(sessionId);
|
|
787
|
+
await this.relayClient.closeSession(sessionId, payload.reason);
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
const participantAppId = payload.appId?.trim() ||
|
|
791
|
+
(session.participants.size === 1
|
|
792
|
+
? [...session.participants.keys()][0]
|
|
793
|
+
: undefined);
|
|
794
|
+
if (!participantAppId) {
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
const participant = session.participants.get(participantAppId);
|
|
798
|
+
session.participants.delete(participantAppId);
|
|
799
|
+
if (participant && session.participants.size > 0) {
|
|
800
|
+
await this.sendSystemMessageToGroupParticipants(sessionId, buildParticipantLeftMessage(participant.displayName), { sentAt: payload.sentAt });
|
|
801
|
+
}
|
|
802
|
+
if (session.participants.size > 0) {
|
|
803
|
+
await this.sendCapabilities(sessionId);
|
|
804
|
+
}
|
|
264
805
|
return;
|
|
806
|
+
}
|
|
265
807
|
case "assistant_message":
|
|
808
|
+
case "participant_message":
|
|
266
809
|
case "server_welcome":
|
|
267
810
|
case "provider_capabilities":
|
|
268
811
|
case "session_renewed":
|
|
269
812
|
case "system_message":
|
|
270
813
|
return;
|
|
271
814
|
default:
|
|
272
|
-
await this.sendSystemMessage(sessionId,
|
|
815
|
+
await this.sendSystemMessage(sessionId, buildUnsupportedPayloadMessage(payload.kind ?? "unknown"), "error");
|
|
273
816
|
}
|
|
274
817
|
}
|
|
275
818
|
async createInviteBundle(params) {
|
|
276
819
|
await this.connect();
|
|
277
|
-
const
|
|
820
|
+
const groupMode = params?.groupMode === true;
|
|
821
|
+
const { sessionId, expiresAt } = await this.relayClient.createSession(params?.ttlMs ?? this.options.defaultTtlMs, params?.label, groupMode);
|
|
278
822
|
const invite = {
|
|
279
823
|
version: 1,
|
|
280
824
|
sessionId,
|
|
281
825
|
sessionKey: generateSessionKey(),
|
|
282
826
|
appWsUrl: this.buildSessionAppUrl(sessionId),
|
|
283
827
|
expiresAt,
|
|
828
|
+
...(groupMode ? { groupMode: true } : {}),
|
|
284
829
|
...(this.options.providerLabel ? { providerLabel: this.options.providerLabel } : {}),
|
|
285
830
|
};
|
|
286
831
|
this.sessions.set(sessionId, {
|
|
287
832
|
invite,
|
|
288
833
|
history: [],
|
|
834
|
+
groupMode,
|
|
835
|
+
botMuted: false,
|
|
836
|
+
participants: new Map(),
|
|
289
837
|
state: "awaiting_hello",
|
|
290
838
|
});
|
|
839
|
+
this.scheduleRenewalReminder(sessionId);
|
|
291
840
|
const inviteUri = encodeInviteToUri(invite);
|
|
292
841
|
const qrSvg = await QRCode.toString(inviteUri, {
|
|
293
842
|
type: "svg",
|
|
294
|
-
errorCorrectionLevel:
|
|
295
|
-
margin:
|
|
843
|
+
errorCorrectionLevel: PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL,
|
|
844
|
+
margin: PRIVATECLAW_QR_SVG_MARGIN,
|
|
296
845
|
});
|
|
297
846
|
const qrTerminal = await QRCode.toString(inviteUri, {
|
|
298
847
|
type: "terminal",
|
|
848
|
+
margin: PRIVATECLAW_QR_TERMINAL_MARGIN,
|
|
299
849
|
small: true,
|
|
300
850
|
});
|
|
301
851
|
return {
|
|
@@ -303,8 +853,11 @@ export class PrivateClawProvider {
|
|
|
303
853
|
inviteUri,
|
|
304
854
|
qrSvg,
|
|
305
855
|
qrTerminal,
|
|
306
|
-
announcementText:
|
|
307
|
-
|
|
856
|
+
announcementText: buildInviteAnnouncementText({
|
|
857
|
+
sessionId,
|
|
858
|
+
expiresAt,
|
|
859
|
+
groupMode,
|
|
860
|
+
}),
|
|
308
861
|
};
|
|
309
862
|
}
|
|
310
863
|
decodeInvite(uri) {
|