@privateclaw/privateclaw 0.1.6 → 0.1.9

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.
@@ -60,6 +60,21 @@ interface OpenClawSessionLogEntry {
60
60
  };
61
61
  }
62
62
 
63
+ interface PrivateClawStructuredMessage {
64
+ text?: string | null;
65
+ }
66
+
67
+ interface PrivateClawStructuredResponse {
68
+ version?: number;
69
+ messages?: PrivateClawStructuredMessage[];
70
+ data?: unknown;
71
+ }
72
+
73
+ interface NormalizedBridgeResult {
74
+ readonly messages: NormalizedBridgeMessage[];
75
+ readonly data?: unknown;
76
+ }
77
+
63
78
  interface NormalizedBridgeMessage {
64
79
  readonly text: string;
65
80
  readonly attachments?: PrivateClawAttachment[];
@@ -67,6 +82,7 @@ interface NormalizedBridgeMessage {
67
82
 
68
83
  interface CollectedSessionMessages {
69
84
  readonly assistantMessages: NormalizedBridgeMessage[];
85
+ readonly assistantData?: unknown;
70
86
  readonly artifactMessages: NormalizedBridgeMessage[];
71
87
  }
72
88
 
@@ -112,6 +128,9 @@ const DEFAULT_STATE_DIR = process.env.OPENCLAW_STATE_DIR ?? path.join(os.homedir
112
128
  const DEFAULT_WORKSPACE_DIR = path.join(DEFAULT_STATE_DIR, "workspace");
113
129
  const GENERIC_BINARY_MIME = "application/octet-stream";
114
130
  const XML_ENTITY_PATTERN = /&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);/giu;
131
+ const PRIVATECLAW_RESPONSE_CONTRACT_VERSION = 1;
132
+ const PRIVATECLAW_RESPONSE_TAG_START = "<privateclaw-response>";
133
+ const PRIVATECLAW_RESPONSE_TAG_END = "</privateclaw-response>";
115
134
  const DOCX_MIME_TYPES = new Set<string>([
116
135
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
117
136
  ]);
@@ -171,11 +190,11 @@ function parseOpenClawAgentJson(stdout: string): OpenClawAgentJsonResult {
171
190
  }
172
191
 
173
192
  function parseOpenClawAgentResult(parsed: OpenClawAgentJsonResult): BridgeResponse {
174
- const messages = extractDisplayMessages(parsed);
175
- return toBridgeResponse(messages);
193
+ const result = extractDisplayResult(parsed);
194
+ return toBridgeResponse(result.messages, result.data);
176
195
  }
177
196
 
178
- function extractDisplayMessages(parsed: OpenClawAgentJsonResult): NormalizedBridgeMessage[] {
197
+ function extractDisplayResult(parsed: OpenClawAgentJsonResult): NormalizedBridgeResult {
179
198
  const payloads = parsed.result?.payloads ?? parsed.payloads ?? [];
180
199
  const hasAlternatePayloadShape = !parsed.status && payloads.length > 0;
181
200
  if (parsed.status && parsed.status !== "ok") {
@@ -189,11 +208,27 @@ function extractDisplayMessages(parsed: OpenClawAgentJsonResult): NormalizedBrid
189
208
  );
190
209
  }
191
210
 
211
+ const structuredResults = payloads.flatMap((payload) =>
212
+ [payload.text, payload.message, payload.summary].flatMap((candidate) => {
213
+ if (typeof candidate !== "string") {
214
+ return [];
215
+ }
216
+ const result = parseStructuredResponseResult(candidate);
217
+ return result ? [result] : [];
218
+ }),
219
+ );
220
+ if (structuredResults.length > 0) {
221
+ return {
222
+ messages: structuredResults.flatMap((result) => result.messages),
223
+ ...combineStructuredData(structuredResults),
224
+ };
225
+ }
226
+
192
227
  const messages =
193
228
  payloads.flatMap((payload) =>
194
229
  [payload.text, payload.message, payload.summary].flatMap((candidate) =>
195
- typeof candidate === "string" && candidate.trim() !== ""
196
- ? [{ text: candidate }]
230
+ typeof candidate === "string" && stripStructuredResponseBlock(candidate) !== ""
231
+ ? [{ text: stripStructuredResponseBlock(candidate) }]
197
232
  : [],
198
233
  ),
199
234
  ) ?? [];
@@ -202,7 +237,7 @@ function extractDisplayMessages(parsed: OpenClawAgentJsonResult): NormalizedBrid
202
237
  throw new OpenClawAgentNoDisplayPayloadError(parsed);
203
238
  }
204
239
 
205
- return messages;
240
+ return { messages };
206
241
  }
207
242
 
208
243
  export class OpenClawAgentBridge implements PrivateClawAgentBridge {
@@ -273,7 +308,7 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
273
308
  this.log(
274
309
  `session_log_fallback session=${params.sessionId} reason=parse_failed recoveredMessages=${recoveredMessages.length}`,
275
310
  );
276
- return toBridgeResponse(recoveredMessages);
311
+ return toBridgeResponse(recoveredMessages, collectedMessages.assistantData);
277
312
  }
278
313
  throw parseError;
279
314
  }
