@privateclaw/privateclaw 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +100 -0
  2. package/dist/bridges/echo-bridge.d.ts +10 -0
  3. package/dist/bridges/echo-bridge.js +16 -0
  4. package/dist/bridges/echo-bridge.js.map +1 -0
  5. package/dist/bridges/openai-compatible-bridge.d.ts +15 -0
  6. package/dist/bridges/openai-compatible-bridge.js +61 -0
  7. package/dist/bridges/openai-compatible-bridge.js.map +1 -0
  8. package/dist/bridges/openclaw-agent-bridge.d.ts +35 -0
  9. package/dist/bridges/openclaw-agent-bridge.js +363 -0
  10. package/dist/bridges/openclaw-agent-bridge.js.map +1 -0
  11. package/dist/bridges/webhook-bridge.d.ts +21 -0
  12. package/dist/bridges/webhook-bridge.js +28 -0
  13. package/dist/bridges/webhook-bridge.js.map +1 -0
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +96 -0
  16. package/dist/cli.js.map +1 -0
  17. package/dist/compat/openclaw.d.ts +134 -0
  18. package/dist/compat/openclaw.js +67 -0
  19. package/dist/compat/openclaw.js.map +1 -0
  20. package/dist/index.d.ts +11 -0
  21. package/dist/index.js +12 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/openclaw-command-discovery.d.ts +2 -0
  24. package/dist/openclaw-command-discovery.js +215 -0
  25. package/dist/openclaw-command-discovery.js.map +1 -0
  26. package/dist/openclaw-plugin.d.ts +30 -0
  27. package/dist/openclaw-plugin.js +294 -0
  28. package/dist/openclaw-plugin.js.map +1 -0
  29. package/dist/provider.d.ts +31 -0
  30. package/dist/provider.js +314 -0
  31. package/dist/provider.js.map +1 -0
  32. package/dist/relay-endpoints.d.ts +6 -0
  33. package/dist/relay-endpoints.js +20 -0
  34. package/dist/relay-endpoints.js.map +1 -0
  35. package/dist/relay-provider-client.d.ts +41 -0
  36. package/dist/relay-provider-client.js +272 -0
  37. package/dist/relay-provider-client.js.map +1 -0
  38. package/dist/types.d.ts +49 -0
  39. package/dist/types.js +2 -0
  40. package/dist/types.js.map +1 -0
  41. package/index.ts +2 -0
  42. package/openclaw.plugin.json +72 -0
  43. package/package.json +66 -0
  44. package/src/bridges/echo-bridge.ts +22 -0
  45. package/src/bridges/openai-compatible-bridge.ts +105 -0
  46. package/src/bridges/openclaw-agent-bridge.test.ts +254 -0
  47. package/src/bridges/openclaw-agent-bridge.ts +490 -0
  48. package/src/bridges/webhook-bridge.ts +45 -0
  49. package/src/cli.ts +115 -0
  50. package/src/compat/openclaw.ts +139 -0
  51. package/src/index.ts +11 -0
  52. package/src/openclaw-command-discovery.ts +276 -0
  53. package/src/openclaw-plugin.test.ts +114 -0
  54. package/src/openclaw-plugin.ts +439 -0
  55. package/src/provider.test.ts +311 -0
  56. package/src/provider.ts +444 -0
  57. package/src/relay-endpoints.test.ts +17 -0
  58. package/src/relay-endpoints.ts +25 -0
  59. package/src/relay-provider-client.ts +341 -0
  60. package/src/types.ts +60 -0
  61. package/tsconfig.json +9 -0
