@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,439 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import QRCode from "qrcode";
5
+ import { EchoBridge } from "./bridges/echo-bridge.js";
6
+ import {
7
+ OpenClawAgentBridge,
8
+ type OpenClawAgentBridgeOptions,
9
+ } from "./bridges/openclaw-agent-bridge.js";
10
+ import { loadAvailableOpenClawCommands } from "./openclaw-command-discovery.js";
11
+ import { WebhookBridge } from "./bridges/webhook-bridge.js";
12
+ import {
13
+ type OpenClawExtensionPluginCompat,
14
+ type OpenClawPluginApiCompat,
15
+ type OpenClawPluginCommandContextCompat,
16
+ type ReplyPayloadCompat,
17
+ privateClawConfigSchema,
18
+ } from "./compat/openclaw.js";
19
+ import { PrivateClawProvider } from "./provider.js";
20
+ import { resolveRelayEndpoints } from "./relay-endpoints.js";
21
+ import type {
22
+ PrivateClawAgentBridge,
23
+ PrivateClawInviteBundle,
24
+ PrivateClawProviderOptions,
25
+ } from "./types.js";
26
+
27
+ type PrivateClawBridgeMode = "openclaw-agent" | "webhook" | "echo";
28
+
29
+ type OpenClawThinkingLevel = NonNullable<OpenClawAgentBridgeOptions["thinking"]>;
30
+
31
+ export interface PrivateClawPluginConfig {
32
+ relayBaseUrl?: string;
33
+ sessionTtlMs?: number;
34
+ welcomeMessage?: string;
35
+ providerLabel?: string;
36
+ webhookUrl?: string;
37
+ webhookToken?: string;
38
+ bridgeMode?: PrivateClawBridgeMode;
39
+ echoPrefix?: string;
40
+ openclawAgentExecutable?: string;
41
+ openclawAgentId?: string;
42
+ openclawAgentChannel?: string;
43
+ openclawAgentLocal?: boolean;
44
+ openclawAgentThinking?: OpenClawThinkingLevel;
45
+ openclawAgentTimeoutSeconds?: number;
46
+ }
47
+
48
+ export interface PrivateClawCommandResult
49
+ extends Pick<PrivateClawInviteBundle, "announcementText" | "inviteUri" | "qrSvg"> {
50
+ qrPngDataUrl?: string;
51
+ }
52
+
53
+ interface ResolvedPrivateClawPluginConfig {
54
+ relayBaseUrl: string;
55
+ bridgeMode: PrivateClawBridgeMode;
56
+ providerLabel: string;
57
+ sessionTtlMs?: number;
58
+ welcomeMessage?: string;
59
+ webhookUrl?: string;
60
+ webhookToken?: string;
61
+ echoPrefix?: string;
62
+ openclawAgentExecutable?: string;
63
+ openclawAgentId?: string;
64
+ openclawAgentChannel?: string;
65
+ openclawAgentLocal?: boolean;
66
+ openclawAgentThinking?: OpenClawThinkingLevel;
67
+ openclawAgentTimeoutSeconds?: number;
68
+ }
69
+
70
+ const DEFAULT_RELAY_BASE_URL = "ws://127.0.0.1:8787";
71
+ const DEFAULT_PROVIDER_LABEL = "PrivateClaw";
72
+ const DEFAULT_BRIDGE_MODE: PrivateClawBridgeMode = "openclaw-agent";
73
+ const ALLOWED_THINKING_LEVELS = new Set<OpenClawThinkingLevel>([
74
+ "off",
75
+ "minimal",
76
+ "low",
77
+ "medium",
78
+ "high",
79
+ ]);
80
+
81
+ function readString(value: unknown): string | undefined {
82
+ if (typeof value !== "string") {
83
+ return undefined;
84
+ }
85
+
86
+ const trimmed = value.trim();
87
+ return trimmed === "" ? undefined : trimmed;
88
+ }
89
+
90
+ function readNumber(value: unknown): number | undefined {
91
+ if (typeof value === "number" && Number.isFinite(value)) {
92
+ return value;
93
+ }
94
+
95
+ if (typeof value !== "string") {
96
+ return undefined;
97
+ }
98
+
99
+ const trimmed = value.trim();
100
+ if (trimmed === "") {
101
+ return undefined;
102
+ }
103
+
104
+ const parsed = Number(trimmed);
105
+ return Number.isFinite(parsed) ? parsed : undefined;
106
+ }
107
+
108
+ function readBoolean(value: unknown): boolean | undefined {
109
+ if (typeof value === "boolean") {
110
+ return value;
111
+ }
112
+
113
+ if (typeof value !== "string") {
114
+ return undefined;
115
+ }
116
+
117
+ const normalized = value.trim().toLowerCase();
118
+ if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") {
119
+ return true;
120
+ }
121
+ if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "off") {
122
+ return false;
123
+ }
124
+
125
+ return undefined;
126
+ }
127
+
128
+ function readBridgeMode(value: unknown): PrivateClawBridgeMode | undefined {
129
+ const normalized = readString(value)?.toLowerCase();
130
+ if (
131
+ normalized === "openclaw-agent" ||
132
+ normalized === "webhook" ||
133
+ normalized === "echo"
134
+ ) {
135
+ return normalized;
136
+ }
137
+
138
+ return undefined;
139
+ }
140
+
141
+ function readThinkingLevel(value: unknown): OpenClawThinkingLevel | undefined {
142
+ const normalized = readString(value)?.toLowerCase();
143
+ if (!normalized) {
144
+ return undefined;
145
+ }
146
+
147
+ return ALLOWED_THINKING_LEVELS.has(normalized as OpenClawThinkingLevel)
148
+ ? (normalized as OpenClawThinkingLevel)
149
+ : undefined;
150
+ }
151
+
152
+ function resolvePluginConfig(
153
+ pluginConfig?: Record<string, unknown>,
154
+ ): ResolvedPrivateClawPluginConfig {
155
+ const relayBaseUrl =
156
+ readString(pluginConfig?.relayBaseUrl) ??
157
+ readString(process.env.PRIVATECLAW_RELAY_BASE_URL) ??
158
+ DEFAULT_RELAY_BASE_URL;
159
+
160
+ const sessionTtlMs =
161
+ readNumber(pluginConfig?.sessionTtlMs) ??
162
+ readNumber(process.env.PRIVATECLAW_SESSION_TTL_MS);
163
+ const welcomeMessage =
164
+ readString(pluginConfig?.welcomeMessage) ??
165
+ readString(process.env.PRIVATECLAW_WELCOME_MESSAGE);
166
+ const webhookUrl =
167
+ readString(pluginConfig?.webhookUrl) ??
168
+ readString(process.env.PRIVATECLAW_WEBHOOK_URL);
169
+ const webhookToken =
170
+ readString(pluginConfig?.webhookToken) ??
171
+ readString(process.env.PRIVATECLAW_WEBHOOK_TOKEN);
172
+ const echoPrefix =
173
+ readString(pluginConfig?.echoPrefix) ??
174
+ readString(process.env.PRIVATECLAW_ECHO_PREFIX);
175
+ const openclawAgentExecutable =
176
+ readString(pluginConfig?.openclawAgentExecutable) ??
177
+ readString(process.env.PRIVATECLAW_OPENCLAW_AGENT_BIN);
178
+ const openclawAgentId =
179
+ readString(pluginConfig?.openclawAgentId) ??
180
+ readString(process.env.PRIVATECLAW_OPENCLAW_AGENT_ID);
181
+ const openclawAgentChannel =
182
+ readString(pluginConfig?.openclawAgentChannel) ??
183
+ readString(process.env.PRIVATECLAW_OPENCLAW_AGENT_CHANNEL);
184
+ const openclawAgentLocal =
185
+ readBoolean(pluginConfig?.openclawAgentLocal) ??
186
+ readBoolean(process.env.PRIVATECLAW_OPENCLAW_AGENT_LOCAL);
187
+ const openclawAgentThinking =
188
+ readThinkingLevel(pluginConfig?.openclawAgentThinking) ??
189
+ readThinkingLevel(process.env.PRIVATECLAW_OPENCLAW_AGENT_THINKING);
190
+ const openclawAgentTimeoutSeconds =
191
+ readNumber(pluginConfig?.openclawAgentTimeoutSeconds) ??
192
+ readNumber(process.env.PRIVATECLAW_OPENCLAW_AGENT_TIMEOUT_SECONDS);
193
+
194
+ const envBridgeMode =
195
+ readBridgeMode(process.env.PRIVATECLAW_BRIDGE_MODE) ??
196
+ (readBoolean(process.env.PRIVATECLAW_OPENCLAW_AGENT_BRIDGE) === false ? "echo" : undefined);
197
+
198
+ const bridgeMode =
199
+ readBridgeMode(pluginConfig?.bridgeMode) ??
200
+ envBridgeMode ??
201
+ (webhookUrl ? "webhook" : DEFAULT_BRIDGE_MODE);
202
+
203
+ return {
204
+ relayBaseUrl,
205
+ bridgeMode,
206
+ providerLabel:
207
+ readString(pluginConfig?.providerLabel) ??
208
+ readString(process.env.PRIVATECLAW_PROVIDER_LABEL) ??
209
+ DEFAULT_PROVIDER_LABEL,
210
+ ...(typeof sessionTtlMs === "number" ? { sessionTtlMs } : {}),
211
+ ...(welcomeMessage ? { welcomeMessage } : {}),
212
+ ...(webhookUrl ? { webhookUrl } : {}),
213
+ ...(webhookToken ? { webhookToken } : {}),
214
+ ...(echoPrefix ? { echoPrefix } : {}),
215
+ ...(openclawAgentExecutable ? { openclawAgentExecutable } : {}),
216
+ ...(openclawAgentId ? { openclawAgentId } : {}),
217
+ ...(openclawAgentChannel ? { openclawAgentChannel } : {}),
218
+ ...(typeof openclawAgentLocal === "boolean" ? { openclawAgentLocal } : {}),
219
+ ...(openclawAgentThinking ? { openclawAgentThinking } : {}),
220
+ ...(typeof openclawAgentTimeoutSeconds === "number"
221
+ ? { openclawAgentTimeoutSeconds }
222
+ : {}),
223
+ };
224
+ }
225
+
226
+ function buildBridge(config: ResolvedPrivateClawPluginConfig): PrivateClawAgentBridge {
227
+ if (config.bridgeMode === "webhook") {
228
+ if (!config.webhookUrl) {
229
+ throw new Error(
230
+ "PrivateClaw bridgeMode=webhook requires webhookUrl or PRIVATECLAW_WEBHOOK_URL.",
231
+ );
232
+ }
233
+
234
+ return new WebhookBridge({
235
+ endpoint: config.webhookUrl,
236
+ ...(config.webhookToken ? { token: config.webhookToken } : {}),
237
+ });
238
+ }
239
+
240
+ if (config.bridgeMode === "echo") {
241
+ return new EchoBridge(config.echoPrefix ?? "PrivateClaw demo");
242
+ }
243
+
244
+ return new OpenClawAgentBridge({
245
+ ...(config.openclawAgentExecutable
246
+ ? { executable: config.openclawAgentExecutable }
247
+ : {}),
248
+ ...(config.openclawAgentId ? { agentId: config.openclawAgentId } : {}),
249
+ ...(config.openclawAgentChannel ? { channel: config.openclawAgentChannel } : {}),
250
+ ...(typeof config.openclawAgentLocal === "boolean"
251
+ ? { local: config.openclawAgentLocal }
252
+ : {}),
253
+ ...(config.openclawAgentThinking
254
+ ? { thinking: config.openclawAgentThinking }
255
+ : {}),
256
+ ...(typeof config.openclawAgentTimeoutSeconds === "number"
257
+ ? { timeoutSeconds: config.openclawAgentTimeoutSeconds }
258
+ : {}),
259
+ });
260
+ }
261
+
262
+ function buildProviderOptions(
263
+ pluginConfig: ResolvedPrivateClawPluginConfig,
264
+ api: Pick<OpenClawPluginApiCompat, "logger">,
265
+ ): { options: PrivateClawProviderOptions; defaultTtlMs?: number } {
266
+ const relay = resolveRelayEndpoints(pluginConfig.relayBaseUrl);
267
+ return {
268
+ options: {
269
+ providerWsUrl: relay.providerWsUrl,
270
+ appWsUrl: relay.appWsUrl,
271
+ bridge: buildBridge(pluginConfig),
272
+ providerLabel: pluginConfig.providerLabel,
273
+ commandsProvider: async () => {
274
+ try {
275
+ return await loadAvailableOpenClawCommands();
276
+ } catch (error) {
277
+ api.logger.warn(
278
+ `[privateclaw] Failed to discover OpenClaw commands: ${formatCommandError(error)}`,
279
+ );
280
+ return [];
281
+ }
282
+ },
283
+ ...(pluginConfig.welcomeMessage ? { welcomeMessage: pluginConfig.welcomeMessage } : {}),
284
+ onLog: (message) => api.logger.info(`[privateclaw] ${message}`),
285
+ },
286
+ ...(typeof pluginConfig.sessionTtlMs === "number"
287
+ ? { defaultTtlMs: pluginConfig.sessionTtlMs }
288
+ : {}),
289
+ };
290
+ }
291
+
292
+ class PrivateClawPluginRuntime {
293
+ private provider: PrivateClawProvider | undefined;
294
+ private stateDir: string | undefined;
295
+
296
+ constructor(
297
+ private readonly providerOptions: PrivateClawProviderOptions,
298
+ private readonly defaultTtlMs?: number,
299
+ ) {}
300
+
301
+ setStateDir(stateDir: string): void {
302
+ this.stateDir = stateDir;
303
+ }
304
+
305
+ private getMediaDir(): string {
306
+ return path.join(
307
+ this.stateDir ?? process.env.OPENCLAW_STATE_DIR ?? path.join(os.homedir(), ".openclaw"),
308
+ "media",
309
+ "privateclaw",
310
+ );
311
+ }
312
+
313
+ private getProvider(): PrivateClawProvider {
314
+ if (!this.provider) {
315
+ this.provider = new PrivateClawProvider(this.providerOptions);
316
+ }
317
+
318
+ return this.provider;
319
+ }
320
+
321
+ async createInviteBundle(): Promise<PrivateClawInviteBundle> {
322
+ return this.getProvider().createInviteBundle(
323
+ typeof this.defaultTtlMs === "number" ? { ttlMs: this.defaultTtlMs } : undefined,
324
+ );
325
+ }
326
+
327
+ async buildCommandReply(bundle: PrivateClawInviteBundle): Promise<ReplyPayloadCompat> {
328
+ const text = `${bundle.announcementText}\n\nOpen invite:\n${bundle.inviteUri}`;
329
+ const qrPngPath = await writeInviteQrPng(bundle, this.getMediaDir());
330
+ return {
331
+ text,
332
+ mediaUrl: qrPngPath,
333
+ };
334
+ }
335
+
336
+ async dispose(): Promise<void> {
337
+ if (!this.provider) {
338
+ return;
339
+ }
340
+
341
+ await this.provider.dispose();
342
+ this.provider = undefined;
343
+ }
344
+ }
345
+
346
+ async function writeInviteQrPng(
347
+ bundle: PrivateClawInviteBundle,
348
+ mediaDir: string,
349
+ ): Promise<string> {
350
+ const pngBuffer = await QRCode.toBuffer(bundle.inviteUri, {
351
+ type: "png",
352
+ errorCorrectionLevel: "M",
353
+ margin: 1,
354
+ width: 512,
355
+ });
356
+ await mkdir(mediaDir, { recursive: true });
357
+ const qrPath = path.join(mediaDir, `privateclaw-${bundle.invite.sessionId}.png`);
358
+ await writeFile(qrPath, pngBuffer);
359
+ return qrPath;
360
+ }
361
+
362
+ function formatCommandError(error: unknown): string {
363
+ return error instanceof Error ? error.message : String(error);
364
+ }
365
+
366
+ function createPluginDefinition(
367
+ runtimeFactory: (api: OpenClawPluginApiCompat) => PrivateClawPluginRuntime,
368
+ ): OpenClawExtensionPluginCompat {
369
+ return {
370
+ id: "privateclaw",
371
+ name: "PrivateClaw",
372
+ description: "Ephemeral end-to-end encrypted private session plugin for OpenClaw.",
373
+ configSchema: privateClawConfigSchema,
374
+ register(api: OpenClawPluginApiCompat) {
375
+ const runtime = runtimeFactory(api);
376
+
377
+ api.registerService?.({
378
+ id: "privateclaw-provider",
379
+ start: ({ stateDir }) => {
380
+ runtime.setStateDir(stateDir);
381
+ },
382
+ stop: async () => {
383
+ await runtime.dispose();
384
+ },
385
+ });
386
+
387
+ api.registerCommand({
388
+ name: "privateclaw",
389
+ description: "Create a one-time encrypted PrivateClaw session QR code.",
390
+ acceptsArgs: false,
391
+ requireAuth: true,
392
+ handler: async (ctx: OpenClawPluginCommandContextCompat) => {
393
+ try {
394
+ api.logger.info(
395
+ `[privateclaw] /privateclaw invoked via ${ctx.channel}${ctx.senderId ? ` by ${ctx.senderId}` : ""}`,
396
+ );
397
+ const bundle = await runtime.createInviteBundle();
398
+ api.logger.info(
399
+ `[privateclaw] invite created for session ${bundle.invite.sessionId} on ${ctx.channel}`,
400
+ );
401
+ const reply = await runtime.buildCommandReply(bundle);
402
+ api.logger.info(
403
+ `[privateclaw] QR image prepared for session ${bundle.invite.sessionId}`,
404
+ );
405
+ return reply;
406
+ } catch (error) {
407
+ api.logger.error(
408
+ `[privateclaw] Failed to create invite bundle: ${formatCommandError(error)}`,
409
+ );
410
+ return {
411
+ text: `Failed to create a PrivateClaw session: ${formatCommandError(error)}`,
412
+ isError: true,
413
+ };
414
+ }
415
+ },
416
+ });
417
+ },
418
+ };
419
+ }
420
+
421
+ export function createOpenClawCompatiblePlugin(
422
+ options: PrivateClawProviderOptions & { defaultTtlMs?: number },
423
+ ): OpenClawExtensionPluginCompat {
424
+ return createPluginDefinition(
425
+ () => new PrivateClawPluginRuntime(options, options.defaultTtlMs),
426
+ );
427
+ }
428
+
429
+ export function createPrivateClawPlugin(): OpenClawExtensionPluginCompat {
430
+ return createPluginDefinition((api) => {
431
+ const pluginConfig = resolvePluginConfig(api.pluginConfig);
432
+ const resolved = buildProviderOptions(pluginConfig, api);
433
+ return new PrivateClawPluginRuntime(resolved.options, resolved.defaultTtlMs);
434
+ });
435
+ }
436
+
437
+ const defaultPlugin = createPrivateClawPlugin();
438
+
439
+ export default defaultPlugin;