@@ -285,7 +320,7 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
285
320
  this.log(
286
321
  `session_log_fallback session=${params.sessionId} reason=${JSON.stringify(error instanceof Error ? error.message : String(error))} recoveredMessages=${recoveredMessages.length}`,
287
322
  );
288
- return toBridgeResponse(recoveredMessages);
323
+ return toBridgeResponse(recoveredMessages, collectedMessages.assistantData);
289
324
  }
290
325
  if (error instanceof OpenClawAgentNoDisplayPayloadError) {
291
326
  return buildNoDisplayPayloadNotice(params.message, error.parsed);
@@ -339,10 +374,8 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
339
374
  .filter((line) => line !== "")
340
375
  .map((line) => JSON.parse(line) as OpenClawSessionLogEntry);
341
376
 
342
- const assistantMessages = entries.flatMap((entry) => {
343
- const text = extractAssistantDisplayText(entry);
344
- return text ? [{ text }] : [];
345
- });
377
+ const assistantResults = entries.map((entry) => extractAssistantDisplayResult(entry));
378
+ const assistantMessages = assistantResults.flatMap((result) => result.messages);
346
379
 
347
380
  const seenPaths = new Set<string>();
348
381
  const attachments: PrivateClawAttachment[] = [];
@@ -365,6 +398,7 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
365
398
  attachments.length > 0
366
399
  ? [{ text: "", attachments } satisfies NormalizedBridgeMessage]
367
400
  : [];
401
+ const assistantData = combineStructuredData(assistantResults).data;
368
402
 
369
403
  if (attachments.length === 0) {
370
404
  this.log(
@@ -372,6 +406,7 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
372
406
  );
373
407
  return {
374
408
  assistantMessages,
409
+ ...(assistantData !== undefined ? { assistantData } : {}),
375
410
  artifactMessages,
376
411
  };
377
412
  }
@@ -381,6 +416,7 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
381
416
  );
382
417
  return {
383
418
  assistantMessages,
419
+ ...(assistantData !== undefined ? { assistantData } : {}),
384
420
  artifactMessages,
385
421
  };
386
422
  }
