@privateclaw/privateclaw 0.1.32 → 0.1.34

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 (40) hide show
  1. package/README.md +16 -9
  2. package/dist/bridges/openclaw-agent-bridge.d.ts +7 -0
  3. package/dist/bridges/openclaw-agent-bridge.js +71 -25
  4. package/dist/bridges/openclaw-agent-bridge.js.map +1 -1
  5. package/dist/channel.d.ts +14 -0
  6. package/dist/channel.js +103 -0
  7. package/dist/channel.js.map +1 -0
  8. package/dist/cli.js +16 -2
  9. package/dist/cli.js.map +1 -1
  10. package/dist/compat/openclaw.d.ts +231 -2
  11. package/dist/compat/openclaw.js +1 -0
  12. package/dist/compat/openclaw.js.map +1 -1
  13. package/dist/openclaw-plugin.js +199 -4
  14. package/dist/openclaw-plugin.js.map +1 -1
  15. package/dist/pair-session.d.ts +32 -0
  16. package/dist/pair-session.js +115 -41
  17. package/dist/pair-session.js.map +1 -1
  18. package/dist/provider.d.ts +4 -1
  19. package/dist/provider.js +109 -4
  20. package/dist/provider.js.map +1 -1
  21. package/dist/session-control.d.ts +15 -1
  22. package/dist/session-control.js +184 -5
  23. package/dist/session-control.js.map +1 -1
  24. package/dist/types.d.ts +20 -1
  25. package/openclaw.plugin.json +3 -2
  26. package/package.json +2 -2
  27. package/src/bridges/openclaw-agent-bridge.test.ts +154 -0
  28. package/src/bridges/openclaw-agent-bridge.ts +97 -27
  29. package/src/channel.ts +130 -0
  30. package/src/cli.ts +17 -1
  31. package/src/compat/openclaw.ts +282 -2
  32. package/src/openclaw-plugin.test.ts +392 -3
  33. package/src/openclaw-plugin.ts +262 -3
  34. package/src/pair-session.test.ts +119 -0
  35. package/src/pair-session.ts +144 -47
  36. package/src/provider.test.ts +266 -0
  37. package/src/provider.ts +133 -4
  38. package/src/session-control.test.ts +87 -0
  39. package/src/session-control.ts +252 -5
  40. package/src/types.ts +23 -0
