@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,139 @@
1
+ export const privateClawConfigSchema = {
2
+ type: "object",
3
+ additionalProperties: false,
4
+ properties: {
5
+ relayBaseUrl: {
6
+ type: "string",
7
+ description: "Relay base URL used to derive /ws/provider and /ws/app endpoints.",
8
+ },
9
+ sessionTtlMs: {
10
+ type: "number",
11
+ description: "Lifetime of a one-time PrivateClaw session in milliseconds.",
12
+ minimum: 1000,
13
+ },
14
+ welcomeMessage: {
15
+ type: "string",
16
+ description: "Encrypted welcome message sent to the client after handshake.",
17
+ },
18
+ providerLabel: {
19
+ type: "string",
20
+ description: "Label rendered into the invite payload and QR metadata.",
21
+ },
22
+ webhookUrl: {
23
+ type: "string",
24
+ description: "Optional upstream bridge endpoint that converts user messages into OpenClaw replies.",
25
+ },
26
+ webhookToken: {
27
+ type: "string",
28
+ description: "Optional bearer token sent with the webhook bridge.",
29
+ },
30
+ bridgeMode: {
31
+ type: "string",
32
+ enum: ["openclaw-agent", "webhook", "echo"],
33
+ description: "Which upstream bridge the plugin should use for PrivateClaw sessions.",
34
+ },
35
+ echoPrefix: {
36
+ type: "string",
37
+ description: "Prefix used when bridgeMode is set to echo.",
38
+ },
39
+ openclawAgentExecutable: {
40
+ type: "string",
41
+ description: "Optional executable path used for the OpenClaw agent bridge.",
42
+ },
43
+ openclawAgentId: {
44
+ type: "string",
45
+ description: "Optional OpenClaw agent id forwarded to `openclaw agent`.",
46
+ },
47
+ openclawAgentChannel: {
48
+ type: "string",
49
+ description: "Optional OpenClaw channel id forwarded to `openclaw agent`.",
50
+ },
51
+ openclawAgentLocal: {
52
+ type: "boolean",
53
+ description: "Whether the OpenClaw agent bridge should pass --local.",
54
+ },
55
+ openclawAgentThinking: {
56
+ type: "string",
57
+ enum: ["off", "minimal", "low", "medium", "high"],
58
+ description: "Optional thinking level for `openclaw agent`.",
59
+ },
60
+ openclawAgentTimeoutSeconds: {
61
+ type: "number",
62
+ description: "Optional timeout in seconds for `openclaw agent` invocations.",
63
+ minimum: 0,
64
+ },
65
+ },
66
+ } as const;
67
+
68
+ export interface ReplyPayloadCompat {
69
+ text?: string;
70
+ mediaUrl?: string;
71
+ mediaUrls?: string[];
72
+ isError?: boolean;
73
+ channelData?: Record<string, unknown>;
74
+ }
75
+
76
+ export interface OpenClawPluginCommandContextCompat {
77
+ senderId?: string;
78
+ channel: string;
79
+ channelId?: string;
80
+ isAuthorizedSender: boolean;
81
+ args?: string;
82
+ commandBody: string;
83
+ config: unknown;
84
+ from?: string;
85
+ to?: string;
86
+ accountId?: string;
87
+ messageThreadId?: number;
88
+ }
89
+
90
+ export interface OpenClawPluginCommandDefinitionCompat {
91
+ name: string;
92
+ nativeNames?: Partial<Record<string, string>> & { default?: string };
93
+ description: string;
94
+ acceptsArgs?: boolean;
95
+ requireAuth?: boolean;
96
+ handler(
97
+ ctx: OpenClawPluginCommandContextCompat,
98
+ ): Promise<ReplyPayloadCompat> | ReplyPayloadCompat;
99
+ }
100
+
101
+ export interface OpenClawPluginLoggerCompat {
102
+ debug?(message: string): void;
103
+ info(message: string): void;
104
+ warn(message: string): void;
105
+ error(message: string): void;
106
+ }
107
+
108
+ export interface OpenClawPluginServiceCompat {
109
+ id: string;
110
+ start(params: {
111
+ config: unknown;
112
+ workspaceDir?: string;
113
+ stateDir: string;
114
+ logger: OpenClawPluginLoggerCompat;
115
+ }): Promise<void> | void;
116
+ stop?(params: {
117
+ config: unknown;
118
+ workspaceDir?: string;
119
+ stateDir: string;
120
+ logger: OpenClawPluginLoggerCompat;
121
+ }): Promise<void> | void;
122
+ }
123
+
124
+ export interface OpenClawPluginApiCompat {
125
+ runtime: unknown;
126
+ pluginConfig?: Record<string, unknown>;
127
+ logger: OpenClawPluginLoggerCompat;
128
+ registerChannel?(params: { plugin: unknown }): void;
129
+ registerCommand(command: OpenClawPluginCommandDefinitionCompat): void;
130
+ registerService?(service: OpenClawPluginServiceCompat): void;
131
+ }
132
+
133
+ export interface OpenClawExtensionPluginCompat {
134
+ id: string;
135
+ name: string;
136
+ description: string;
137
+ configSchema: typeof privateClawConfigSchema;
138
+ register(api: OpenClawPluginApiCompat): void;
139
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ export * from "./bridges/echo-bridge.js";
2
+ export * from "./bridges/openclaw-agent-bridge.js";
3
+ export * from "./bridges/openai-compatible-bridge.js";
4
+ export * from "./bridges/webhook-bridge.js";
5
+ export * from "./compat/openclaw.js";
6
+ export { default } from "./openclaw-plugin.js";
7
+ export * from "./openclaw-plugin.js";
8
+ export * from "./provider.js";
9
+ export * from "./relay-endpoints.js";
10
+ export * from "./relay-provider-client.js";
11
+ export * from "./types.js";
@@ -0,0 +1,276 @@
1
+ import { execFile } from "node:child_process";
2
+ import { access, readFile, readdir, realpath } from "node:fs/promises";
3
+ import { constants } from "node:fs";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { pathToFileURL } from "node:url";
7
+ import type { PrivateClawSlashCommand } from "@privateclaw/protocol";
8
+
9
+ const execFileAsync = promisify(execFile);
10
+
11
+ interface OpenClawCommandDefinitionLike {
12
+ key?: unknown;
13
+ description?: unknown;
14
+ textAliases?: unknown;
15
+ acceptsArgs?: unknown;
16
+ }
17
+
18
+ interface OpenClawPluginCommandSpecLike {
19
+ name?: unknown;
20
+ description?: unknown;
21
+ acceptsArgs?: unknown;
22
+ }
23
+
24
+ interface OpenClawCommandRuntime {
25
+ listChatCommands: () => OpenClawCommandDefinitionLike[];
26
+ getPluginCommandSpecs: () => OpenClawPluginCommandSpecLike[];
27
+ }
28
+
29
+ let cachedRuntimePromise: Promise<OpenClawCommandRuntime | null> | undefined;
30
+
31
+ function normalizeSlash(value: string): string {
32
+ const trimmed = value.trim();
33
+ if (!trimmed) {
34
+ return "";
35
+ }
36
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
37
+ }
38
+
39
+ function mapBuiltInCommands(
40
+ commands: OpenClawCommandDefinitionLike[],
41
+ ): PrivateClawSlashCommand[] {
42
+ return commands.flatMap((command) => {
43
+ const aliases = Array.isArray(command.textAliases)
44
+ ? command.textAliases.filter((value): value is string => typeof value === "string")
45
+ : [];
46
+ const fallback =
47
+ typeof command.key === "string" && command.key.trim()
48
+ ? `/${command.key.trim().toLowerCase()}`
49
+ : "";
50
+ const slash = normalizeSlash(aliases[0] ?? fallback);
51
+ const description =
52
+ typeof command.description === "string" ? command.description.trim() : "";
53
+ if (!slash || !description) {
54
+ return [];
55
+ }
56
+ return [
57
+ {
58
+ slash,
59
+ description,
60
+ acceptsArgs: Boolean(command.acceptsArgs),
61
+ source: "openclaw" as const,
62
+ },
63
+ ];
64
+ });
65
+ }
66
+
67
+ function mapPluginCommands(
68
+ commands: OpenClawPluginCommandSpecLike[],
69
+ ): PrivateClawSlashCommand[] {
70
+ return commands.flatMap((command) => {
71
+ const slash =
72
+ typeof command.name === "string" ? normalizeSlash(command.name) : "";
73
+ const description =
74
+ typeof command.description === "string" ? command.description.trim() : "";
75
+ if (!slash || !description) {
76
+ return [];
77
+ }
78
+ return [
79
+ {
80
+ slash,
81
+ description,
82
+ acceptsArgs: Boolean(command.acceptsArgs),
83
+ source: "plugin" as const,
84
+ },
85
+ ];
86
+ });
87
+ }
88
+
89
+ function dedupeCommands(commands: PrivateClawSlashCommand[]): PrivateClawSlashCommand[] {
90
+ const unique = new Map<string, PrivateClawSlashCommand>();
91
+ for (const command of commands) {
92
+ unique.set(command.slash.toLowerCase(), command);
93
+ }
94
+ return [...unique.values()].sort((left, right) =>
95
+ left.slash.localeCompare(right.slash),
96
+ );
97
+ }
98
+
99
+ async function pathExists(filePath: string): Promise<boolean> {
100
+ try {
101
+ await access(filePath, constants.F_OK);
102
+ return true;
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+
108
+ async function isOpenClawRoot(candidate: string): Promise<boolean> {
109
+ const packageJsonPath = path.join(candidate, "package.json");
110
+ if (!(await pathExists(packageJsonPath))) {
111
+ return false;
112
+ }
113
+ try {
114
+ const parsed = JSON.parse(await readFile(packageJsonPath, "utf8")) as {
115
+ name?: unknown;
116
+ };
117
+ return parsed.name === "openclaw";
118
+ } catch {
119
+ return false;
120
+ }
121
+ }
122
+
123
+ async function searchParentsForOpenClawRoot(startPath: string): Promise<string | null> {
124
+ let current = startPath;
125
+ try {
126
+ current = await realpath(startPath);
127
+ } catch {
128
+ return null;
129
+ }
130
+
131
+ let cursor = current;
132
+ while (true) {
133
+ const candidate = path.extname(cursor) ? path.dirname(cursor) : cursor;
134
+ if (await isOpenClawRoot(candidate)) {
135
+ return candidate;
136
+ }
137
+ const parent = path.dirname(candidate);
138
+ if (parent === candidate) {
139
+ return null;
140
+ }
141
+ cursor = parent;
142
+ }
143
+ }
144
+
145
+ async function resolveGlobalOpenClawRoot(): Promise<string | null> {
146
+ try {
147
+ const { stdout } = await execFileAsync("npm", ["root", "-g"]);
148
+ const npmRoot = stdout.trim();
149
+ if (!npmRoot) {
150
+ return null;
151
+ }
152
+ const candidate = path.join(npmRoot, "openclaw");
153
+ return (await isOpenClawRoot(candidate)) ? candidate : null;
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+
159
+ async function resolveOpenClawRoot(): Promise<string | null> {
160
+ const envCandidate = process.env.OPENCLAW_PACKAGE_ROOT?.trim();
161
+ if (envCandidate) {
162
+ const resolved = await searchParentsForOpenClawRoot(envCandidate);
163
+ if (resolved) {
164
+ return resolved;
165
+ }
166
+ }
167
+
168
+ const searchCandidates = [
169
+ process.argv[1],
170
+ process.cwd(),
171
+ "/opt/homebrew/lib/node_modules/openclaw",
172
+ "/usr/local/lib/node_modules/openclaw",
173
+ ].filter((value): value is string => typeof value === "string" && value.trim() !== "");
174
+
175
+ for (const candidate of searchCandidates) {
176
+ const resolved = await searchParentsForOpenClawRoot(candidate);
177
+ if (resolved) {
178
+ return resolved;
179
+ }
180
+ }
181
+
182
+ return resolveGlobalOpenClawRoot();
183
+ }
184
+
185
+ async function resolveHashedModulePath(params: {
186
+ distDir: string;
187
+ entryFile: string;
188
+ prefix: string;
189
+ }): Promise<string | null> {
190
+ const entryPath = path.join(params.distDir, params.entryFile);
191
+ try {
192
+ const entryContents = await readFile(entryPath, "utf8");
193
+ const match = entryContents.match(
194
+ new RegExp(`["']\\.\\/(${params.prefix}[A-Za-z0-9_-]+\\.js)["']`),
195
+ );
196
+ if (match?.[1]) {
197
+ return path.join(params.distDir, match[1]);
198
+ }
199
+ } catch {
200
+ // Fall through to directory scan.
201
+ }
202
+
203
+ try {
204
+ const entries = await readdir(params.distDir);
205
+ const match = entries.find(
206
+ (entry) => entry.startsWith(params.prefix) && entry.endsWith(".js"),
207
+ );
208
+ return match ? path.join(params.distDir, match) : null;
209
+ } catch {
210
+ return null;
211
+ }
212
+ }
213
+
214
+ async function loadRuntime(): Promise<OpenClawCommandRuntime | null> {
215
+ if (!cachedRuntimePromise) {
216
+ cachedRuntimePromise = (async () => {
217
+ const openClawRoot = await resolveOpenClawRoot();
218
+ if (!openClawRoot) {
219
+ return null;
220
+ }
221
+
222
+ const distDir = path.join(openClawRoot, "dist");
223
+ const pluginSdkDir = path.join(distDir, "plugin-sdk");
224
+ const [commandsRegistryPath, registryPath] = await Promise.all([
225
+ resolveHashedModulePath({
226
+ distDir: pluginSdkDir,
227
+ entryFile: "index.js",
228
+ prefix: "commands-registry-",
229
+ }),
230
+ resolveHashedModulePath({
231
+ distDir,
232
+ entryFile: "index.js",
233
+ prefix: "registry-",
234
+ }),
235
+ ]);
236
+
237
+ if (!commandsRegistryPath || !registryPath) {
238
+ return null;
239
+ }
240
+
241
+ const [commandsModule, registryModule] = await Promise.all([
242
+ import(pathToFileURL(commandsRegistryPath).href) as Promise<Record<string, unknown>>,
243
+ import(pathToFileURL(registryPath).href) as Promise<Record<string, unknown>>,
244
+ ]);
245
+
246
+ const listChatCommands = commandsModule.i;
247
+ const getPluginCommandSpecs = registryModule.w;
248
+ if (
249
+ typeof listChatCommands !== "function" ||
250
+ typeof getPluginCommandSpecs !== "function"
251
+ ) {
252
+ return null;
253
+ }
254
+
255
+ return {
256
+ listChatCommands: () => listChatCommands() as OpenClawCommandDefinitionLike[],
257
+ getPluginCommandSpecs: () =>
258
+ getPluginCommandSpecs() as OpenClawPluginCommandSpecLike[],
259
+ };
260
+ })();
261
+ }
262
+
263
+ return cachedRuntimePromise;
264
+ }
265
+
266
+ export async function loadAvailableOpenClawCommands(): Promise<PrivateClawSlashCommand[]> {
267
+ const runtime = await loadRuntime();
268
+ if (!runtime) {
269
+ return [];
270
+ }
271
+
272
+ return dedupeCommands([
273
+ ...mapBuiltInCommands(runtime.listChatCommands()),
274
+ ...mapPluginCommands(runtime.getPluginCommandSpecs()),
275
+ ]);
276
+ }
@@ -0,0 +1,114 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+ import { decodeInviteString } from "@privateclaw/protocol";
7
+ import { createRelayServer } from "../../../services/relay-server/src/relay-server.js";
8
+ import { EchoBridge } from "./bridges/echo-bridge.js";
9
+ import type {
10
+ OpenClawPluginApiCompat,
11
+ OpenClawPluginCommandDefinitionCompat,
12
+ OpenClawPluginServiceCompat,
13
+ } from "./compat/openclaw.js";
14
+ import { createOpenClawCompatiblePlugin } from "./openclaw-plugin.js";
15
+
16
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
17
+
18
+ function createMockApi(): {
19
+ api: OpenClawPluginApiCompat;
20
+ getCommand(): OpenClawPluginCommandDefinitionCompat;
21
+ getService(): OpenClawPluginServiceCompat;
22
+ } {
23
+ let command: OpenClawPluginCommandDefinitionCompat | undefined;
24
+ let service: OpenClawPluginServiceCompat | undefined;
25
+ const logger = {
26
+ info: (_message: string) => undefined,
27
+ warn: (_message: string) => undefined,
28
+ error: (_message: string) => undefined,
29
+ };
30
+
31
+ return {
32
+ api: {
33
+ runtime: {},
34
+ logger,
35
+ registerCommand(registeredCommand) {
36
+ command = registeredCommand;
37
+ },
38
+ registerService(registeredService) {
39
+ service = registeredService;
40
+ },
41
+ },
42
+ getCommand() {
43
+ assert.ok(command, "plugin should register the /privateclaw command");
44
+ return command;
45
+ },
46
+ getService() {
47
+ assert.ok(service, "plugin should register the provider lifecycle service");
48
+ return service;
49
+ },
50
+ };
51
+ }
52
+
53
+ test("privateclaw command writes QR media into the OpenClaw state media directory", async (t) => {
54
+ const relay = createRelayServer({
55
+ host: "127.0.0.1",
56
+ port: 0,
57
+ sessionTtlMs: 60_000,
58
+ frameCacheSize: 8,
59
+ });
60
+ const { port } = await relay.start();
61
+
62
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-state-"));
63
+ t.after(async () => {
64
+ await rm(stateDir, { recursive: true, force: true });
65
+ await relay.stop();
66
+ });
67
+
68
+ const plugin = createOpenClawCompatiblePlugin({
69
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
70
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
71
+ bridge: new EchoBridge("OpenClaw bridge"),
72
+ welcomeMessage: "Welcome to PrivateClaw",
73
+ });
74
+ const { api, getCommand, getService } = createMockApi();
75
+ plugin.register(api);
76
+
77
+ const service = getService();
78
+ await service.start({
79
+ config: {},
80
+ stateDir,
81
+ logger: api.logger,
82
+ });
83
+ t.after(async () => {
84
+ await service.stop?.({
85
+ config: {},
86
+ stateDir,
87
+ logger: api.logger,
88
+ });
89
+ });
90
+
91
+ const command = getCommand();
92
+ const reply = await command.handler({
93
+ channel: "telegram",
94
+ senderId: "tester",
95
+ isAuthorizedSender: true,
96
+ commandBody: "/privateclaw",
97
+ config: {},
98
+ });
99
+
100
+ assert.equal(reply.isError, undefined);
101
+ assert.ok(reply.text);
102
+ assert.ok(reply.mediaUrl);
103
+
104
+ const inviteUri = reply.text.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
105
+ assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
106
+
107
+ const invite = decodeInviteString(inviteUri);
108
+ const expectedMediaDir = path.join(stateDir, "media", "privateclaw");
109
+ assert.equal(path.dirname(reply.mediaUrl), expectedMediaDir);
110
+ assert.equal(path.basename(reply.mediaUrl), `privateclaw-${invite.sessionId}.png`);
111
+
112
+ const qrPng = await readFile(reply.mediaUrl);
113
+ assert.deepEqual(qrPng.subarray(0, PNG_SIGNATURE.length), PNG_SIGNATURE);
114
+ });