@@ -421,37 +457,41 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
421
457
  ): Promise<string> {
422
458
  const trimmed = message.trim();
423
459
  const stagedAttachments = await this.stageAttachments(sessionId, attachments);
424
- this.log(
425
- `prompt_ready session=${sessionId} stagedAttachments=${stagedAttachments.length} textChars=${trimmed.length}`,
426
- );
427
-
428
- if (stagedAttachments.length === 0) {
429
- return trimmed;
430
- }
431
-
432
- const lines = [
433
- trimmed !== ""
434
- ? trimmed
435
- : "The user sent one or more file attachments without additional text.",
436
- "",
437
- "PrivateClaw staged the attachments into the OpenClaw workspace.",
438
- "Inspect the staged files before answering, and use the exact paths below instead of guessing a workspace-root filename.",
439
- "",
440
- "Staged attachments:",
441
- ];
442
-
443
- for (const attachment of stagedAttachments) {
444
- lines.push(`- ${attachment.name}`);
445
- lines.push(` mimeType: ${attachment.effectiveMimeType}`);
446
- lines.push(` kind: ${attachment.kind}`);
447
- lines.push(` workspacePath: ${attachment.workspacePath}`);
448
- if (attachment.extractedTextWorkspacePath) {
449
- lines.push(` extractedTextPath: ${attachment.extractedTextWorkspacePath}`);
460
+ let promptBody = trimmed;
461
+
462
+ if (stagedAttachments.length > 0) {
463
+ const lines = [
464
+ trimmed !== ""
465
+ ? trimmed
466
+ : "The user sent one or more file attachments without additional text.",
467
+ "",
468
+ "PrivateClaw staged the attachments into the OpenClaw workspace.",
469
+ "Inspect the staged files before answering, and use the exact paths below instead of guessing a workspace-root filename.",
470
+ "",
471
+ "Staged attachments:",
472
+ ];
473
+
474
+ for (const attachment of stagedAttachments) {
475
+ lines.push(`- ${attachment.name}`);
476
+ lines.push(` mimeType: ${attachment.effectiveMimeType}`);
477
+ lines.push(` kind: ${attachment.kind}`);
478
+ lines.push(` workspacePath: ${attachment.workspacePath}`);
479
+ if (attachment.extractedTextWorkspacePath) {
480
+ lines.push(` extractedTextPath: ${attachment.extractedTextWorkspacePath}`);
481
+ }
482
+ lines.push(` instruction: ${attachment.instruction}`);
450
483
  }
451
- lines.push(` instruction: ${attachment.instruction}`);
484
+
485
+ promptBody = lines.join("\n");
452
486
  }
453
487
 
454
- return lines.join("\n");
488
+ const promptMessage = appendStructuredResponseContract(
489
+ promptBody !== "" ? promptBody : "The user sent a message that requires a reply.",
490
+ );
491
+ this.log(
492
+ `prompt_ready session=${sessionId} stagedAttachments=${stagedAttachments.length} textChars=${trimmed.length} contractVersion=${PRIVATECLAW_RESPONSE_CONTRACT_VERSION}`,
493
+ );
494
+ return promptMessage;
455
495
  }
456
496
 
457
497
  private async stageAttachments(
@@ -703,10 +743,13 @@ function mergeBridgeResponses(
703
743
  return primary;
704
744
  }
705
745
 
706
- return toBridgeResponse([
707
- ...normalizeBridgeResponse(primary),
708
- ...supplemental,
709
- ]);
746
+ return toBridgeResponse(
747
+ [
748
+ ...normalizeBridgeResponse(primary),
749
+ ...supplemental,
750
+ ],
751
+ extractBridgeResponseData(primary),
752
+ );
710
753
  }
711
754
 
712
755
  function normalizeBridgeResponse(response: BridgeResponse): NormalizedBridgeMessage[] {
@@ -724,13 +767,16 @@ function normalizeBridgeResponse(response: BridgeResponse): NormalizedBridgeMess
724
767
  );
725
768
  }
726
769
 
727
- function toBridgeResponse(messages: NormalizedBridgeMessage[]): BridgeResponse {
770
+ function toBridgeResponse(
771
+ messages: NormalizedBridgeMessage[],
772
+ data?: unknown,
773
+ ): BridgeResponse {
728
774
  if (messages.length === 1) {
729
775
  const [message] = messages;
730
776
  if (!message) {
731
777
  throw new Error("Bridge response did not contain any messages.");
732
778
  }
733
- if (!message.attachments || message.attachments.length === 0) {
779
+ if ((!message.attachments || message.attachments.length === 0) && data === undefined) {
734
780
  return message.text;
735
781
  }
736
782
  }
@@ -741,6 +787,7 @@ function toBridgeResponse(messages: NormalizedBridgeMessage[]): BridgeResponse {
741
787
  ? message
742
788
  : { text: message.text },
743
789
  ),
790
+ ...(data !== undefined ? { data } : {}),
744
791
  };
745
792
  }
746
793
 
@@ -770,9 +817,9 @@ function extractMediaPaths(entry: OpenClawSessionLogEntry): string[] {
770
817
  return [...mediaPaths];
771
818
  }
772
819
 
773
- function extractAssistantDisplayText(entry: OpenClawSessionLogEntry): string | undefined {
820
+ function extractAssistantDisplayResult(entry: OpenClawSessionLogEntry): NormalizedBridgeResult {
774
821
  if (entry.type !== "message" || entry.message?.role !== "assistant" || entry.message.isError) {
775
- return undefined;
822
+ return { messages: [] };
776
823
  }
777
824
 
778
825
  const parts = (entry.message.content ?? [])
@@ -784,10 +831,114 @@ function extractAssistantDisplayText(entry: OpenClawSessionLogEntry): string | u
784
831
  .filter((text) => text !== "");
785
832
 
786
833
  if (parts.length === 0) {
834
+ return { messages: [] };
835
+ }
836
+
837
+ const rawText = parts.join("\n\n");
838
+ const structuredResult = parseStructuredResponseResult(rawText);
839
+ if (structuredResult) {
840
+ return structuredResult;
841
+ }
842
+
843
+ const fallbackText = stripStructuredResponseBlock(rawText);
844
+ return fallbackText !== "" ? { messages: [{ text: fallbackText }] } : { messages: [] };
845
+ }
846
+
847
+ function appendStructuredResponseContract(prompt: string): string {
848
+ return `${prompt}\n\n${buildStructuredResponseContractPrompt()}`;
849
+ }
850
+
851
+ function buildStructuredResponseContractPrompt(): string {
852
+ return [
853
+ "PrivateClaw response contract:",
854
+ `- After you finish your reasoning and tool usage, put the final user-visible result inside exactly one ${PRIVATECLAW_RESPONSE_TAG_START}...${PRIVATECLAW_RESPONSE_TAG_END} block.`,
855
+ "- The block content must be valid JSON.",
856
+ `- Use this JSON shape: {\"version\":${PRIVATECLAW_RESPONSE_CONTRACT_VERSION},\"messages\":[{\"text\":\"...\"}],\"data\":{}}`,
857
+ "- Always include at least one messages entry.",
858
+ "- Put user-visible text only in messages[].text.",
859
+ "- Use data for optional machine-readable extraction results that PrivateClaw may consume in future file-processing flows.",
860
+ "- Do not wrap the JSON in markdown fences.",
861
+ ].join("\n");
862
+ }
863
+
864
+ function parseStructuredResponseResult(raw: string): NormalizedBridgeResult | undefined {
865
+ const structured = parseStructuredResponseBlock(raw);
866
+ if (!structured?.messages || structured.messages.length === 0) {
867
+ return undefined;
868
+ }
869
+
870
+ const messages = structured.messages.flatMap((message) => {
871
+ const text = typeof message.text === "string" ? message.text.trim() : "";
872
+ return text !== "" ? [{ text }] : [];
873
+ });
874
+ if (messages.length === 0) {
787
875
  return undefined;
788
876
  }
789
877
 
790
- return parts.join("\n\n");
878
+ return {
879
+ messages,
880
+ ...combineStructuredData([{ data: structured.data }]),
881
+ };
882
+ }
883
+
884
+ function parseStructuredResponseBlock(raw: string): PrivateClawStructuredResponse | undefined {
885
+ const match = raw.match(buildStructuredResponseBlockPattern("u"));
886
+ const payload = match?.[1]?.trim();
887
+ if (!payload) {
888
+ return undefined;
889
+ }
890
+
891
+ try {
892
+ const parsed = JSON.parse(payload) as PrivateClawStructuredResponse;
893
+ if (parsed.version !== PRIVATECLAW_RESPONSE_CONTRACT_VERSION || !Array.isArray(parsed.messages)) {
894
+ return undefined;
895
+ }
896
+ return parsed;
897
+ } catch {
898
+ return undefined;
899
+ }
900
+ }
901
+
902
+ function stripStructuredResponseBlock(raw: string): string {
903
+ return raw.replace(buildStructuredResponseBlockPattern("gu"), "").trim();
904
+ }
905
+
906
+ function buildStructuredResponseBlockPattern(flags: string): RegExp {
907
+ return new RegExp(
908
+ `${escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_START)}([\\s\\S]*?)${escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_END)}`,
909
+ flags,
910
+ );
911
+ }
912
+
913
+ function escapeRegExpLiteral(value: string): string {
914
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
915
+ }
916
+
917
+ function combineStructuredData(
918
+ results: ReadonlyArray<{ data?: unknown }>,
919
+ ): { data?: unknown } {
920
+ const data = [...results]
921
+ .reverse()
922
+ .map((result) => normalizeStructuredData(result.data))
923
+ .find((candidate) => candidate !== undefined);
924
+ return data === undefined ? {} : { data };
925
+ }
926
+
927
+ function normalizeStructuredData(value: unknown): unknown | undefined {
928
+ if (value === undefined || value === null) {
929
+ return undefined;
930
+ }
931
+ if (Array.isArray(value)) {
932
+ return value.length > 0 ? value : undefined;
933
+ }
934
+ if (typeof value === "object") {
935
+ return Object.keys(value as Record<string, unknown>).length > 0 ? value : undefined;
936
+ }
937
+ return value;
938
+ }
939
+
940
+ function extractBridgeResponseData(response: BridgeResponse): unknown {
941
+ return typeof response === "string" ? undefined : response.data;
791
942
  }
792
943
 
793
944
  async function buildAttachmentFromMediaPath(mediaPath: string): Promise<PrivateClawAttachment> {
@@ -155,6 +155,7 @@ test("privateclaw command writes QR media into the OpenClaw state media director
155
155
  assert.equal(reply.isError, undefined);
156
156
  assert.ok(reply.text);
157
157
  assert.ok(reply.mediaUrl);
158
+ assert.ok(!reply.text.includes("<qqimg>"));
158
159
  assert.match(reply.text, /邀请链接 \/ Invite URI/);
159
160
  assert.match(reply.text, /PrivateClaw 会话|PrivateClaw session/);
160
161
 
@@ -177,6 +178,73 @@ test("privateclaw command writes QR media into the OpenClaw state media director
177
178
  assert.deepEqual(qrPng.subarray(0, PNG_SIGNATURE.length), PNG_SIGNATURE);
178
179
  });
179
180
 
181
+ test("privateclaw command embeds qqimg tags for QQ channel replies", async (t) => {
182
+ const relay = createRelayServer({
183
+ host: "127.0.0.1",
184
+ port: 0,
185
+ sessionTtlMs: 60_000,
186
+ frameCacheSize: 8,
187
+ });
188
+ const { port } = await relay.start();
189
+
190
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-state-"));
191
+ t.after(async () => {
192
+ await rm(stateDir, { recursive: true, force: true });
193
+ await relay.stop();
194
+ });
195
+
196
+ const plugin = createOpenClawCompatiblePlugin({
197
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
198
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
199
+ bridge: new EchoBridge("OpenClaw bridge"),
200
+ welcomeMessage: "Welcome to PrivateClaw",
201
+ });
202
+ const { api, getCommand, getService } = createMockApi();
203
+ plugin.register(api);
204
+
205
+ const service = getService();
206
+ await service.start({
207
+ config: {},
208
+ stateDir,
209
+ logger: api.logger,
210
+ });
211
+ t.after(async () => {
212
+ await service.stop?.({
213
+ config: {},
214
+ stateDir,
215
+ logger: api.logger,
216
+ });
217
+ });
218
+
219
+ const command = getCommand();
220
+ const reply = await command.handler({
221
+ channel: "qqbot",
222
+ senderId: "tester",
223
+ isAuthorizedSender: true,
224
+ commandBody: "/privateclaw",
225
+ config: {},
226
+ });
227
+
228
+ assert.equal(reply.isError, undefined);
229
+ assert.ok(reply.text);
230
+ assert.equal(reply.mediaUrl, undefined);
231
+ assert.match(reply.text, /<qqimg>[^<]+<\/qqimg>/);
232
+
233
+ const inviteUri = reply.text.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
234
+ assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
235
+ const invite = decodeInviteString(inviteUri);
236
+
237
+ const qqImagePath = reply.text.match(/<qqimg>([^<]+)<\/qqimg>/)?.[1];
238
+ assert.ok(qqImagePath, "QQ reply should embed the QR path inside <qqimg> tags");
239
+
240
+ const expectedMediaDir = path.join(stateDir, "media", "privateclaw");
241
+ assert.equal(path.dirname(qqImagePath), expectedMediaDir);
242
+ assert.equal(path.basename(qqImagePath), `privateclaw-${invite.sessionId}.png`);
243
+
244
+ const qrPng = await readFile(qqImagePath);
245
+ assert.deepEqual(qrPng.subarray(0, PNG_SIGNATURE.length), PNG_SIGNATURE);
246
+ });
247
+
180
248
  test("privateclaw plugin local pair CLI defaults to the long session TTL", async (t) => {
181
249
  const relay = createRelayServer({
182
250
  host: "127.0.0.1",
@@ -92,6 +92,7 @@ interface PrivateClawPairCliOptions {
92
92
 
93
93
  const DEFAULT_PROVIDER_LABEL = "PrivateClaw";
94
94
  const DEFAULT_BRIDGE_MODE: PrivateClawBridgeMode = "openclaw-agent";
95
+ const QQ_INLINE_IMAGE_REPLY_CHANNELS = new Set(["qqbot", "qq", "qqguild", "qq-guild"]);
95
96
  const ALLOWED_THINKING_LEVELS = new Set<OpenClawThinkingLevel>([
96
97
  "off",
97
98
  "minimal",
@@ -109,6 +110,27 @@ function readString(value: unknown): string | undefined {
109
110
  return trimmed === "" ? undefined : trimmed;
110
111
  }
111
112
 
113
+ function channelRequiresInlineImageReply(channel?: string): boolean {
114
+ const normalized = readString(channel)?.toLowerCase();
115
+ return normalized != null && QQ_INLINE_IMAGE_REPLY_CHANNELS.has(normalized);
116
+ }
117
+
118
+ function buildCommandReplyText(params: {
119
+ announcementText: string;
120
+ inviteUri: string;
121
+ channel: string | undefined;
122
+ qrImagePath: string;
123
+ }): string {
124
+ const baseText =
125
+ `${params.announcementText}\n\n${PRIVATECLAW_INVITE_URI_LABEL}:\n${params.inviteUri}`;
126
+ if (!channelRequiresInlineImageReply(params.channel)) {
127
+ return baseText;
128
+ }
129
+
130
+ // QQ command replies expand images from inline <qqimg> tags instead of mediaUrl payloads.
131
+ return `${baseText}\n\n<qqimg>${params.qrImagePath}</qqimg>`;
132
+ }
133
+
112
134
  function readNumber(value: unknown): number | undefined {
113
135
  if (typeof value === "number" && Number.isFinite(value)) {
114
136
  return value;
@@ -391,9 +413,21 @@ class PrivateClawPluginRuntime {
391
413
  );
392
414
  }
393
415
 
394
- async buildCommandReply(bundle: PrivateClawInviteBundle): Promise<ReplyPayloadCompat> {
395
- const text = `${bundle.announcementText}\n\n${PRIVATECLAW_INVITE_URI_LABEL}:\n${bundle.inviteUri}`;
416
+ async buildCommandReply(
417
+ bundle: PrivateClawInviteBundle,
418
+ channel?: string,
419
+ ): Promise<ReplyPayloadCompat> {
396
420
  const qrPng = await writeInviteQrPng(bundle, this.getMediaDir());
421
+ const text = buildCommandReplyText({
422
+ announcementText: bundle.announcementText,
423
+ inviteUri: bundle.inviteUri,
424
+ channel,
425
+ qrImagePath: qrPng.pngPath,
426
+ });
427
+ if (channelRequiresInlineImageReply(channel)) {
428
+ return { text };
429
+ }
430
+
397
431
  return {
398
432
  text,
399
433
  mediaUrl: process.platform === "win32" ? qrPng.pngFileUrl : qrPng.pngPath,
@@ -475,7 +509,7 @@ function createPluginDefinition(
475
509
  api.logger.info(
476
510
  `[privateclaw] invite created for session ${bundle.invite.sessionId} on ${ctx.channel}`,
477
511
  );
478
- const reply = await runtime.buildCommandReply(bundle);
512
+ const reply = await runtime.buildCommandReply(bundle, ctx.channel);
479
513
  api.logger.info(
480
514
  `[privateclaw] QR image prepared for session ${bundle.invite.sessionId}`,
481
515
  );
@@ -11,6 +11,8 @@ import { createRelayServer } from "../../../services/relay-server/src/relay-serv
11
11
  import { EchoBridge } from "./bridges/echo-bridge.js";
12
12
  import { DEFAULT_SESSION_TTL_MS, PrivateClawProvider } from "./provider.js";
13
13
 
14
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
15
+
14
16
  function waitForOpen(socket: WebSocket): Promise<void> {
15
17
  return new Promise((resolve, reject) => {
16
18
  socket.once("open", () => resolve());
@@ -204,6 +206,10 @@ test("provider creates one-time invites and replies through the encrypted relay"
204
206
  JSON.stringify(capabilities.commands),
205
207
  /renew-session/,
206
208
  );
209
+ assert.match(
210
+ JSON.stringify(capabilities.commands),
211
+ /session-qr/,
212
+ );
207
213
 
208
214
  appSocket.send(
209
215
  JSON.stringify({
@@ -229,6 +235,130 @@ test("provider creates one-time invites and replies through the encrypted relay"
229
235
  await waitForClose(appSocket);
230
236
  });
231
237
 
238
+ test("provider returns the current session QR only to the requesting participant", async (t) => {
239
+ const relay = createRelayServer({
240
+ host: "127.0.0.1",
241
+ port: 0,
242
+ sessionTtlMs: 60_000,
243
+ frameCacheSize: 8,
244
+ });
245
+ const { port } = await relay.start();
246
+ t.after(async () => {
247
+ await relay.stop();
248
+ });
249
+
250
+ const provider = new PrivateClawProvider({
251
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
252
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
253
+ bridge: new GroupBridge(),
254
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
255
+ });
256
+ await provider.connect();
257
+ t.after(async () => {
258
+ await provider.dispose();
259
+ });
260
+
261
+ const inviteBundle = await provider.createInviteBundle({ groupMode: true });
262
+ const invite = decodeInviteString(inviteBundle.inviteUri);
263
+
264
+ const appOneUrl = new URL(invite.appWsUrl);
265
+ appOneUrl.searchParams.set("appId", "app-one");
266
+ const appOne = new WebSocket(appOneUrl.toString());
267
+ const appOneAttached = nextMessage(appOne);
268
+ await waitForOpen(appOne);
269
+ assert.equal((await appOneAttached).type, "relay:attached");
270
+ const appOneInitialFrames = nextMessages(appOne, 3);
271
+ appOne.send(
272
+ JSON.stringify({
273
+ type: "app:frame",
274
+ envelope: encryptPayload({
275
+ sessionId: invite.sessionId,
276
+ sessionKey: invite.sessionKey,
277
+ payload: {
278
+ kind: "client_hello",
279
+ appId: "app-one",
280
+ displayName: "SolarFox",
281
+ appVersion: "flutter-test",
282
+ deviceLabel: "Tester One",
283
+ sentAt: new Date().toISOString(),
284
+ },
285
+ }),
286
+ }),
287
+ );
288
+ await appOneInitialFrames;
289
+
290
+ const appTwoUrl = new URL(invite.appWsUrl);
291
+ appTwoUrl.searchParams.set("appId", "app-two");
292
+ const appTwo = new WebSocket(appTwoUrl.toString());
293
+ const appTwoAttached = nextMessage(appTwo);
294
+ await waitForOpen(appTwo);
295
+ assert.equal((await appTwoAttached).type, "relay:attached");
296
+ const appTwoInitialFrames = nextMessages(appTwo, 3);
297
+ const appOneJoinFrames = nextMessages(appOne, 2);
298
+ appTwo.send(
299
+ JSON.stringify({
300
+ type: "app:frame",
301
+ envelope: encryptPayload({
302
+ sessionId: invite.sessionId,
303
+ sessionKey: invite.sessionKey,
304
+ payload: {
305
+ kind: "client_hello",
306
+ appId: "app-two",
307
+ displayName: "RiverCat",
308
+ appVersion: "flutter-test",
309
+ deviceLabel: "Tester Two",
310
+ sentAt: new Date().toISOString(),
311
+ },
312
+ }),
313
+ }),
314
+ );
315
+ await Promise.all([appTwoInitialFrames, appOneJoinFrames]);
316
+
317
+ const appOneQrFramesPromise = nextMessages(appOne, 1);
318
+ appOne.send(
319
+ JSON.stringify({
320
+ type: "app:frame",
321
+ envelope: encryptPayload({
322
+ sessionId: invite.sessionId,
323
+ sessionKey: invite.sessionKey,
324
+ payload: {
325
+ kind: "user_message",
326
+ appId: "app-one",
327
+ text: "/session-qr",
328
+ clientMessageId: "session-qr-1",
329
+ sentAt: new Date().toISOString(),
330
+ },
331
+ }),
332
+ }),
333
+ );
334
+
335
+ const [appOneQrFrames] = await Promise.all([
336
+ appOneQrFramesPromise,
337
+ waitForNoMessage(appTwo),
338
+ ]);
339
+ const qrPayload = decryptRelayPayload(appOneQrFrames[0]!, invite);
340
+ assert.equal(qrPayload.kind, "assistant_message");
341
+ assert.equal(qrPayload.replyTo, "session-qr-1");
342
+ assert.match(qrPayload.text, /二维码|QR/i);
343
+ assert.equal(qrPayload.attachments?.length, 1);
344
+ const qrAttachment = qrPayload.attachments?.[0];
345
+ assert.ok(qrAttachment);
346
+ assert.equal(qrAttachment.mimeType, "image/png");
347
+ assert.equal(qrAttachment.name, `privateclaw-${invite.sessionId}.png`);
348
+ assert.ok(qrAttachment.dataBase64);
349
+ assert.deepEqual(
350
+ Buffer.from(qrAttachment.dataBase64, "base64").subarray(
351
+ 0,
352
+ PNG_SIGNATURE.length,
353
+ ),
354
+ PNG_SIGNATURE,
355
+ );
356
+
357
+ appOne.close();
358
+ appTwo.close();
359
+ await Promise.all([waitForClose(appOne), waitForClose(appTwo)]);
360
+ });
361
+
232
362
  test("provider renews the session key and keeps the chat usable after re-handshake", async (t) => {
233
363
  const relay = createRelayServer({
234
364
  host: "127.0.0.1",