@@ -22,6 +22,7 @@ import {
22
22
  buildManagedSessionsReportLines,
23
23
  closeManagedSessionsFromStateDir,
24
24
  closeManagedSessionFromStateDir,
25
+ deliverManagedSessionOutboundFromStateDir,
25
26
  followManagedSessionLogFromStateDir,
26
27
  getManagedSessionQrBundleFromStateDir,
27
28
  isManagedSessionQrLegacyResult,
@@ -343,6 +344,92 @@ test("session control can print and notify a managed session QR", async (t) => {
343
344
  await Promise.all([waitForClose(appOne), waitForClose(appTwo)]);
344
345
  });
345
346
 
347
+ test("session control outbound delivery accepts group-prefixed session targets", async (t) => {
348
+ const relay = createRelayServer({
349
+ host: "127.0.0.1",
350
+ port: 0,
351
+ sessionTtlMs: 60_000,
352
+ frameCacheSize: 8,
353
+ });
354
+ const { port } = await relay.start();
355
+ t.after(async () => {
356
+ await relay.stop();
357
+ });
358
+
359
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-session-control-"));
360
+ t.after(async () => {
361
+ await rm(stateDir, { recursive: true, force: true });
362
+ });
363
+
364
+ const provider = new PrivateClawProvider({
365
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
366
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
367
+ bridge: new EchoBridge("OpenClaw bridge"),
368
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
369
+ });
370
+ await provider.connect();
371
+ t.after(async () => {
372
+ await provider.dispose();
373
+ });
374
+
375
+ const controlServer = new PrivateClawSessionControlServer({
376
+ provider,
377
+ stateDir,
378
+ kind: "pair-foreground",
379
+ });
380
+ await controlServer.start();
381
+ t.after(async () => {
382
+ await controlServer.stop();
383
+ });
384
+
385
+ const inviteBundle = await provider.createInviteBundle({ groupMode: true });
386
+ const invite = decodeInviteString(inviteBundle.inviteUri);
387
+
388
+ const appUrl = new URL(invite.appWsUrl);
389
+ appUrl.searchParams.set("appId", "group-target-app");
390
+ const appSocket = new WebSocket(appUrl.toString());
391
+ const attached = nextMessage(appSocket);
392
+ await waitForOpen(appSocket);
393
+ assert.equal((await attached).type, "relay:attached");
394
+ const initialFrames = nextMessages(appSocket, 2);
395
+ appSocket.send(
396
+ JSON.stringify({
397
+ type: "app:frame",
398
+ envelope: encryptPayload({
399
+ sessionId: invite.sessionId,
400
+ sessionKey: invite.sessionKey,
401
+ payload: {
402
+ kind: "client_hello",
403
+ appId: "group-target-app",
404
+ displayName: "Group Target Tester",
405
+ appVersion: "flutter-test",
406
+ deviceLabel: "Group Target Device",
407
+ sentAt: new Date().toISOString(),
408
+ },
409
+ }),
410
+ }),
411
+ );
412
+ await initialFrames;
413
+
414
+ await deliverManagedSessionOutboundFromStateDir({
415
+ stateDir,
416
+ sessionId: `group:${invite.sessionId}`,
417
+ payload: {
418
+ text: "scheduled hello from group target",
419
+ replyToId: "scheduled-user-msg-1",
420
+ },
421
+ });
422
+
423
+ const outboundFrame = await nextMessage(appSocket);
424
+ const outboundPayload = decryptRelayPayload(outboundFrame, invite);
425
+ assert.equal(outboundPayload.kind, "assistant_message");
426
+ assert.equal(outboundPayload.text, "scheduled hello from group target");
427
+ assert.equal(outboundPayload.replyTo, "scheduled-user-msg-1");
428
+
429
+ appSocket.close();
430
+ await waitForClose(appSocket);
431
+ });
432
+
346
433
  test("session control can follow a managed OpenClaw session log", async (t) => {
347
434
  const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-session-control-follow-"));
348
435
  t.after(async () => {
@@ -12,6 +12,8 @@ import {
12
12
  import type {
13
13
  PrivateClawInviteBundle,
14
14
  PrivateClawManagedSession,
15
+ PrivateClawOpenClawOutboundMessage,
16
+ PrivateClawRoutedAppMessage,
15
17
  } from "./types.js";
16
18
 
17
19
  export type PrivateClawControlHostKind =
@@ -77,6 +79,15 @@ interface PrivateClawSessionQrResult {
77
79
  bundle: PrivateClawInviteBundle;
78
80
  }
79
81
 
82
+ interface PrivateClawSessionOutboundResult {
83
+ sessionId: string;
84
+ }
85
+
86
+ interface PrivateClawAppDispatchResult {
87
+ sessionId: string;
88
+ handled: true;
89
+ }
90
+
80
91
  interface PrivateClawSessionControlProvider {
81
92
  listManagedSessions(): PrivateClawManagedSession[];
82
93
  getSessionQrBundle(
@@ -95,6 +106,13 @@ interface PrivateClawSessionControlProvider {
95
106
  appId: string;
96
107
  displayName: string;
97
108
  }>;
109
+ deliverOpenClawOutboundMessage?(
110
+ sessionId: string,
111
+ payload: PrivateClawOpenClawOutboundMessage,
112
+ ): Promise<void>;
113
+ routeAppMessageToOpenClaw?(
114
+ message: PrivateClawRoutedAppMessage,
115
+ ): Promise<void>;
98
116
  }
99
117
 
100
118
  function writeJson(
@@ -156,6 +174,110 @@ function isDescriptor(
156
174
  );
157
175
  }
158
176
 
177
+ function readNonEmptyString(value: unknown): string | undefined {
178
+ if (typeof value !== "string") {
179
+ return undefined;
180
+ }
181
+ const trimmed = value.trim();
182
+ return trimmed === "" ? undefined : trimmed;
183
+ }
184
+
185
+ function normalizeManagedSessionLookupId(sessionId: string): string {
186
+ const trimmed = sessionId.trim();
187
+ const separatorIndex = trimmed.indexOf(":");
188
+ if (separatorIndex <= 0) {
189
+ return trimmed;
190
+ }
191
+ const prefix = trimmed.slice(0, separatorIndex).toLowerCase();
192
+ if (prefix !== "group" && prefix !== "direct") {
193
+ return trimmed;
194
+ }
195
+ const bareSessionId = trimmed.slice(separatorIndex + 1).trim();
196
+ return bareSessionId === "" ? trimmed : bareSessionId;
197
+ }
198
+
199
+ function normalizeRoutedAppMessage(value: unknown): PrivateClawRoutedAppMessage {
200
+ if (!value || typeof value !== "object") {
201
+ throw new Error("Expected a routed app message object.");
202
+ }
203
+ const candidate = value as Record<string, unknown>;
204
+ const sessionId = readNonEmptyString(candidate.sessionId);
205
+ if (!sessionId) {
206
+ throw new Error("Routed app message requires a sessionId.");
207
+ }
208
+ if (typeof candidate.groupMode !== "boolean") {
209
+ throw new Error("Routed app message requires a boolean groupMode.");
210
+ }
211
+ const payload =
212
+ candidate.payload && typeof candidate.payload === "object"
213
+ ? (candidate.payload as Record<string, unknown>)
214
+ : undefined;
215
+ if (!payload || payload.kind !== "user_message") {
216
+ throw new Error("Routed app message payload must be a user_message.");
217
+ }
218
+ if (!readNonEmptyString(payload.text)) {
219
+ throw new Error("Routed app message payload requires text.");
220
+ }
221
+ if (!readNonEmptyString(payload.clientMessageId)) {
222
+ throw new Error("Routed app message payload requires clientMessageId.");
223
+ }
224
+ if (!readNonEmptyString(payload.sentAt)) {
225
+ throw new Error("Routed app message payload requires sentAt.");
226
+ }
227
+ const participantCandidate =
228
+ candidate.participant && typeof candidate.participant === "object"
229
+ ? (candidate.participant as Record<string, unknown>)
230
+ : undefined;
231
+ const participant =
232
+ participantCandidate &&
233
+ readNonEmptyString(participantCandidate.appId) &&
234
+ readNonEmptyString(participantCandidate.displayName)
235
+ ? (() => {
236
+ const deviceLabel = readNonEmptyString(participantCandidate.deviceLabel);
237
+ return {
238
+ appId: readNonEmptyString(participantCandidate.appId)!,
239
+ displayName: readNonEmptyString(participantCandidate.displayName)!,
240
+ ...(deviceLabel ? { deviceLabel } : {}),
241
+ };
242
+ })()
243
+ : undefined;
244
+ const sessionLabel = readNonEmptyString(candidate.sessionLabel);
245
+ return {
246
+ sessionId,
247
+ ...(sessionLabel ? { sessionLabel } : {}),
248
+ groupMode: candidate.groupMode,
249
+ ...(participant ? { participant } : {}),
250
+ payload: candidate.payload as PrivateClawRoutedAppMessage["payload"],
251
+ };
252
+ }
253
+
254
+ function normalizeOpenClawOutboundMessage(
255
+ value: unknown,
256
+ ): PrivateClawOpenClawOutboundMessage {
257
+ if (!value || typeof value !== "object") {
258
+ throw new Error("Expected an outbound payload object.");
259
+ }
260
+ const candidate = value as Record<string, unknown>;
261
+ const text = readNonEmptyString(candidate.text);
262
+ const mediaUrl = readNonEmptyString(candidate.mediaUrl);
263
+ const mediaUrls = Array.isArray(candidate.mediaUrls)
264
+ ? candidate.mediaUrls
265
+ .map((item) => readNonEmptyString(item))
266
+ .filter((item): item is string => item != null)
267
+ : undefined;
268
+ const replyToId =
269
+ candidate.replyToId === null ? null : readNonEmptyString(candidate.replyToId);
270
+ if (!text && !mediaUrl && (!mediaUrls || mediaUrls.length === 0)) {
271
+ throw new Error("Outbound payload must include text, mediaUrl, or mediaUrls.");
272
+ }
273
+ return {
274
+ ...(text ? { text } : {}),
275
+ ...(mediaUrl ? { mediaUrl } : {}),
276
+ ...(mediaUrls && mediaUrls.length > 0 ? { mediaUrls } : {}),
277
+ ...(replyToId !== undefined ? { replyToId } : {}),
278
+ };
279
+ }
280
+
159
281
  async function listDescriptorPaths(controlDir: string): Promise<string[]> {
160
282
  try {
161
283
  const entries = await readdir(controlDir, { withFileTypes: true });
@@ -472,6 +594,43 @@ export class PrivateClawSessionControlServer {
472
594
  } satisfies PrivateClawSessionCloseResult);
473
595
  return;
474
596
  }
597
+ if (
598
+ request.method === "POST" &&
599
+ url.pathname.startsWith("/sessions/") &&
600
+ url.pathname.endsWith("/outbound")
601
+ ) {
602
+ if (!this.options.provider.deliverOpenClawOutboundMessage) {
603
+ writeJson(response, 404, { error: "not_found" });
604
+ return;
605
+ }
606
+ const sessionId = decodeURIComponent(
607
+ url.pathname.slice("/sessions/".length, -"/outbound".length),
608
+ );
609
+ const payload = normalizeOpenClawOutboundMessage(
610
+ await readJsonBody(request),
611
+ );
612
+ await this.options.provider.deliverOpenClawOutboundMessage(
613
+ sessionId,
614
+ payload,
615
+ );
616
+ writeJson(response, 200, {
617
+ sessionId,
618
+ } satisfies PrivateClawSessionOutboundResult);
619
+ return;
620
+ }
621
+ if (request.method === "POST" && url.pathname === "/openclaw/dispatch-app-message") {
622
+ if (!this.options.provider.routeAppMessageToOpenClaw) {
623
+ writeJson(response, 404, { error: "not_found" });
624
+ return;
625
+ }
626
+ const message = normalizeRoutedAppMessage(await readJsonBody(request));
627
+ await this.options.provider.routeAppMessageToOpenClaw(message);
628
+ writeJson(response, 200, {
629
+ sessionId: message.sessionId,
630
+ handled: true,
631
+ } satisfies PrivateClawAppDispatchResult);
632
+ return;
633
+ }
475
634
 
476
635
  writeJson(response, 404, { error: "not_found" });
477
636
  } catch (error) {
@@ -572,12 +731,13 @@ async function resolveManagedSessionDescriptor(params: {
572
731
  descriptor: PrivateClawSessionControlDescriptor;
573
732
  descriptorPath: string;
574
733
  }> {
734
+ const normalizedSessionId = normalizeManagedSessionLookupId(params.sessionId);
575
735
  const listings = await listManagedSessionsFromStateDir(params.stateDir);
576
736
  const descriptors = await loadDescriptors(params.stateDir);
577
737
 
578
738
  for (const listing of listings) {
579
739
  const session = listing.sessions.find(
580
- (candidate) => candidate.sessionId === params.sessionId,
740
+ (candidate) => candidate.sessionId === normalizedSessionId,
581
741
  );
582
742
  if (!session) {
583
743
  continue;
@@ -603,13 +763,39 @@ async function resolveManagedSessionDescriptor(params: {
603
763
  );
604
764
  }
605
765
 
766
+ async function resolvePluginServiceDescriptor(params: {
767
+ stateDir: string;
768
+ }): Promise<{
769
+ descriptor: PrivateClawSessionControlDescriptor;
770
+ descriptorPath: string;
771
+ }> {
772
+ const descriptors = await loadDescriptors(params.stateDir);
773
+ const pluginDescriptors = descriptors
774
+ .filter((candidate) => candidate.descriptor.kind === "plugin-service")
775
+ .sort((left, right) =>
776
+ right.descriptor.startedAt.localeCompare(left.descriptor.startedAt),
777
+ );
778
+ for (const candidate of pluginDescriptors) {
779
+ try {
780
+ await requestDescriptorJson<{ ok: true }>(candidate.descriptor, "/healthz");
781
+ return candidate;
782
+ } catch {
783
+ await rm(candidate.descriptorPath, { force: true });
784
+ }
785
+ }
786
+ throw new Error(
787
+ `Could not find an active PrivateClaw plugin-service host in ${resolvePrivateClawStateDir(params.stateDir)}.`,
788
+ );
789
+ }
790
+
606
791
  async function resolveLegacySessionQrPngPath(params: {
607
792
  stateDir: string;
608
793
  sessionId: string;
609
794
  }): Promise<string | undefined> {
795
+ const normalizedSessionId = normalizeManagedSessionLookupId(params.sessionId);
610
796
  const pngPath = path.join(
611
797
  resolvePrivateClawMediaDir(resolvePrivateClawStateDir(params.stateDir)),
612
- `privateclaw-${params.sessionId}.png`,
798
+ `privateclaw-${normalizedSessionId}.png`,
613
799
  );
614
800
  try {
615
801
  await access(pngPath);
@@ -701,7 +887,7 @@ export async function kickManagedParticipantFromStateDir(params: {
701
887
  });
702
888
  const result = await requestDescriptorJson<PrivateClawKickResult>(
703
889
  resolved.descriptor,
704
- `/sessions/${encodeURIComponent(params.sessionId)}/kick`,
890
+ `/sessions/${encodeURIComponent(resolved.session.sessionId)}/kick`,
705
891
  {
706
892
  method: "POST",
707
893
  body: {
@@ -717,6 +903,67 @@ export async function kickManagedParticipantFromStateDir(params: {
717
903
  };
718
904
  }
719
905
 
906
+ export async function dispatchRoutedAppMessageToPluginServiceFromStateDir(params: {
907
+ stateDir: string;
908
+ message: PrivateClawRoutedAppMessage;
909
+ }): Promise<void> {
910
+ const resolved = await resolvePluginServiceDescriptor({
911
+ stateDir: params.stateDir,
912
+ });
913
+ try {
914
+ await requestDescriptorJson<PrivateClawAppDispatchResult>(
915
+ resolved.descriptor,
916
+ "/openclaw/dispatch-app-message",
917
+ {
918
+ method: "POST",
919
+ body: params.message,
920
+ },
921
+ );
922
+ } catch (error) {
923
+ if (error instanceof PrivateClawControlRequestError && error.status === 404) {
924
+ throw new Error(
925
+ "The active PrivateClaw plugin-service host is too old to accept routed app messages.",
926
+ );
927
+ }
928
+ throw error;
929
+ }
930
+ }
931
+
932
+ export async function deliverManagedSessionOutboundFromStateDir(params: {
933
+ stateDir: string;
934
+ sessionId: string;
935
+ payload: PrivateClawOpenClawOutboundMessage;
936
+ }): Promise<{
937
+ host: PrivateClawDiscoveredSessionHost;
938
+ session: PrivateClawManagedSession;
939
+ }> {
940
+ const resolved = await resolveManagedSessionDescriptor({
941
+ stateDir: params.stateDir,
942
+ sessionId: params.sessionId,
943
+ });
944
+ try {
945
+ await requestDescriptorJson<PrivateClawSessionOutboundResult>(
946
+ resolved.descriptor,
947
+ `/sessions/${encodeURIComponent(resolved.session.sessionId)}/outbound`,
948
+ {
949
+ method: "POST",
950
+ body: params.payload,
951
+ },
952
+ );
953
+ } catch (error) {
954
+ if (error instanceof PrivateClawControlRequestError && error.status === 404) {
955
+ throw new Error(
956
+ `The PrivateClaw host for session ${params.sessionId} is too old to accept OpenClaw channel replies.`,
957
+ );
958
+ }
959
+ throw error;
960
+ }
961
+ return {
962
+ host: resolved.listing.host,
963
+ session: resolved.session,
964
+ };
965
+ }
966
+
720
967
  export async function closeManagedSessionFromStateDir(params: {
721
968
  stateDir: string;
722
969
  sessionId: string;
@@ -733,7 +980,7 @@ export async function closeManagedSessionFromStateDir(params: {
733
980
  try {
734
981
  await requestDescriptorJson<PrivateClawSessionCloseResult>(
735
982
  resolved.descriptor,
736
- `/sessions/${encodeURIComponent(params.sessionId)}/close`,
983
+ `/sessions/${encodeURIComponent(resolved.session.sessionId)}/close`,
737
984
  {
738
985
  method: "POST",
739
986
  body: {
@@ -843,7 +1090,7 @@ export async function getManagedSessionQrBundleFromStateDir(params: {
843
1090
  try {
844
1091
  const result = await requestDescriptorJson<PrivateClawSessionQrResult>(
845
1092
  resolved.descriptor,
846
- `/sessions/${encodeURIComponent(params.sessionId)}/qr`,
1093
+ `/sessions/${encodeURIComponent(resolved.session.sessionId)}/qr`,
847
1094
  {
848
1095
  method: "POST",
849
1096
  body: {
package/src/types.ts CHANGED
@@ -5,6 +5,7 @@ import type {
5
5
  PrivateClawSlashCommand,
6
6
  PrivateClawThinkingEntry,
7
7
  PrivateClawThinkingStatus,
8
+ UserMessagePayload,
8
9
  } from "@privateclaw/protocol";
9
10
 
10
11
  export interface PrivateClawConversationTurn {
@@ -76,6 +77,27 @@ export interface PrivateClawAgentBridge {
76
77
  ): Promise<string>;
77
78
  }
78
79
 
80
+ export interface PrivateClawAppMessageParticipant {
81
+ appId: string;
82
+ displayName: string;
83
+ deviceLabel?: string;
84
+ }
85
+
86
+ export interface PrivateClawRoutedAppMessage {
87
+ sessionId: string;
88
+ sessionLabel?: string;
89
+ groupMode: boolean;
90
+ participant?: PrivateClawAppMessageParticipant;
91
+ payload: UserMessagePayload;
92
+ }
93
+
94
+ export interface PrivateClawOpenClawOutboundMessage {
95
+ text?: string;
96
+ mediaUrl?: string;
97
+ mediaUrls?: string[];
98
+ replyToId?: string | null;
99
+ }
100
+
79
101
  export interface PrivateClawProviderOptions {
80
102
  providerWsUrl: string;
81
103
  appWsUrl: string;
@@ -89,6 +111,7 @@ export interface PrivateClawProviderOptions {
89
111
  botModeSilentJoinDelayMs?: number;
90
112
  botModeIdleDelayMs?: number;
91
113
  commandsProvider?: () => Promise<PrivateClawSlashCommand[]>;
114
+ appMessageRouter?: (params: PrivateClawRoutedAppMessage) => Promise<boolean>;
92
115
  verboseController?: PrivateClawVerboseController;
93
116
  onLog?: (message: string) => void;
94
117
  }