@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,490 @@
1
+ import type { PrivateClawAttachment } from "@privateclaw/protocol";
2
+ import { execFile } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+ import fs from "node:fs/promises";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { unzipSync } from "fflate";
8
+ import type { BridgeResponse, PrivateClawAgentBridge } from "../types.js";
9
+
10
+ type OpenClawThinkingLevel = "off" | "minimal" | "low" | "medium" | "high";
11
+
12
+ interface OpenClawAgentBridgeExecOptions {
13
+ maxBuffer: number;
14
+ }
15
+
16
+ type OpenClawAgentExecFile = (
17
+ file: string,
18
+ args: string[],
19
+ options: OpenClawAgentBridgeExecOptions,
20
+ callback: (error: Error | null, stdout: string, stderr: string) => void,
21
+ ) => void;
22
+
23
+ interface OpenClawAgentPayload {
24
+ text?: string | null;
25
+ }
26
+
27
+ interface OpenClawAgentJsonResult {
28
+ status?: string;
29
+ summary?: string;
30
+ result?: {
31
+ payloads?: OpenClawAgentPayload[];
32
+ };
33
+ }
34
+
35
+ interface StagedAttachment {
36
+ readonly name: string;
37
+ readonly effectiveMimeType: string;
38
+ readonly kind: "image" | "pdf" | "docx" | "text" | "file";
39
+ readonly absolutePath: string;
40
+ readonly workspacePath: string;
41
+ readonly sizeBytes: number;
42
+ readonly extractedTextAbsolutePath?: string;
43
+ readonly extractedTextWorkspacePath?: string;
44
+ readonly instruction: string;
45
+ }
46
+
47
+ export interface OpenClawAgentBridgeOptions {
48
+ executable?: string;
49
+ agentId?: string;
50
+ channel?: string;
51
+ local?: boolean;
52
+ thinking?: OpenClawThinkingLevel;
53
+ timeoutSeconds?: number;
54
+ workspaceDir?: string;
55
+ execFileImpl?: OpenClawAgentExecFile;
56
+ }
57
+
58
+ const DEFAULT_MAX_BUFFER = 10 * 1024 * 1024;
59
+ const DEFAULT_STATE_DIR = process.env.OPENCLAW_STATE_DIR ?? path.join(os.homedir(), ".openclaw");
60
+ const DEFAULT_WORKSPACE_DIR = path.join(DEFAULT_STATE_DIR, "workspace");
61
+ const GENERIC_BINARY_MIME = "application/octet-stream";
62
+ const XML_ENTITY_PATTERN = /&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);/giu;
63
+ const DOCX_MIME_TYPES = new Set<string>([
64
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
65
+ ]);
66
+ const TEXT_LIKE_MIME_TYPES = new Set<string>([
67
+ "application/json",
68
+ "application/ld+json",
69
+ "application/xml",
70
+ "application/yaml",
71
+ "application/x-yaml",
72
+ "application/javascript",
73
+ "application/x-javascript",
74
+ "application/typescript",
75
+ "application/x-typescript",
76
+ "image/svg+xml",
77
+ ]);
78
+
79
+ export function parseOpenClawAgentOutput(stdout: string): BridgeResponse {
80
+ const parsed = JSON.parse(stdout) as OpenClawAgentJsonResult;
81
+ return parseOpenClawAgentResult(parsed);
82
+ }
83
+
84
+ function parseOpenClawAgentResult(parsed: OpenClawAgentJsonResult): BridgeResponse {
85
+ if (parsed.status !== "ok") {
86
+ throw new Error(
87
+ `OpenClaw agent bridge returned status ${parsed.status ?? "unknown"}${parsed.summary ? ` (${parsed.summary})` : ""}.`,
88
+ );
89
+ }
90
+
91
+ const messages =
92
+ parsed.result?.payloads
93
+ ?.flatMap((payload) =>
94
+ typeof payload.text === "string" && payload.text.trim() !== ""
95
+ ? [{ text: payload.text }]
96
+ : [],
97
+ ) ?? [];
98
+
99
+ if (messages.length === 0) {
100
+ throw new Error("OpenClaw agent bridge returned no text payloads.");
101
+ }
102
+
103
+ if (messages.length === 1) {
104
+ const [message] = messages;
105
+ if (!message) {
106
+ throw new Error("OpenClaw agent bridge returned no text payloads.");
107
+ }
108
+ return message.text;
109
+ }
110
+
111
+ return { messages };
112
+ }
113
+
114
+ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
115
+ private readonly executable: string;
116
+ private readonly execFileImpl: OpenClawAgentExecFile;
117
+ private readonly workspaceDir: string;
118
+
119
+ constructor(private readonly options: OpenClawAgentBridgeOptions = {}) {
120
+ this.executable = options.executable ?? "openclaw";
121
+ this.execFileImpl = options.execFileImpl ?? execFile;
122
+ this.workspaceDir = options.workspaceDir ?? DEFAULT_WORKSPACE_DIR;
123
+ }
124
+
125
+ async handleUserMessage(params: {
126
+ sessionId: string;
127
+ message: string;
128
+ attachments?: ReadonlyArray<PrivateClawAttachment>;
129
+ }): Promise<BridgeResponse> {
130
+ const promptMessage = await this.buildPromptMessage(
131
+ params.sessionId,
132
+ params.message,
133
+ params.attachments,
134
+ );
135
+ const args = this.buildArgs(params.sessionId, promptMessage);
136
+ const stdout = await this.execOpenClaw(args);
137
+ return parseOpenClawAgentOutput(stdout);
138
+ }
139
+
140
+ private async buildPromptMessage(
141
+ sessionId: string,
142
+ message: string,
143
+ attachments?: ReadonlyArray<PrivateClawAttachment>,
144
+ ): Promise<string> {
145
+ const trimmed = message.trim();
146
+ const stagedAttachments = await this.stageAttachments(sessionId, attachments);
147
+
148
+ if (stagedAttachments.length === 0) {
149
+ return trimmed;
150
+ }
151
+
152
+ const lines = [
153
+ trimmed !== ""
154
+ ? trimmed
155
+ : "The user sent one or more file attachments without additional text.",
156
+ "",
157
+ "PrivateClaw staged the attachments into the OpenClaw workspace.",
158
+ "Inspect the staged files before answering, and use the exact paths below instead of guessing a workspace-root filename.",
159
+ "",
160
+ "Staged attachments:",
161
+ ];
162
+
163
+ for (const attachment of stagedAttachments) {
164
+ lines.push(`- ${attachment.name}`);
165
+ lines.push(` mimeType: ${attachment.effectiveMimeType}`);
166
+ lines.push(` kind: ${attachment.kind}`);
167
+ lines.push(` workspacePath: ${attachment.workspacePath}`);
168
+ if (attachment.extractedTextWorkspacePath) {
169
+ lines.push(` extractedTextPath: ${attachment.extractedTextWorkspacePath}`);
170
+ }
171
+ lines.push(` instruction: ${attachment.instruction}`);
172
+ }
173
+
174
+ return lines.join("\n");
175
+ }
176
+
177
+ private async stageAttachments(
178
+ sessionId: string,
179
+ attachments?: ReadonlyArray<PrivateClawAttachment>,
180
+ ): Promise<StagedAttachment[]> {
181
+ if (!attachments || attachments.length === 0) {
182
+ return [];
183
+ }
184
+
185
+ const sessionDir = path.join(this.workspaceDir, "privateclaw", sessionId);
186
+ await fs.mkdir(sessionDir, { recursive: true });
187
+
188
+ const staged: StagedAttachment[] = [];
189
+ for (const attachment of attachments) {
190
+ const dataBase64 = attachment.dataBase64?.trim();
191
+ if (!dataBase64) {
192
+ continue;
193
+ }
194
+
195
+ const effectiveMimeType = resolveAttachmentMimeType(attachment);
196
+ const uniqueFileName = `${Date.now()}-${randomUUID().slice(0, 8)}-${sanitizeFileName(attachment.name)}`;
197
+ const absolutePath = path.join(sessionDir, uniqueFileName);
198
+ const rawBytes = Buffer.from(dataBase64, "base64");
199
+ await fs.writeFile(absolutePath, rawBytes);
200
+
201
+ const workspacePath = toWorkspacePath(this.workspaceDir, absolutePath);
202
+ const kind = classifyAttachmentKind(attachment.name, effectiveMimeType);
203
+ let extractedTextAbsolutePath: string | undefined;
204
+ let extractedTextWorkspacePath: string | undefined;
205
+
206
+ if (kind === "docx") {
207
+ const extractedText = extractDocxText(rawBytes);
208
+ if (extractedText.trim() !== "") {
209
+ extractedTextAbsolutePath = `${absolutePath}.extracted.txt`;
210
+ await fs.writeFile(extractedTextAbsolutePath, extractedText, "utf8");
211
+ extractedTextWorkspacePath = toWorkspacePath(
212
+ this.workspaceDir,
213
+ extractedTextAbsolutePath,
214
+ );
215
+ }
216
+ }
217
+
218
+ staged.push({
219
+ name: attachment.name,
220
+ effectiveMimeType,
221
+ kind,
222
+ absolutePath,
223
+ workspacePath,
224
+ sizeBytes: attachment.sizeBytes,
225
+ ...(extractedTextAbsolutePath ? { extractedTextAbsolutePath } : {}),
226
+ ...(extractedTextWorkspacePath ? { extractedTextWorkspacePath } : {}),
227
+ instruction: buildAttachmentInstruction({
228
+ kind,
229
+ workspacePath,
230
+ ...(extractedTextWorkspacePath ? { extractedTextWorkspacePath } : {}),
231
+ }),
232
+ });
233
+ }
234
+
235
+ return staged;
236
+ }
237
+
238
+ private buildArgs(sessionId: string, message: string): string[] {
239
+ const args = ["agent", "--session-id", sessionId, "--message", message, "--json"];
240
+
241
+ if (this.options.agentId) {
242
+ args.push("--agent", this.options.agentId);
243
+ }
244
+ if (this.options.channel) {
245
+ args.push("--channel", this.options.channel);
246
+ }
247
+ if (this.options.local) {
248
+ args.push("--local");
249
+ }
250
+ if (this.options.thinking) {
251
+ args.push("--thinking", this.options.thinking);
252
+ }
253
+ if (this.options.timeoutSeconds) {
254
+ args.push("--timeout", String(this.options.timeoutSeconds));
255
+ }
256
+
257
+ return args;
258
+ }
259
+
260
+ private execOpenClaw(args: string[]): Promise<string> {
261
+ return new Promise((resolve, reject) => {
262
+ this.execFileImpl(
263
+ this.executable,
264
+ args,
265
+ { maxBuffer: DEFAULT_MAX_BUFFER },
266
+ (error, stdout, stderr) => {
267
+ if (error) {
268
+ const suffix = stderr.trim() !== "" ? ` ${stderr.trim()}` : "";
269
+ reject(new Error(`Failed to run OpenClaw agent bridge:${suffix || ` ${error.message}`}`));
270
+ return;
271
+ }
272
+
273
+ resolve(stdout);
274
+ },
275
+ );
276
+ });
277
+ }
278
+ }
279
+
280
+ function buildAttachmentInstruction(params: {
281
+ kind: StagedAttachment["kind"];
282
+ workspacePath: string;
283
+ extractedTextWorkspacePath?: string;
284
+ }): string {
285
+ switch (params.kind) {
286
+ case "image":
287
+ return `Use the image tool with "${params.workspacePath}" before answering.`;
288
+ case "pdf":
289
+ return `Use the pdf tool with "${params.workspacePath}" before answering.`;
290
+ case "docx":
291
+ if (params.extractedTextWorkspacePath) {
292
+ return `Read "${params.extractedTextWorkspacePath}" first because it contains extracted text from the Word document.`;
293
+ }
294
+ return `The Word document is staged at "${params.workspacePath}", but automatic text extraction was unavailable.`;
295
+ case "text":
296
+ return `Use the read tool with "${params.workspacePath}" before answering.`;
297
+ case "file":
298
+ return `The raw file is staged at "${params.workspacePath}". If you need to inspect it, use an appropriate tool on that exact path.`;
299
+ }
300
+ }
301
+
302
+ function classifyAttachmentKind(
303
+ fileName: string,
304
+ mimeType: string,
305
+ ): StagedAttachment["kind"] {
306
+ if (mimeType.startsWith("image/")) {
307
+ return "image";
308
+ }
309
+ if (mimeType === "application/pdf" || fileName.toLowerCase().endsWith(".pdf")) {
310
+ return "pdf";
311
+ }
312
+ if (DOCX_MIME_TYPES.has(mimeType) || fileName.toLowerCase().endsWith(".docx")) {
313
+ return "docx";
314
+ }
315
+ if (isTextLikeMimeType(mimeType) || isTextLikeExtension(fileName)) {
316
+ return "text";
317
+ }
318
+ return "file";
319
+ }
320
+
321
+ function resolveAttachmentMimeType(attachment: PrivateClawAttachment): string {
322
+ const explicitMimeType = attachment.mimeType.trim().toLowerCase();
323
+ if (explicitMimeType !== "" && explicitMimeType !== GENERIC_BINARY_MIME) {
324
+ return explicitMimeType;
325
+ }
326
+
327
+ return inferMimeTypeFromFileName(attachment.name) ?? (explicitMimeType || GENERIC_BINARY_MIME);
328
+ }
329
+
330
+ function inferMimeTypeFromFileName(fileName: string): string | undefined {
331
+ const extension = getFileExtension(fileName);
332
+ switch (extension) {
333
+ case "png":
334
+ return "image/png";
335
+ case "jpg":
336
+ case "jpeg":
337
+ return "image/jpeg";
338
+ case "gif":
339
+ return "image/gif";
340
+ case "webp":
341
+ return "image/webp";
342
+ case "svg":
343
+ return "image/svg+xml";
344
+ case "pdf":
345
+ return "application/pdf";
346
+ case "doc":
347
+ return "application/msword";
348
+ case "docx":
349
+ return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
350
+ case "txt":
351
+ return "text/plain";
352
+ case "md":
353
+ case "markdown":
354
+ return "text/markdown";
355
+ case "csv":
356
+ return "text/csv";
357
+ case "json":
358
+ return "application/json";
359
+ case "xml":
360
+ return "application/xml";
361
+ case "yaml":
362
+ case "yml":
363
+ return "application/yaml";
364
+ case "html":
365
+ return "text/html";
366
+ case "js":
367
+ case "mjs":
368
+ return "application/javascript";
369
+ case "ts":
370
+ return "application/typescript";
371
+ default:
372
+ return undefined;
373
+ }
374
+ }
375
+
376
+ function extractDocxText(buffer: Buffer): string {
377
+ try {
378
+ const archive = unzipSync(new Uint8Array(buffer));
379
+ const sectionNames = Object.keys(archive)
380
+ .filter((name) => /^word\/(document|header\d+|footer\d+)\.xml$/u.test(name))
381
+ .sort((left, right) => {
382
+ if (left === "word/document.xml") {
383
+ return -1;
384
+ }
385
+ if (right === "word/document.xml") {
386
+ return 1;
387
+ }
388
+ return left.localeCompare(right);
389
+ });
390
+
391
+ const sections = sectionNames
392
+ .map((name) => {
393
+ const entry = archive[name];
394
+ if (!entry) {
395
+ return "";
396
+ }
397
+ return extractWordXmlText(Buffer.from(entry).toString("utf8"));
398
+ })
399
+ .filter((section) => section.trim() !== "");
400
+
401
+ return sections.join("\n\n").trim();
402
+ } catch {
403
+ return "";
404
+ }
405
+ }
406
+
407
+ function extractWordXmlText(xml: string): string {
408
+ const paragraphs = xml
409
+ .split(/<w:p\b[^>]*>/u)
410
+ .slice(1)
411
+ .map((paragraphXml) => {
412
+ const withinParagraph = paragraphXml.split(/<\/w:p>/u, 1)[0] ?? paragraphXml;
413
+ const normalized = withinParagraph
414
+ .replace(/<w:tab\/>/gu, "\t")
415
+ .replace(/<w:br(?:\s[^>]*)?\/>/gu, "\n")
416
+ .replace(/<\/w:tr>/gu, "\n")
417
+ .replace(/<\/w:tc>/gu, "\t");
418
+
419
+ const textRuns = [...normalized.matchAll(/<w:t\b[^>]*>([\s\S]*?)<\/w:t>/gu)]
420
+ .map((match) => decodeXmlEntities(match[1] ?? ""))
421
+ .join("");
422
+
423
+ return textRuns.replace(/\r\n/gu, "\n").trim();
424
+ })
425
+ .filter((paragraph) => paragraph !== "");
426
+
427
+ return paragraphs.join("\n");
428
+ }
429
+
430
+ function decodeXmlEntities(value: string): string {
431
+ return value.replace(XML_ENTITY_PATTERN, (entity, rawName: string) => {
432
+ switch (rawName) {
433
+ case "amp":
434
+ return "&";
435
+ case "lt":
436
+ return "<";
437
+ case "gt":
438
+ return ">";
439
+ case "quot":
440
+ return '"';
441
+ case "apos":
442
+ return "'";
443
+ default:
444
+ if (rawName.startsWith("#x")) {
445
+ return String.fromCodePoint(parseInt(rawName.slice(2), 16));
446
+ }
447
+ if (rawName.startsWith("#")) {
448
+ return String.fromCodePoint(parseInt(rawName.slice(1), 10));
449
+ }
450
+ return entity;
451
+ }
452
+ });
453
+ }
454
+
455
+ function sanitizeFileName(fileName: string): string {
456
+ const trimmed = fileName.trim();
457
+ const fallback = trimmed === "" ? "attachment" : trimmed;
458
+ return fallback.replace(/[\\/:*?"<>|\u0000-\u001f]/gu, "_");
459
+ }
460
+
461
+ function toWorkspacePath(workspaceDir: string, absolutePath: string): string {
462
+ return path.relative(workspaceDir, absolutePath).split(path.sep).join("/");
463
+ }
464
+
465
+ function getFileExtension(fileName: string): string {
466
+ const extension = path.extname(fileName).toLowerCase();
467
+ return extension.startsWith(".") ? extension.slice(1) : extension;
468
+ }
469
+
470
+ function isTextLikeMimeType(mimeType: string): boolean {
471
+ return mimeType.startsWith("text/") || TEXT_LIKE_MIME_TYPES.has(mimeType);
472
+ }
473
+
474
+ function isTextLikeExtension(fileName: string): boolean {
475
+ const extension = getFileExtension(fileName);
476
+ return new Set([
477
+ "txt",
478
+ "md",
479
+ "markdown",
480
+ "csv",
481
+ "json",
482
+ "xml",
483
+ "yaml",
484
+ "yml",
485
+ "html",
486
+ "js",
487
+ "mjs",
488
+ "ts",
489
+ ]).has(extension);
490
+ }
@@ -0,0 +1,45 @@
1
+ import type { PrivateClawAttachment } from "@privateclaw/protocol";
2
+ import type { BridgeResponse, PrivateClawAgentBridge } from "../types.js";
3
+
4
+ interface WebhookBridgeOptions {
5
+ endpoint: string;
6
+ token?: string;
7
+ }
8
+
9
+ interface WebhookResponseShape {
10
+ reply?: string;
11
+ messages?: Array<string | { text: string; attachments?: PrivateClawAttachment[] }>;
12
+ }
13
+
14
+ export class WebhookBridge implements PrivateClawAgentBridge {
15
+ constructor(private readonly options: WebhookBridgeOptions) {}
16
+
17
+ async handleUserMessage(params: {
18
+ sessionId: string;
19
+ message: string;
20
+ history: ReadonlyArray<{ role: string; text: string; sentAt: string }>;
21
+ attachments?: ReadonlyArray<PrivateClawAttachment>;
22
+ }): Promise<BridgeResponse> {
23
+ const response = await fetch(this.options.endpoint, {
24
+ method: "POST",
25
+ headers: {
26
+ "content-type": "application/json",
27
+ ...(this.options.token ? { authorization: `Bearer ${this.options.token}` } : {}),
28
+ },
29
+ body: JSON.stringify(params),
30
+ });
31
+
32
+ if (!response.ok) {
33
+ throw new Error(`Webhook bridge responded with ${response.status} ${response.statusText}`);
34
+ }
35
+
36
+ const payload = (await response.json()) as WebhookResponseShape;
37
+ if (Array.isArray(payload.messages) && payload.messages.length > 0) {
38
+ return { messages: payload.messages };
39
+ }
40
+ if (typeof payload.reply === "string" && payload.reply.trim() !== "") {
41
+ return payload.reply;
42
+ }
43
+ throw new Error("Webhook bridge must return either reply or messages.");
44
+ }
45
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { EchoBridge } from "./bridges/echo-bridge.js";
4
+ import { OpenClawAgentBridge } from "./bridges/openclaw-agent-bridge.js";
5
+ import { OpenAICompatibleBridge } from "./bridges/openai-compatible-bridge.js";
6
+ import { WebhookBridge } from "./bridges/webhook-bridge.js";
7
+ import { PrivateClawProvider } from "./provider.js";
8
+ import { resolveRelayEndpoints } from "./relay-endpoints.js";
9
+
10
+ function parsePositiveInteger(value: string | undefined, fallback: number): number {
11
+ if (!value || value.trim() === "") {
12
+ return fallback;
13
+ }
14
+
15
+ const parsed = Number.parseInt(value, 10);
16
+ if (!Number.isInteger(parsed) || parsed <= 0) {
17
+ throw new Error(`Expected a positive integer, received: ${value}`);
18
+ }
19
+
20
+ return parsed;
21
+ }
22
+
23
+ function parseBooleanFlag(value: string | undefined): boolean {
24
+ return value != null && /^(1|true|yes|on)$/i.test(value.trim());
25
+ }
26
+
27
+ function resolveChatCompletionsUrl(baseUrl: string): string {
28
+ const url = new URL(baseUrl);
29
+ url.pathname = "/v1/chat/completions";
30
+ url.search = "";
31
+ url.hash = "";
32
+ return url.toString();
33
+ }
34
+
35
+ const relayBaseUrl = process.env.PRIVATECLAW_RELAY_BASE_URL?.trim() || "ws://127.0.0.1:8787";
36
+ const { providerWsUrl, appWsUrl } = resolveRelayEndpoints(relayBaseUrl);
37
+ const webhookUrl = process.env.PRIVATECLAW_WEBHOOK_URL?.trim();
38
+ const webhookToken = process.env.PRIVATECLAW_WEBHOOK_TOKEN?.trim();
39
+ const gatewayBaseUrl = process.env.PRIVATECLAW_GATEWAY_BASE_URL?.trim();
40
+ const gatewayChatCompletionsUrl = process.env.PRIVATECLAW_GATEWAY_CHAT_COMPLETIONS_URL?.trim();
41
+ const gatewayModel = process.env.PRIVATECLAW_GATEWAY_MODEL?.trim() || "openclaw";
42
+ const gatewayApiKey = process.env.PRIVATECLAW_GATEWAY_API_KEY?.trim();
43
+ const gatewaySystemPrompt = process.env.PRIVATECLAW_GATEWAY_SYSTEM_PROMPT?.trim();
44
+ const openClawAgentBridge = parseBooleanFlag(process.env.PRIVATECLAW_OPENCLAW_AGENT_BRIDGE);
45
+ const openClawAgentExecutable = process.env.PRIVATECLAW_OPENCLAW_AGENT_BIN?.trim();
46
+ const openClawAgentId = process.env.PRIVATECLAW_OPENCLAW_AGENT_ID?.trim();
47
+ const openClawAgentChannel = process.env.PRIVATECLAW_OPENCLAW_AGENT_CHANNEL?.trim();
48
+ const openClawAgentThinking = process.env.PRIVATECLAW_OPENCLAW_AGENT_THINKING?.trim() as
49
+ | "off"
50
+ | "minimal"
51
+ | "low"
52
+ | "medium"
53
+ | "high"
54
+ | undefined;
55
+ const openClawAgentLocal = parseBooleanFlag(process.env.PRIVATECLAW_OPENCLAW_AGENT_LOCAL);
56
+ const openClawAgentTimeoutSeconds = process.env.PRIVATECLAW_OPENCLAW_AGENT_TIMEOUT_SECONDS
57
+ ? parsePositiveInteger(process.env.PRIVATECLAW_OPENCLAW_AGENT_TIMEOUT_SECONDS, 600)
58
+ : undefined;
59
+ const ttlMs = parsePositiveInteger(process.env.PRIVATECLAW_SESSION_TTL_MS, 15 * 60 * 1000);
60
+ const providerLabel = process.env.PRIVATECLAW_PROVIDER_LABEL?.trim() || "PrivateClaw";
61
+ const welcomeMessage = process.env.PRIVATECLAW_WELCOME_MESSAGE?.trim();
62
+
63
+ const bridge =
64
+ openClawAgentBridge
65
+ ? new OpenClawAgentBridge({
66
+ ...(openClawAgentExecutable ? { executable: openClawAgentExecutable } : {}),
67
+ ...(openClawAgentId ? { agentId: openClawAgentId } : {}),
68
+ ...(openClawAgentChannel ? { channel: openClawAgentChannel } : {}),
69
+ ...(openClawAgentThinking ? { thinking: openClawAgentThinking } : {}),
70
+ ...(openClawAgentTimeoutSeconds ? { timeoutSeconds: openClawAgentTimeoutSeconds } : {}),
71
+ ...(openClawAgentLocal ? { local: true } : {}),
72
+ })
73
+ : gatewayChatCompletionsUrl || gatewayBaseUrl
74
+ ? new OpenAICompatibleBridge({
75
+ endpoint: gatewayChatCompletionsUrl || resolveChatCompletionsUrl(gatewayBaseUrl!),
76
+ model: gatewayModel,
77
+ ...(gatewayApiKey ? { apiKey: gatewayApiKey } : {}),
78
+ ...(gatewaySystemPrompt ? { systemPrompt: gatewaySystemPrompt } : {}),
79
+ })
80
+ : webhookUrl
81
+ ? new WebhookBridge({ endpoint: webhookUrl, ...(webhookToken ? { token: webhookToken } : {}) })
82
+ : new EchoBridge(process.env.PRIVATECLAW_ECHO_PREFIX?.trim() || "PrivateClaw demo");
83
+
84
+ const provider = new PrivateClawProvider({
85
+ providerWsUrl,
86
+ appWsUrl,
87
+ bridge,
88
+ defaultTtlMs: ttlMs,
89
+ providerLabel,
90
+ ...(welcomeMessage ? { welcomeMessage } : {}),
91
+ onLog: (message) => {
92
+ console.log(`[privateclaw-provider] ${message}`);
93
+ },
94
+ });
95
+
96
+ await provider.connect();
97
+ const inviteBundle = await provider.createInviteBundle();
98
+
99
+ console.log(inviteBundle.announcementText);
100
+ console.log(`Invite URI: ${inviteBundle.inviteUri}`);
101
+ console.log(inviteBundle.qrTerminal);
102
+
103
+ async function shutdown(signal: string): Promise<void> {
104
+ console.log(`[privateclaw-provider] received ${signal}, shutting down`);
105
+ await provider.dispose();
106
+ process.exit(0);
107
+ }
108
+
109
+ process.on("SIGINT", () => {
110
+ void shutdown("SIGINT");
111
+ });
112
+ process.on("SIGTERM", () => {
113
+ void shutdown("SIGTERM");
114
+ });
115
+ process.stdin.resume();