@privateclaw/privateclaw 0.1.31 → 0.1.33

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 (44) hide show
  1. package/README.md +14 -9
  2. package/dist/audio-transcriber.js +98 -20
  3. package/dist/audio-transcriber.js.map +1 -1
  4. package/dist/bridges/openclaw-agent-bridge.d.ts +7 -0
  5. package/dist/bridges/openclaw-agent-bridge.js +71 -25
  6. package/dist/bridges/openclaw-agent-bridge.js.map +1 -1
  7. package/dist/channel.d.ts +14 -0
  8. package/dist/channel.js +103 -0
  9. package/dist/channel.js.map +1 -0
  10. package/dist/cli.js +16 -2
  11. package/dist/cli.js.map +1 -1
  12. package/dist/compat/openclaw.d.ts +231 -2
  13. package/dist/compat/openclaw.js +1 -0
  14. package/dist/compat/openclaw.js.map +1 -1
  15. package/dist/openclaw-plugin.js +199 -4
  16. package/dist/openclaw-plugin.js.map +1 -1
  17. package/dist/pair-session.d.ts +32 -0
  18. package/dist/pair-session.js +115 -41
  19. package/dist/pair-session.js.map +1 -1
  20. package/dist/provider.d.ts +4 -1
  21. package/dist/provider.js +109 -4
  22. package/dist/provider.js.map +1 -1
  23. package/dist/session-control.d.ts +15 -1
  24. package/dist/session-control.js +184 -5
  25. package/dist/session-control.js.map +1 -1
  26. package/dist/types.d.ts +20 -1
  27. package/openclaw.plugin.json +3 -2
  28. package/package.json +1 -1
  29. package/src/audio-transcriber.test.ts +152 -0
  30. package/src/audio-transcriber.ts +116 -23
  31. package/src/bridges/openclaw-agent-bridge.test.ts +154 -0
  32. package/src/bridges/openclaw-agent-bridge.ts +97 -27
  33. package/src/channel.ts +130 -0
  34. package/src/cli.ts +17 -1
  35. package/src/compat/openclaw.ts +282 -2
  36. package/src/openclaw-plugin.test.ts +392 -3
  37. package/src/openclaw-plugin.ts +262 -3
  38. package/src/pair-session.test.ts +119 -0
  39. package/src/pair-session.ts +144 -47
  40. package/src/provider.test.ts +266 -0
  41. package/src/provider.ts +133 -4
  42. package/src/session-control.test.ts +87 -0
  43. package/src/session-control.ts +252 -5
  44. package/src/types.ts +23 -0
@@ -4,7 +4,7 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import test from "node:test";
6
6
  import { fileURLToPath } from "node:url";
7
- import { decodeInviteString, encryptPayload } from "@privateclaw/protocol";
7
+ import { decodeInviteString, decryptPayload, encryptPayload } from "@privateclaw/protocol";
8
8
  import WebSocket from "ws";
9
9
  import { createRelayServer } from "../../../services/relay-server/src/relay-server.js";
10
10
  import { EchoBridge } from "./bridges/echo-bridge.js";
@@ -12,21 +12,70 @@ import { privateClawConfigSchema } from "./compat/openclaw.js";
12
12
  import { DEFAULT_SESSION_TTL_MS } from "./provider.js";
13
13
  import { DEFAULT_RELAY_BASE_URL } from "./relay-defaults.js";
14
14
  import type {
15
+ OpenClawChannelPluginCompat,
15
16
  OpenClawPluginCliRegistrarCompat,
16
17
  OpenClawPluginApiCompat,
17
18
  OpenClawPluginCommandDefinitionCompat,
18
19
  OpenClawPluginServiceCompat,
20
+ OpenClawPluginRuntimeCompat,
19
21
  } from "./compat/openclaw.js";
20
22
  import { createOpenClawCompatiblePlugin } from "./openclaw-plugin.js";
23
+ import { listManagedSessionsFromStateDir } from "./session-control.js";
21
24
 
22
25
  const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
23
26
 