@@ -0,0 +1,444 @@
1
+ import {
2
+ decodeInviteString,
3
+ decryptPayload,
4
+ encodeInviteToUri,
5
+ encryptPayload,
6
+ generateSessionKey,
7
+ type PrivateClawAttachment,
8
+ type PrivateClawInvite,
9
+ type PrivateClawSlashCommand,
10
+ } from "@privateclaw/protocol";
11
+ import QRCode from "qrcode";
12
+ import { RelayProviderClient } from "./relay-provider-client.js";
13
+ import type {
14
+ BridgeMessage,
15
+ BridgeResponse,
16
+ PrivateClawConversationTurn,
17
+ PrivateClawInviteBundle,
18
+ PrivateClawProviderOptions,
19
+ ProviderSessionState,
20
+ } from "./types.js";
21
+
22
+ const RENEW_SESSION_TTL_MS = 8 * 60 * 60 * 1000;
23
+
24
+ function normalizeBridgeMessages(
25
+ response: BridgeResponse,
26
+ ): Array<{ text: string; attachments?: PrivateClawAttachment[] }> {
27
+ if (typeof response === "string") {
28
+ return [{ text: response }];
29
+ }
30
+
31
+ return response.messages.map((message: BridgeMessage) =>
32
+ typeof message === "string"
33
+ ? { text: message }
34
+ : { text: message.text, ...(message.attachments ? { attachments: message.attachments } : {}) },
35
+ );
36
+ }
37
+
38
+ function nowIso(): string {
39
+ return new Date().toISOString();
40
+ }
41
+
42
+ function dedupeCommands(
43
+ commands: ReadonlyArray<PrivateClawSlashCommand>,
44
+ ): PrivateClawSlashCommand[] {
45
+ const unique = new Map<string, PrivateClawSlashCommand>();
46
+ for (const command of commands) {
47
+ unique.set(command.slash.toLowerCase(), command);
48
+ }
49
+ return [...unique.values()].sort((left, right) =>
50
+ left.slash.localeCompare(right.slash),
51
+ );
52
+ }
53
+
54
+ export class PrivateClawProvider {
55
+ private readonly relayClient: RelayProviderClient;
56
+ private readonly sessions = new Map<string, ProviderSessionState>();
57
+
58
+ constructor(private readonly options: PrivateClawProviderOptions) {
59
+ this.relayClient = new RelayProviderClient({
60
+ providerWsUrl: options.providerWsUrl,
61
+ onFrame: async (sessionId, envelope) => {
62
+ await this.handleRelayFrame(sessionId, envelope);
63
+ },
64
+ onSessionClosed: async (sessionId, reason) => {
65
+ this.sessions.delete(sessionId);
66
+ this.options.onLog?.(`Session ${sessionId} closed by relay: ${reason}`);
67
+ },
68
+ onError: (message) => {
69
+ this.options.onLog?.(`[relay] ${message}`);
70
+ },
71
+ });
72
+ }
73
+
74
+ async connect(): Promise<void> {
75
+ await this.relayClient.connect();
76
+ }
77
+
78
+ async dispose(): Promise<void> {
79
+ const activeSessionIds = [...this.sessions.keys()];
80
+ for (const sessionId of activeSessionIds) {
81
+ try {
82
+ await this.relayClient.closeSession(sessionId, "provider_shutdown");
83
+ } catch (error) {
84
+ this.options.onLog?.(
85
+ `[provider] failed to close session ${sessionId} during shutdown: ${error instanceof Error ? error.message : String(error)}`,
86
+ );
87
+ }
88
+ }
89
+ this.sessions.clear();
90
+ await this.relayClient.dispose();
91
+ }
92
+
93
+ listActiveSessions(): PrivateClawInvite[] {
94
+ return [...this.sessions.values()].map((session) => session.invite);
95
+ }
96
+
97
+ private buildSessionAppUrl(sessionId: string): string {
98
+ const url = new URL(this.options.appWsUrl);
99
+ url.searchParams.set("sessionId", sessionId);
100
+ return url.toString();
101
+ }
102
+
103
+ private requireSession(sessionId: string): ProviderSessionState {
104
+ const session = this.sessions.get(sessionId);
105
+ if (!session) {
106
+ throw new Error(`Unknown PrivateClaw session: ${sessionId}`);
107
+ }
108
+ return session;
109
+ }
110
+
111
+ private async sendPayloadWithSessionKey(
112
+ sessionId: string,
113
+ sessionKey: string,
114
+ payload: Parameters<typeof encryptPayload>[0]["payload"],
115
+ ): Promise<void> {
116
+ await this.relayClient.sendFrame(
117
+ sessionId,
118
+ encryptPayload({
119
+ sessionId,
120
+ sessionKey,
121
+ payload,
122
+ }),
123
+ );
124
+ }
125
+
126
+ private async sendPayload(
127
+ sessionId: string,
128
+ payload: Parameters<typeof encryptPayload>[0]["payload"],
129
+ ): Promise<void> {
130
+ const session = this.requireSession(sessionId);
131
+ await this.sendPayloadWithSessionKey(
132
+ sessionId,
133
+ session.invite.sessionKey,
134
+ payload,
135
+ );
136
+ }
137
+
138
+ async sendAssistantMessage(
139
+ sessionId: string,
140
+ params: {
141
+ text: string;
142
+ replyTo?: string;
143
+ attachments?: PrivateClawAttachment[];
144
+ },
145
+ ): Promise<void> {
146
+ const sentAt = nowIso();
147
+ const session = this.requireSession(sessionId);
148
+ session.history.push({
149
+ role: "assistant",
150
+ text: params.text,
151
+ sentAt,
152
+ ...(params.attachments ? { attachments: params.attachments } : {}),
153
+ });
154
+ await this.sendPayload(sessionId, {
155
+ kind: "assistant_message",
156
+ text: params.text,
157
+ sentAt,
158
+ ...(params.replyTo ? { replyTo: params.replyTo } : {}),
159
+ ...(params.attachments ? { attachments: params.attachments } : {}),
160
+ });
161
+ }
162
+
163
+ async sendSystemMessage(
164
+ sessionId: string,
165
+ message: string,
166
+ severity: "info" | "error" = "info",
167
+ replyTo?: string,
168
+ ): Promise<void> {
169
+ const sentAt = nowIso();
170
+ const session = this.requireSession(sessionId);
171
+ session.history.push({ role: "system", text: message, sentAt });
172
+ await this.sendPayload(sessionId, {
173
+ kind: "system_message",
174
+ message,
175
+ severity,
176
+ sentAt,
177
+ ...(replyTo ? { replyTo } : {}),
178
+ });
179
+ }
180
+
181
+ private async sendWelcomeMessage(sessionId: string): Promise<void> {
182
+ 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.";
186
+ await this.sendPayload(sessionId, {
187
+ kind: "server_welcome",
188
+ message,
189
+ sentAt,
190
+ });
191
+ }
192
+
193
+ private async listAvailableCommands(): Promise<PrivateClawSlashCommand[]> {
194
+ const discovered = (await this.options.commandsProvider?.()) ?? [];
195
+ return dedupeCommands([
196
+ ...discovered,
197
+ {
198
+ slash: "/renew-session",
199
+ description:
200
+ "Rotate the current PrivateClaw session key and extend this session by 8 hours.",
201
+ acceptsArgs: false,
202
+ source: "privateclaw",
203
+ },
204
+ ]);
205
+ }
206
+
207
+ private async sendCapabilities(sessionId: string): Promise<void> {
208
+ const session = this.requireSession(sessionId);
209
+ await this.sendPayload(sessionId, {
210
+ kind: "provider_capabilities",
211
+ sentAt: nowIso(),
212
+ expiresAt: session.invite.expiresAt,
213
+ commands: await this.listAvailableCommands(),
214
+ ...(session.invite.providerLabel
215
+ ? { providerLabel: session.invite.providerLabel }
216
+ : {}),
217
+ });
218
+ }
219
+
220
+ private async renewSession(sessionId: string, replyTo?: string): Promise<void> {
221
+ const session = this.requireSession(sessionId);
222
+ if (session.pendingRenewal) {
223
+ await this.sendSystemMessage(
224
+ sessionId,
225
+ "A session renewal is already in progress. Wait for the reconnect handshake to finish and try again.",
226
+ "error",
227
+ replyTo,
228
+ );
229
+ return;
230
+ }
231
+
232
+ const { expiresAt } = await this.relayClient.renewSession(
233
+ sessionId,
234
+ RENEW_SESSION_TTL_MS,
235
+ );
236
+ const sentAt = nowIso();
237
+ const previousSessionKey = session.invite.sessionKey;
238
+ const nextSessionKey = generateSessionKey();
239
+
240
+ await this.sendPayloadWithSessionKey(sessionId, previousSessionKey, {
241
+ kind: "session_renewed",
242
+ message: "Session renewed.",
243
+ newSessionKey: nextSessionKey,
244
+ expiresAt,
245
+ sentAt,
246
+ ...(replyTo ? { replyTo } : {}),
247
+ });
248
+
249
+ session.invite = {
250
+ ...session.invite,
251
+ sessionKey: nextSessionKey,
252
+ expiresAt,
253
+ };
254
+ session.pendingRenewal = { expiresAt, sentAt };
255
+ session.state = "awaiting_hello";
256
+ session.history.push({
257
+ role: "system",
258
+ text: `PrivateClaw session renewal initiated until ${expiresAt}`,
259
+ sentAt,
260
+ });
261
+ }
262
+
263
+ private async handleRelayFrame(
264
+ sessionId: string,
265
+ envelope: Parameters<typeof decryptPayload>[0]["envelope"],
266
+ ): Promise<void> {
267
+ const session = this.requireSession(sessionId);
268
+ const payload = decryptPayload({
269
+ sessionId,
270
+ sessionKey: session.invite.sessionKey,
271
+ envelope,
272
+ });
273
+
274
+ switch (payload.kind) {
275
+ case "client_hello": {
276
+ const wasAwaitingHello = session.state !== "active";
277
+ const wasRenewing = Boolean(session.pendingRenewal);
278
+ session.state = "active";
279
+ if (wasRenewing) {
280
+ session.history.push({
281
+ role: "system",
282
+ text: `${payload.deviceLabel ?? "PrivateClaw app"} completed session key rotation`,
283
+ sentAt: payload.sentAt,
284
+ });
285
+ delete session.pendingRenewal;
286
+ } else if (wasAwaitingHello) {
287
+ session.history.push({
288
+ role: "system",
289
+ text: `${payload.deviceLabel ?? "PrivateClaw app"} connected`,
290
+ sentAt: payload.sentAt,
291
+ });
292
+ await this.sendWelcomeMessage(sessionId);
293
+ }
294
+ await this.sendCapabilities(sessionId);
295
+ return;
296
+ }
297
+ case "user_message": {
298
+ if (session.state !== "active") {
299
+ await this.sendSystemMessage(
300
+ sessionId,
301
+ "The PrivateClaw handshake is not complete yet. Scan the QR code again or retry the connection.",
302
+ "error",
303
+ payload.clientMessageId,
304
+ );
305
+ return;
306
+ }
307
+
308
+ session.history.push({
309
+ role: "user",
310
+ text: payload.text,
311
+ sentAt: payload.sentAt,
312
+ ...(payload.attachments ? { attachments: payload.attachments } : {}),
313
+ });
314
+ this.options.onLog?.(
315
+ `[provider] user_message session=${sessionId} textChars=${payload.text.length} attachments=${payload.attachments?.length ?? 0}`,
316
+ );
317
+
318
+ const normalizedCommand = payload.text.trim().toLowerCase();
319
+ if (normalizedCommand === "/renew-session") {
320
+ if ((payload.attachments?.length ?? 0) > 0) {
321
+ await this.sendSystemMessage(
322
+ sessionId,
323
+ "The /renew-session command does not accept attachments.",
324
+ "error",
325
+ payload.clientMessageId,
326
+ );
327
+ return;
328
+ }
329
+ try {
330
+ await this.renewSession(sessionId, payload.clientMessageId);
331
+ } catch (error) {
332
+ await this.sendSystemMessage(
333
+ sessionId,
334
+ `Failed to renew the PrivateClaw session: ${error instanceof Error ? error.message : String(error)}`,
335
+ "error",
336
+ payload.clientMessageId,
337
+ );
338
+ }
339
+ return;
340
+ }
341
+ if (normalizedCommand.startsWith("/renew-session ")) {
342
+ await this.sendSystemMessage(
343
+ sessionId,
344
+ "The /renew-session command does not accept arguments.",
345
+ "error",
346
+ payload.clientMessageId,
347
+ );
348
+ return;
349
+ }
350
+
351
+ try {
352
+ const bridgeResponse = await this.options.bridge.handleUserMessage({
353
+ sessionId,
354
+ invite: session.invite,
355
+ message: payload.text,
356
+ ...(payload.attachments ? { attachments: payload.attachments } : {}),
357
+ history: [...session.history],
358
+ });
359
+
360
+ for (const message of normalizeBridgeMessages(bridgeResponse)) {
361
+ await this.sendAssistantMessage(sessionId, {
362
+ text: message.text,
363
+ replyTo: payload.clientMessageId,
364
+ ...(message.attachments ? { attachments: message.attachments } : {}),
365
+ });
366
+ }
367
+ } catch (error) {
368
+ await this.sendSystemMessage(
369
+ sessionId,
370
+ `OpenClaw bridge error: ${error instanceof Error ? error.message : String(error)}`,
371
+ "error",
372
+ payload.clientMessageId,
373
+ );
374
+ }
375
+ return;
376
+ }
377
+ case "session_close":
378
+ this.sessions.delete(sessionId);
379
+ await this.relayClient.closeSession(sessionId, payload.reason);
380
+ return;
381
+ case "assistant_message":
382
+ case "server_welcome":
383
+ case "provider_capabilities":
384
+ case "session_renewed":
385
+ case "system_message":
386
+ return;
387
+ default:
388
+ await this.sendSystemMessage(
389
+ sessionId,
390
+ `Unsupported PrivateClaw payload: ${(payload as { kind?: string }).kind ?? "unknown"}`,
391
+ "error",
392
+ );
393
+ }
394
+ }
395
+
396
+ async createInviteBundle(params?: { ttlMs?: number; label?: string }): Promise<PrivateClawInviteBundle> {
397
+ await this.connect();
398
+
399
+ const { sessionId, expiresAt } = await this.relayClient.createSession(
400
+ params?.ttlMs ?? this.options.defaultTtlMs,
401
+ params?.label,
402
+ );
403
+
404
+ const invite: PrivateClawInvite = {
405
+ version: 1,
406
+ sessionId,
407
+ sessionKey: generateSessionKey(),
408
+ appWsUrl: this.buildSessionAppUrl(sessionId),
409
+ expiresAt,
410
+ ...(this.options.providerLabel ? { providerLabel: this.options.providerLabel } : {}),
411
+ };
412
+
413
+ this.sessions.set(sessionId, {
414
+ invite,
415
+ history: [],
416
+ state: "awaiting_hello",
417
+ });
418
+
419
+ const inviteUri = encodeInviteToUri(invite);
420
+ const qrSvg = await QRCode.toString(inviteUri, {
421
+ type: "svg",
422
+ errorCorrectionLevel: "M",
423
+ margin: 1,
424
+ });
425
+ const qrTerminal = await QRCode.toString(inviteUri, {
426
+ type: "terminal",
427
+ small: true,
428
+ });
429
+
430
+ return {
431
+ invite,
432
+ inviteUri,
433
+ qrSvg,
434
+ qrTerminal,
435
+ announcementText:
436
+ `PrivateClaw session ${sessionId} is ready until ${expiresAt}. ` +
437
+ "Scan the QR code or paste the invite link into the PrivateClaw app to connect.",
438
+ };
439
+ }
440
+
441
+ decodeInvite(uri: string): PrivateClawInvite {
442
+ return decodeInviteString(uri);
443
+ }
444
+ }
@@ -0,0 +1,17 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { resolveRelayEndpoints } from "./relay-endpoints.js";
4
+
5
+ test("resolveRelayEndpoints normalizes secure relay base URLs", () => {
6
+ assert.deepEqual(resolveRelayEndpoints("https://relay.example.com/base?ignored=1"), {
7
+ providerWsUrl: "wss://relay.example.com/ws/provider",
8
+ appWsUrl: "wss://relay.example.com/ws/app",
9
+ });
10
+ });
11
+
12
+ test("resolveRelayEndpoints accepts bare host:port values", () => {
13
+ assert.deepEqual(resolveRelayEndpoints("127.0.0.1:8787"), {
14
+ providerWsUrl: "ws://127.0.0.1:8787/ws/provider",
15
+ appWsUrl: "ws://127.0.0.1:8787/ws/app",
16
+ });
17
+ });
@@ -0,0 +1,25 @@
1
+ export interface PrivateClawRelayEndpoints {
2
+ providerWsUrl: string;
3
+ appWsUrl: string;
4
+ }
5
+
6
+ export function resolveRelaySocketUrl(base: string, path: string): string {
7
+ const rawUrl = new URL(base.includes("://") ? base : `ws://${base}`);
8
+ if (rawUrl.protocol === "http:") {
9
+ rawUrl.protocol = "ws:";
10
+ }
11
+ if (rawUrl.protocol === "https:") {
12
+ rawUrl.protocol = "wss:";
13
+ }
14
+ rawUrl.pathname = path;
15
+ rawUrl.search = "";
16
+ rawUrl.hash = "";
17
+ return rawUrl.toString();
18
+ }
19
+
20
+ export function resolveRelayEndpoints(baseUrl: string): PrivateClawRelayEndpoints {
21
+ return {
22
+ providerWsUrl: resolveRelaySocketUrl(baseUrl, "/ws/provider"),
23
+ appWsUrl: resolveRelaySocketUrl(baseUrl, "/ws/app"),
24
+ };
25
+ }