24
- function createMockApi(): {
27
+ function waitForOpen(socket: WebSocket): Promise<void> {
28
+ return new Promise((resolve, reject) => {
29
+ socket.once("open", () => resolve());
30
+ socket.once("error", reject);
31
+ });
32
+ }
33
+
34
+ function nextMessage(socket: WebSocket): Promise<Record<string, unknown>> {
35
+ return new Promise((resolve, reject) => {
36
+ socket.once("message", (data) => {
37
+ resolve(JSON.parse(data.toString()) as Record<string, unknown>);
38
+ });
39
+ socket.once("error", reject);
40
+ });
41
+ }
42
+
43
+ function nextMessages(
44
+ socket: WebSocket,
45
+ count: number,
46
+ ): Promise<Record<string, unknown>[]> {
47
+ return new Promise((resolve, reject) => {
48
+ const messages: Record<string, unknown>[] = [];
49
+ const handleMessage = (data: WebSocket.RawData) => {
50
+ messages.push(JSON.parse(data.toString()) as Record<string, unknown>);
51
+ if (messages.length === count) {
52
+ cleanup();
53
+ resolve(messages);
54
+ }
55
+ };
56
+ const handleError = (error: Error) => {
57
+ cleanup();
58
+ reject(error);
59
+ };
60
+ const cleanup = () => {
61
+ socket.off("message", handleMessage);
62
+ socket.off("error", handleError);
63
+ };
64
+ socket.on("message", handleMessage);
65
+ socket.on("error", handleError);
66
+ });
67
+ }
68
+
69
+ function createMockApi(
70
+ runtime: OpenClawPluginRuntimeCompat | unknown = {},
71
+ ): {
25
72
  api: OpenClawPluginApiCompat;
73
+ getChannel(): OpenClawChannelPluginCompat;
26
74
  getCli(): { registrar: OpenClawPluginCliRegistrarCompat; commands: string[] };
27
75
  getCommand(): OpenClawPluginCommandDefinitionCompat;
28
76
  getService(): OpenClawPluginServiceCompat;
29
77
  } {
78
+ let channel: OpenClawChannelPluginCompat | undefined;
30
79
  let command: OpenClawPluginCommandDefinitionCompat | undefined;
31
80
  let cli:
32
81
  | {
@@ -43,8 +92,11 @@ function createMockApi(): {
43
92
 
44
93
  return {
45
94
  api: {
46
- runtime: {},
95
+ runtime,
47
96
  logger,
97
+ registerChannel(params) {
98
+ channel = params.plugin as OpenClawChannelPluginCompat;
99
+ },
48
100
  registerCommand(registeredCommand) {
49
101
  command = registeredCommand;
50
102
  },
@@ -62,6 +114,10 @@ function createMockApi(): {
62
114
  assert.ok(cli, "plugin should register the local privateclaw CLI");
63
115
  return cli;
64
116
  },
117
+ getChannel() {
118
+ assert.ok(channel, "plugin should register the privateclaw channel plugin");
119
+ return channel;
120
+ },
65
121
  getCommand() {
66
122
  assert.ok(command, "plugin should register the /privateclaw command");
67
123
  return command;
@@ -110,11 +166,344 @@ test("privateclaw schema advertises the public relay default", () => {
110
166
  privateClawConfigSchema.properties.relayBaseUrl.default,
111
167
  DEFAULT_RELAY_BASE_URL,
112
168
  );
169
+ assert.equal(
170
+ privateClawConfigSchema.properties.openclawAgentChannel.default,
171
+ "privateclaw",
172
+ );
113
173
  assert.equal(privateClawConfigSchema.properties.botMode.type, "boolean");
114
174
  assert.equal(privateClawConfigSchema.properties.botModeSilentJoinDelayMs.minimum, 0);
115
175
  assert.equal(privateClawConfigSchema.properties.botModeIdleDelayMs.minimum, 0);
116
176
  });
117
177
 
178
+ test("plugin registers the privateclaw channel plugin", () => {
179
+ const plugin = createOpenClawCompatiblePlugin({
180
+ providerWsUrl: "ws://127.0.0.1:8787/ws/provider",
181
+ appWsUrl: "ws://127.0.0.1:8787/ws/app",
182
+ bridge: new EchoBridge("OpenClaw bridge"),
183
+ });
184
+ const { api, getChannel } = createMockApi();
185
+ plugin.register(api);
186
+ const channel = getChannel();
187
+ assert.equal(channel.id, "privateclaw");
188
+ assert.equal(channel.meta.id, "privateclaw");
189
+ assert.equal(channel.outbound?.deliveryMode, "direct");
190
+ assert.deepEqual(channel.capabilities.chatTypes, ["direct", "group"]);
191
+ });
192
+
193
+ test("plugin service startup eagerly starts the plugin-service control host", async (t) => {
194
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-service-"));
195
+ t.after(async () => {
196
+ await rm(stateDir, { recursive: true, force: true });
197
+ });
198
+
199
+ const plugin = createOpenClawCompatiblePlugin({
200
+ providerWsUrl: "ws://127.0.0.1:8787/ws/provider",
201
+ appWsUrl: "ws://127.0.0.1:8787/ws/app",
202
+ bridge: new EchoBridge("OpenClaw bridge"),
203
+ });
204
+ const { api, getService } = createMockApi();
205
+ plugin.register(api);
206
+
207
+ const service = getService();
208
+ await service.start({
209
+ config: {},
210
+ stateDir,
211
+ logger: api.logger,
212
+ });
213
+ t.after(async () => {
214
+ await service.stop?.({
215
+ config: {},
216
+ stateDir,
217
+ logger: api.logger,
218
+ });
219
+ });
220
+
221
+ const listings = await listManagedSessionsFromStateDir(stateDir);
222
+ assert.equal(listings.length, 1);
223
+ assert.equal(listings[0]?.host.kind, "plugin-service");
224
+ assert.deepEqual(listings[0]?.sessions, []);
225
+ });
226
+
227
+ test("plugin routes paired app text through OpenClaw runtime helpers with the real session-store signatures", async (t) => {
228
+ const relay = createRelayServer({
229
+ host: "127.0.0.1",
230
+ port: 0,
231
+ sessionTtlMs: 60_000,
232
+ frameCacheSize: 8,
233
+ });
234
+ const { port } = await relay.start();
235
+
236
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-state-"));
237
+ t.after(async () => {
238
+ await rm(stateDir, { recursive: true, force: true });
239
+ await relay.stop();
240
+ });
241
+
242
+ const resolvedStorePaths: Array<{
243
+ store?: string;
244
+ opts?: { agentId?: string };
245
+ }> = [];
246
+ const recordedSessions: Array<Record<string, unknown>> = [];
247
+ const fakeRuntime = {
248
+ channel: {
249
+ reply: {
250
+ finalizeInboundContext: <T extends Record<string, unknown>>(ctx: T) =>
251
+ ({
252
+ ...ctx,
253
+ CommandAuthorized: true,
254
+ }) as T & { CommandAuthorized: true },
255
+ dispatchReplyWithBufferedBlockDispatcher: async ({
256
+ ctx,
257
+ dispatcherOptions,
258
+ }: {
259
+ ctx: Record<string, unknown>;
260
+ dispatcherOptions: {
261
+ deliver(
262
+ payload: {
263
+ text?: string;
264
+ replyToId?: string | null;
265
+ },
266
+ info: { kind: "tool" | "block" | "final" },
267
+ ): Promise<void>;
268
+ };
269
+ }) => {
270
+ const commandBody = String(ctx.CommandBody ?? "");
271
+ await dispatcherOptions.deliver(
272
+ {
273
+ text: `Runtime reply: ${commandBody}`,
274
+ },
275
+ { kind: "final" },
276
+ );
277
+ return {};
278
+ },
279
+ },
280
+ routing: {
281
+ resolveAgentRoute: ({ ctx }: { ctx: Record<string, unknown> }) => ({
282
+ agentId: "runtime-agent",
283
+ sessionKey: `runtime-${String(ctx.To ?? "session")}`,
284
+ mainSessionKey: `runtime-${String(ctx.To ?? "session")}`,
285
+ lastRoutePolicy: "current" as const,
286
+ }),
287
+ },
288
+ session: {
289
+ resolveStorePath: (store?: string, opts?: { agentId?: string }) => {
290
+ resolvedStorePaths.push({ store, opts });
291
+ return path.join(stateDir, "memory", `${opts?.agentId ?? "agent"}.sqlite`);
292
+ },
293
+ recordInboundSession: async (params: Record<string, unknown>) => {
294
+ recordedSessions.push(params);
295
+ },
296
+ },
297
+ },
298
+ } satisfies OpenClawPluginRuntimeCompat;
299
+
300
+ const plugin = createOpenClawCompatiblePlugin({
301
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
302
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
303
+ bridge: {
304
+ async handleUserMessage() {
305
+ throw new Error("bridge should not be used when runtime routing is available");
306
+ },
307
+ },
308
+ welcomeMessage: "Welcome to PrivateClaw",
309
+ });
310
+ const { api, getCommand, getService } = createMockApi(fakeRuntime);
311
+ plugin.register(api);
312
+
313
+ const config = {
314
+ session: {
315
+ store: "~/privateclaw-runtime-{agentId}.sqlite",
316
+ },
317
+ };
318
+ const service = getService();
319
+ await service.start({
320
+ config,
321
+ stateDir,
322
+ logger: api.logger,
323
+ });
324
+ t.after(async () => {
325
+ await service.stop?.({
326
+ config,
327
+ stateDir,
328
+ logger: api.logger,
329
+ });
330
+ });
331
+
332
+ const command = getCommand();
333
+ const reply = await command.handler({
334
+ channel: "telegram",
335
+ senderId: "tester",
336
+ isAuthorizedSender: true,
337
+ commandBody: "/privateclaw",
338
+ config,
339
+ });
340
+ const inviteUri = reply.text?.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
341
+ assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
342
+ const invite = decodeInviteString(inviteUri);
343
+
344
+ const appUrl = new URL(invite.appWsUrl);
345
+ appUrl.searchParams.set("appId", "runtime-router-app");
346
+ const appSocket = new WebSocket(appUrl.toString());
347
+ t.after(() => {
348
+ appSocket.terminate();
349
+ });
350
+ const attached = nextMessage(appSocket);
351
+ await waitForOpen(appSocket);
352
+ assert.equal((await attached).type, "relay:attached");
353
+ const initialFrames = nextMessages(appSocket, 2);
354
+ appSocket.send(
355
+ JSON.stringify({
356
+ type: "app:frame",
357
+ envelope: encryptPayload({
358
+ sessionId: invite.sessionId,
359
+ sessionKey: invite.sessionKey,
360
+ payload: {
361
+ kind: "client_hello",
362
+ appId: "runtime-router-app",
363
+ displayName: "Runtime Router",
364
+ appVersion: "plugin-test",
365
+ deviceLabel: "Runtime Router Device",
366
+ sentAt: new Date().toISOString(),
367
+ },
368
+ }),
369
+ }),
370
+ );
371
+ await initialFrames;
372
+
373
+ appSocket.send(
374
+ JSON.stringify({
375
+ type: "app:frame",
376
+ envelope: encryptPayload({
377
+ sessionId: invite.sessionId,
378
+ sessionKey: invite.sessionKey,
379
+ payload: {
380
+ kind: "user_message",
381
+ appId: "runtime-router-app",
382
+ text: "hello runtime",
383
+ clientMessageId: "runtime-msg-1",
384
+ sentAt: new Date().toISOString(),
385
+ },
386
+ }),
387
+ }),
388
+ );
389
+
390
+ const replyFrame = await nextMessage(appSocket);
391
+ const replyPayload = decryptPayload({
392
+ sessionId: invite.sessionId,
393
+ sessionKey: invite.sessionKey,
394
+ envelope: replyFrame.envelope as Parameters<typeof decryptPayload>[0]["envelope"],
395
+ });
396
+ assert.equal(replyPayload.kind, "assistant_message");
397
+ assert.equal(replyPayload.text, "Runtime reply: hello runtime");
398
+ assert.equal(replyPayload.replyTo, "runtime-msg-1");
399
+ assert.equal(resolvedStorePaths[0]?.store, "~/privateclaw-runtime-{agentId}.sqlite");
400
+ assert.equal(resolvedStorePaths[0]?.opts?.agentId, "runtime-agent");
401
+ assert.equal(recordedSessions[0]?.storePath, path.join(stateDir, "memory", "runtime-agent.sqlite"));
402
+ assert.equal(recordedSessions[0]?.createIfMissing, true);
403
+ assert.deepEqual(recordedSessions[0]?.updateLastRoute, {
404
+ sessionKey: `runtime-${invite.sessionId}`,
405
+ channel: "privateclaw",
406
+ to: invite.sessionId,
407
+ accountId: "default",
408
+ });
409
+ });
410
+
411
+ test("privateclaw channel outbound delivers replies into managed sessions", async (t) => {
412
+ const relay = createRelayServer({
413
+ host: "127.0.0.1",
414
+ port: 0,
415
+ sessionTtlMs: 60_000,
416
+ frameCacheSize: 8,
417
+ });
418
+ const { port } = await relay.start();
419
+
420
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-state-"));
421
+ t.after(async () => {
422
+ await rm(stateDir, { recursive: true, force: true });
423
+ await relay.stop();
424
+ });
425
+
426
+ const plugin = createOpenClawCompatiblePlugin({
427
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
428
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
429
+ bridge: new EchoBridge("OpenClaw bridge"),
430
+ welcomeMessage: "Welcome to PrivateClaw",
431
+ });
432
+ const { api, getChannel, getCommand, getService } = createMockApi();
433
+ plugin.register(api);
434
+
435
+ const service = getService();
436
+ await service.start({
437
+ config: {},
438
+ stateDir,
439
+ logger: api.logger,
440
+ });
441
+ t.after(async () => {
442
+ await service.stop?.({
443
+ config: {},
444
+ stateDir,
445
+ logger: api.logger,
446
+ });
447
+ });
448
+
449
+ const command = getCommand();
450
+ const reply = await command.handler({
451
+ channel: "telegram",
452
+ senderId: "tester",
453
+ isAuthorizedSender: true,
454
+ commandBody: "/privateclaw",
455
+ config: {},
456
+ });
457
+ const inviteUri = reply.text?.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
458
+ assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
459
+ const invite = decodeInviteString(inviteUri);
460
+
461
+ const appUrl = new URL(invite.appWsUrl);
462
+ appUrl.searchParams.set("appId", "plugin-test-app");
463
+ const appSocket = new WebSocket(appUrl.toString());
464
+ const attached = nextMessage(appSocket);
465
+ await waitForOpen(appSocket);
466
+ assert.equal((await attached).type, "relay:attached");
467
+ const initialFrames = nextMessages(appSocket, 2);
468
+ appSocket.send(
469
+ JSON.stringify({
470
+ type: "app:frame",
471
+ envelope: encryptPayload({
472
+ sessionId: invite.sessionId,
473
+ sessionKey: invite.sessionKey,
474
+ payload: {
475
+ kind: "client_hello",
476
+ appId: "plugin-test-app",
477
+ displayName: "Plugin Tester",
478
+ appVersion: "plugin-test",
479
+ deviceLabel: "Plugin Tester Device",
480
+ sentAt: new Date().toISOString(),
481
+ },
482
+ }),
483
+ }),
484
+ );
485
+ await initialFrames;
486
+
487
+ const channel = getChannel();
488
+ await channel.outbound?.sendText?.({
489
+ cfg: {},
490
+ to: invite.sessionId,
491
+ text: "scheduled hello from channel",
492
+ replyToId: "user-msg-1",
493
+ });
494
+
495
+ const outboundFrame = await nextMessage(appSocket);
496
+ const outboundPayload = decryptPayload({
497
+ sessionId: invite.sessionId,
498
+ sessionKey: invite.sessionKey,
499
+ envelope: outboundFrame.envelope as Parameters<typeof decryptPayload>[0]["envelope"],
500
+ });
501
+ assert.equal(outboundPayload.kind, "assistant_message");
502
+ assert.equal(outboundPayload.text, "scheduled hello from channel");
503
+ assert.equal(outboundPayload.replyTo, "user-msg-1");
504
+ appSocket.close();
505
+ });
506
+
118
507
  test("privateclaw command writes QR media into the OpenClaw state media directory", async (t) => {
119
508
  const relay = createRelayServer({
120
509
  host: "127.0.0.1",