@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
@@ -168,6 +168,31 @@ function coerceText(value: string | Buffer | null | undefined): string {
168
168
  return "";
169
169
  }
170
170
 
171
+ function looksLikeJsonPayload(value: string): boolean {
172
+ const trimmed = value.trimStart();
173
+ return trimmed.startsWith("{") || trimmed.startsWith("[") || trimmed.startsWith('"');
174
+ }
175
+
176
+ function looksLikeHtmlPayload(value: string): boolean {
177
+ const trimmed = value.trimStart().toLowerCase();
178
+ return trimmed.startsWith("<!doctype html") || trimmed.startsWith("<html") || trimmed.startsWith("<body");
179
+ }
180
+
181
+ function looksLikeWhisperHelpText(value: string): boolean {
182
+ const trimmed = value.trim();
183
+ if (trimmed === "") {
184
+ return false;
185
+ }
186
+ return (
187
+ /(?:^|\n)\s*usage:\s*(?:(?:python(?:\d+(?:\.\d+)*)?(?:\s+-m)?)\s+)?(?:openai-)?whisper\b/iu.test(
188
+ trimmed,
189
+ ) ||
190
+ (/--model\b/iu.test(trimmed) &&
191
+ /--output_(?:dir|format)\b/iu.test(trimmed) &&
192
+ /--(?:language|task)\b/iu.test(trimmed))
193
+ );
194
+ }
195
+
171
196
  function truncateLogDetail(value: string, maxLength = 300): string {
172
197
  return value.length > maxLength ? `${value.slice(0, maxLength)}...` : value;
173
198
  }
@@ -218,25 +243,75 @@ function execFileText(
218
243
  });
219
244
  }
220
245
 
221
- function parseWhisperTranscriptJson(payload: string): string | null {
222
- const parsed = JSON.parse(payload) as {
223
- text?: unknown;
224
- segments?: Array<{ text?: unknown }>;
225
- };
226
- const directText = readString(parsed.text);
227
- if (directText) {
228
- return directText;
229
- }
230
- const segmentText = Array.isArray(parsed.segments)
231
- ? parsed.segments.flatMap((segment) => {
232
- const value = readString(segment?.text);
233
- return value ? [value] : [];
234
- })
235
- : [];
236
- const combined = segmentText.join("").trim();
246
+ function combineTranscriptFragments(fragments: ReadonlyArray<string>): string | null {
247
+ const combined = fragments.join("").trim();
237
248
  return combined === "" ? null : combined;
238
249
  }
239
250
 
251
+ function extractTranscriptText(value: unknown, depth = 0): string | null {
252
+ if (depth > 6 || value == null) {
253
+ return null;
254
+ }
255
+ if (typeof value === "string") {
256
+ return readString(value) ?? null;
257
+ }
258
+ if (Array.isArray(value)) {
259
+ const fragments = value.flatMap((entry) => {
260
+ const transcript = extractTranscriptText(entry, depth + 1);
261
+ return transcript ? [transcript] : [];
262
+ });
263
+ return combineTranscriptFragments(fragments);
264
+ }
265
+ if (typeof value !== "object") {
266
+ return null;
267
+ }
268
+ const parsed = value as Record<string, unknown>;
269
+ for (const key of ["text", "transcript", "output_text"] as const) {
270
+ const directText = readString(parsed[key]);
271
+ if (directText) {
272
+ return directText;
273
+ }
274
+ }
275
+ for (const key of ["segments", "content", "results", "alternatives"] as const) {
276
+ const transcript = extractTranscriptText(parsed[key], depth + 1);
277
+ if (transcript) {
278
+ return transcript;
279
+ }
280
+ }
281
+ for (const key of ["result", "data", "response", "output", "message"] as const) {
282
+ const transcript = extractTranscriptText(parsed[key], depth + 1);
283
+ if (transcript) {
284
+ return transcript;
285
+ }
286
+ }
287
+ return null;
288
+ }
289
+
290
+ function parseTranscriptJsonPayload(payload: string): string | null {
291
+ return extractTranscriptText(JSON.parse(payload) as unknown);
292
+ }
293
+
294
+ function parseTranscriptionResponsePayload(params: {
295
+ payload: string;
296
+ contentType?: string | null;
297
+ }): string | null {
298
+ const trimmedPayload = params.payload.trim();
299
+ if (trimmedPayload === "") {
300
+ return null;
301
+ }
302
+ const normalizedContentType = params.contentType?.toLowerCase() ?? "";
303
+ if (
304
+ normalizedContentType.includes("json") ||
305
+ looksLikeJsonPayload(trimmedPayload)
306
+ ) {
307
+ return parseTranscriptJsonPayload(trimmedPayload);
308
+ }
309
+ if (looksLikeHtmlPayload(trimmedPayload)) {
310
+ return null;
311
+ }
312
+ return trimmedPayload;
313
+ }
314
+
240
315
  function buildWhisperOutputFilePath(outputDir: string, fileName: string): string {
241
316
  return path.join(
242
317
  outputDir,
@@ -311,6 +386,7 @@ export function resolvePrivateClawWhisperCliConfig(params?: {
311
386
  spawnSyncImpl?: typeof spawnSync;
312
387
  }): PrivateClawWhisperCliConfig | undefined {
313
388
  const env = params?.env ?? process.env;
389
+ const probeEnv = params?.env ? { ...process.env, ...params.env } : env;
314
390
  const command =
315
391
  readString(params?.command) ??
316
392
  readString(env.PRIVATECLAW_WHISPER_BIN) ??
@@ -319,14 +395,15 @@ export function resolvePrivateClawWhisperCliConfig(params?: {
319
395
  const probe = spawnSyncImpl(command, ["--help"], {
320
396
  encoding: "utf8",
321
397
  stdio: "pipe",
322
- timeout: 10_000,
323
- env,
398
+ timeout: 30_000,
399
+ env: probeEnv,
400
+ windowsHide: true,
324
401
  });
325
- if (probe.error) {
402
+ if (probe.error || probe.signal) {
326
403
  return undefined;
327
404
  }
328
405
  const helpText = `${coerceText(probe.stdout)}\n${coerceText(probe.stderr)}`;
329
- if ((probe.status ?? 1) !== 0 || !/usage:\s*whisper\b/iu.test(helpText)) {
406
+ if (!looksLikeWhisperHelpText(helpText)) {
330
407
  return undefined;
331
408
  }
332
409
  const model =
@@ -386,8 +463,24 @@ async function transcribeSingleAttachment(params: {
386
463
  );
387
464
  }
388
465
 
389
- const result = (await response.json()) as { text?: string };
390
- const transcript = result.text?.trim() || null;
466
+ const responsePayload = await response.text();
467
+ let transcript: string | null;
468
+ try {
469
+ transcript = parseTranscriptionResponsePayload({
470
+ payload: responsePayload,
471
+ contentType: response.headers.get("content-type"),
472
+ });
473
+ } catch (error) {
474
+ const detail = error instanceof Error ? error.message : String(error);
475
+ throw new Error(
476
+ `STT returned an unreadable transcript payload for ${fileName}: ${truncateLogDetail(detail)}`,
477
+ );
478
+ }
479
+ if (!transcript) {
480
+ throw new Error(
481
+ `STT returned HTTP ${response.status} without transcript text for ${fileName}: ${truncateLogDetail(responsePayload)}`,
482
+ );
483
+ }
391
484
  params.onLog?.(
392
485
  `[stt] transcribe_complete session=${params.request.sessionId} request=${params.request.requestId} file=${JSON.stringify(fileName)} transcriptChars=${transcript?.length ?? 0}`,
393
486
  );
@@ -444,7 +537,7 @@ async function transcribeSingleAttachmentWithWhisperCli(params: {
444
537
  maxBuffer: 64 * 1024 * 1024,
445
538
  });
446
539
  const transcriptPayload = await readFile(outputPath, "utf8");
447
- const transcript = parseWhisperTranscriptJson(transcriptPayload);
540
+ const transcript = parseTranscriptJsonPayload(transcriptPayload);
448
541
  params.onLog?.(
449
542
  `[stt] whisper_transcribe_complete session=${params.request.sessionId} request=${params.request.requestId} file=${JSON.stringify(fileName)} transcriptChars=${transcript?.length ?? 0}`,
450
543
  );
@@ -408,6 +408,160 @@ test("parseOpenClawAgentOutput tolerates malformed closing tags and qqimg markup
408
408
  assert.equal(attachment.dataBase64, imageBytes.toString("base64"));
409
409
  });
410
410
 
411
+ test("parseOpenClawAgentOutput extracts qqfile markup into standard attachments", async (t) => {
412
+ const workspaceDir = await fs.mkdtemp(path.join(os.tmpdir(), "privateclaw-structured-workspace-"));
413
+ const mediaDir = await fs.mkdtemp(path.join(os.tmpdir(), "privateclaw-structured-media-"));
414
+ const filePath = path.join(mediaDir, "report.pdf");
415
+ const fileBytes = Buffer.from("%PDF-privateclaw-test");
416
+ await fs.writeFile(filePath, fileBytes);
417
+ t.after(async () => {
418
+ await Promise.all([
419
+ fs.rm(workspaceDir, { recursive: true, force: true }),
420
+ fs.rm(mediaDir, { recursive: true, force: true }),
421
+ ]);
422
+ });
423
+
424
+ const result = parseOpenClawAgentOutput(
425
+ JSON.stringify({
426
+ status: "ok",
427
+ result: {
428
+ payloads: [
429
+ {
430
+ text: [
431
+ "<privateclaw-response>",
432
+ JSON.stringify({
433
+ version: 1,
434
+ messages: [
435
+ {
436
+ text: `这是你要的文档\n\n<qqfile>${filePath}</qqfile>\n\n请查收。`,
437
+ },
438
+ ],
439
+ data: {},
440
+ }),
441
+ "</privateclaw-response>",
442
+ ].join("\n"),
443
+ },
444
+ ],
445
+ },
446
+ }),
447
+ { workspaceDir },
448
+ );
449
+
450
+ if (typeof result === "string") {
451
+ assert.fail("Expected an attachment-bearing bridge response.");
452
+ }
453
+ const [message] = result.messages;
454
+ assert(message && typeof message !== "string");
455
+ assert.equal(message.text, "这是你要的文档\n\n请查收。");
456
+ const [attachment] = message.attachments ?? [];
457
+ assert(attachment);
458
+ assert.match(attachment.id, /^structured-attachment-/u);
459
+ assert.equal(attachment.name, "report.pdf");
460
+ assert.equal(attachment.mimeType, "application/pdf");
461
+ assert.equal(attachment.sizeBytes, fileBytes.byteLength);
462
+ assert.equal(attachment.dataBase64, fileBytes.toString("base64"));
463
+ });
464
+
465
+ test("parseOpenClawAgentOutput extracts qqfile markup from plain-text fallbacks", async (t) => {
466
+ const workspaceDir = await fs.mkdtemp(path.join(os.tmpdir(), "privateclaw-plain-workspace-"));
467
+ const mediaDir = await fs.mkdtemp(path.join(os.tmpdir(), "privateclaw-plain-media-"));
468
+ const filePath = path.join(mediaDir, "notes.txt");
469
+ const fileBytes = Buffer.from("plain-fallback-file");
470
+ await fs.writeFile(filePath, fileBytes);
471
+ t.after(async () => {
472
+ await Promise.all([
473
+ fs.rm(workspaceDir, { recursive: true, force: true }),
474
+ fs.rm(mediaDir, { recursive: true, force: true }),
475
+ ]);
476
+ });
477
+
478
+ const result = parseOpenClawAgentOutput(
479
+ JSON.stringify({
480
+ status: "ok",
481
+ result: {
482
+ payloads: [
483
+ {
484
+ text: `这是 plain fallback\n\n<qqfile>${filePath}</qqfile>\n\n已经附上。`,
485
+ },
486
+ ],
487
+ },
488
+ }),
489
+ { workspaceDir },
490
+ );
491
+
492
+ if (typeof result === "string") {
493
+ assert.fail("Expected an attachment-bearing bridge response.");
494
+ }
495
+ const [message] = result.messages;
496
+ assert(message && typeof message !== "string");
497
+ assert.equal(message.text, "这是 plain fallback\n\n已经附上。");
498
+ const [attachment] = message.attachments ?? [];
499
+ assert(attachment);
500
+ assert.equal(attachment.name, "notes.txt");
501
+ assert.equal(attachment.mimeType, "text/plain");
502
+ assert.equal(attachment.sizeBytes, fileBytes.byteLength);
503
+ assert.equal(attachment.dataBase64, fileBytes.toString("base64"));
504
+ });
505
+
506
+ test("parseOpenClawAgentOutput preserves mixed qqimg and qqfile markup in order", async (t) => {
507
+ const workspaceDir = await fs.mkdtemp(path.join(os.tmpdir(), "privateclaw-mixed-workspace-"));
508
+ const filePath = path.join(workspaceDir, "manual.txt");
509
+ const fileBytes = Buffer.from("mixed-inline-file");
510
+ await fs.writeFile(filePath, fileBytes);
511
+ t.after(async () => {
512
+ await fs.rm(workspaceDir, { recursive: true, force: true });
513
+ });
514
+
515
+ const result = parseOpenClawAgentOutput(
516
+ JSON.stringify({
517
+ status: "ok",
518
+ result: {
519
+ payloads: [
520
+ {
521
+ text: [
522
+ "先看图",
523
+ "<qqimg>https://example.com/bridge.png</qqimg>",
524
+ "再收文件",
525
+ `<qqfile>${filePath}</qqfile>`,
526
+ ].join("\n\n"),
527
+ },
528
+ ],
529
+ },
530
+ }),
531
+ { workspaceDir },
532
+ );
533
+
534
+ if (typeof result === "string") {
535
+ assert.fail("Expected an attachment-bearing bridge response.");
536
+ }
537
+ const [message] = result.messages;
538
+ assert(message && typeof message !== "string");
539
+ assert.equal(message.text, "先看图\n\n再收文件");
540
+ assert.equal(message.attachments?.length, 2);
541
+ assert.deepEqual(
542
+ message.attachments?.map((attachment) => ({
543
+ name: attachment.name,
544
+ mimeType: attachment.mimeType,
545
+ uri: attachment.uri,
546
+ dataBase64: attachment.dataBase64,
547
+ })),
548
+ [
549
+ {
550
+ name: "bridge.png",
551
+ mimeType: "image/png",
552
+ uri: "https://example.com/bridge.png",
553
+ dataBase64: undefined,
554
+ },
555
+ {
556
+ name: "manual.txt",
557
+ mimeType: "text/plain",
558
+ uri: undefined,
559
+ dataBase64: fileBytes.toString("base64"),
560
+ },
561
+ ],
562
+ );
563
+ });
564
+
411
565
  test("OpenClawAgentBridge invokes openclaw agent with session-aware arguments", async () => {
412
566
  let invokedFile = "";
413
567
  let invokedArgs: string[] = [];
@@ -288,11 +288,16 @@ function extractDisplayResult(
288
288
 
289
289
  const messages =
290
290
  payloads.flatMap((payload) =>
291
- [payload.text, payload.message, payload.summary].flatMap((candidate) =>
292
- typeof candidate === "string" && stripStructuredResponseBlock(candidate) !== ""
293
- ? [{ text: stripStructuredResponseBlock(candidate) }]
294
- : [],
295
- ),
291
+ [payload.text, payload.message, payload.summary].flatMap((candidate) => {
292
+ if (typeof candidate !== "string") {
293
+ return [];
294
+ }
295
+ const normalized = normalizePlainBridgeTextMessage(
296
+ candidate,
297
+ options?.workspaceDir ? { workspaceDir: options.workspaceDir } : undefined,
298
+ );
299
+ return normalized ? [normalized] : [];
300
+ }),
296
301
  ) ?? [];
297
302
 
298
303
  if (messages.length === 0) {
@@ -1314,9 +1319,12 @@ function extractAssistantDisplayResult(
1314
1319
  return { result: structuredResult, isStructured: true };
1315
1320
  }
1316
1321
 
1317
- const fallbackText = stripStructuredResponseBlock(rawText);
1318
- return fallbackText !== ""
1319
- ? { result: { messages: [{ text: fallbackText }] }, isStructured: false }
1322
+ const fallbackMessage = normalizePlainBridgeTextMessage(
1323
+ rawText,
1324
+ options?.workspaceDir ? { workspaceDir: options.workspaceDir } : undefined,
1325
+ );
1326
+ return fallbackMessage
1327
+ ? { result: { messages: [fallbackMessage] }, isStructured: false }
1320
1328
  : { result: { messages: [] }, isStructured: false };
1321
1329
  }
1322
1330
 
@@ -1357,7 +1365,7 @@ function buildStructuredResponseContractPrompt(): string {
1357
1365
  "- To send images/files, add an attachments array to the message: {\"text\":\"...\",\"attachments\":[{\"name\":\"file.png\",\"mimeType\":\"image/png\",\"filePath\":\"relative/path/in/current/workspace/or/absolute/local/path\"}]}",
1358
1366
  "- Or use dataBase64 for inline binary: {\"name\":\"file.png\",\"mimeType\":\"image/png\",\"dataBase64\":\"...\"}",
1359
1367
  "- Never put attachments at the top level of the response object. Files must live inside messages[].attachments.",
1360
- "- Never put channel-specific markup such as <qqimg>...</qqimg>, markdown image syntax, or raw local file paths inside messages[].text. Put files only in messages[].attachments.",
1368
+ "- Never put channel-specific markup such as <qqimg>...</qqimg>, <qqvoice>...</qqvoice>, <qqvideo>...</qqvideo>, or <qqfile>...</qqfile>, markdown image syntax, or raw local file paths inside messages[].text. Put files only in messages[].attachments.",
1361
1369
  "- Use data for optional machine-readable extraction results that PrivateClaw may consume in future file-processing flows.",
1362
1370
  "- Do not wrap the JSON in markdown fences.",
1363
1371
  ].join("\n");
@@ -1437,14 +1445,14 @@ function parseStructuredResponseResult(
1437
1445
  const messages: NormalizedBridgeMessage[] = [];
1438
1446
  for (const message of structured.messages ?? []) {
1439
1447
  const text = typeof message.text === "string" ? message.text.trim() : "";
1440
- const qqimgResult = extractInlineQqimgAttachments(text, options);
1448
+ const qqMediaResult = extractInlineQqMediaAttachments(text, options);
1441
1449
  const attachments = [
1442
1450
  ...resolveStructuredAttachments(message.attachments, options),
1443
- ...qqimgResult.attachments,
1451
+ ...qqMediaResult.attachments,
1444
1452
  ];
1445
- if (qqimgResult.text !== "" || attachments.length > 0) {
1453
+ if (qqMediaResult.text !== "" || attachments.length > 0) {
1446
1454
  messages.push({
1447
- text: qqimgResult.text,
1455
+ text: qqMediaResult.text,
1448
1456
  ...(attachments.length > 0 ? { attachments } : {}),
1449
1457
  });
1450
1458
  }
@@ -1516,7 +1524,31 @@ function extractStructuredResponsePayload(raw: string): string | undefined {
1516
1524
  return undefined;
1517
1525
  }
1518
1526
 
1519
- function extractInlineQqimgAttachments(
1527
+ function normalizePlainBridgeTextMessage(
1528
+ rawText: string,
1529
+ options?: {
1530
+ workspaceDir?: string;
1531
+ },
1532
+ ): NormalizedBridgeMessage | undefined {
1533
+ const strippedText = stripStructuredResponseBlock(rawText);
1534
+ if (strippedText === "") {
1535
+ return undefined;
1536
+ }
1537
+
1538
+ const mediaResult = extractInlineQqMediaAttachments(strippedText, options);
1539
+ if (mediaResult.text === "" && mediaResult.attachments.length === 0) {
1540
+ return undefined;
1541
+ }
1542
+
1543
+ return {
1544
+ text: mediaResult.text,
1545
+ ...(mediaResult.attachments.length > 0
1546
+ ? { attachments: mediaResult.attachments }
1547
+ : {}),
1548
+ };
1549
+ }
1550
+
1551
+ export function extractInlineQqMediaAttachments(
1520
1552
  text: string,
1521
1553
  options?: {
1522
1554
  workspaceDir?: string;
@@ -1525,17 +1557,28 @@ function extractInlineQqimgAttachments(
1525
1557
  text: string;
1526
1558
  attachments: PrivateClawAttachment[];
1527
1559
  } {
1528
- if (!text.includes("<qqimg>")) {
1560
+ if (!text.includes("<qq")) {
1529
1561
  return { text, attachments: [] };
1530
1562
  }
1531
1563
 
1532
1564
  const attachments: PrivateClawAttachment[] = [];
1533
- for (const match of text.matchAll(/<qqimg>([\s\S]*?)<\/qqimg>/giu)) {
1534
- const rawValue = match[1]?.trim();
1535
- if (!rawValue) {
1565
+ const mediaTagPattern = /<(qqimg|qqvoice|qqvideo|qqfile)>([\s\S]*?)<\/(?:qqimg|qqvoice|qqvideo|qqfile|img)>/giu;
1566
+ for (const match of text.matchAll(mediaTagPattern)) {
1567
+ const rawTagName = match[1]?.trim().toLowerCase();
1568
+ const rawValue = match[2]?.trim();
1569
+ if (
1570
+ !rawTagName ||
1571
+ !isInlineQqMediaTag(rawTagName) ||
1572
+ !rawValue ||
1573
+ rawValue === ""
1574
+ ) {
1536
1575
  continue;
1537
1576
  }
1538
- const attachment = resolveInlineQqimgAttachment(rawValue, options);
1577
+ const attachment = resolveInlineQqMediaAttachment(
1578
+ rawValue,
1579
+ rawTagName,
1580
+ options,
1581
+ );
1539
1582
  if (attachment) {
1540
1583
  attachments.push(attachment);
1541
1584
  }
@@ -1543,15 +1586,40 @@ function extractInlineQqimgAttachments(
1543
1586
 
1544
1587
  return {
1545
1588
  text: text
1546
- .replace(/<qqimg>[\s\S]*?<\/qqimg>/giu, "")
1589
+ .replace(mediaTagPattern, "")
1547
1590
  .replace(/\n{3,}/gu, "\n\n")
1548
1591
  .trim(),
1549
1592
  attachments,
1550
1593
  };
1551
1594
  }
1552
1595
 
1553
- function resolveInlineQqimgAttachment(
1596
+ function isInlineQqMediaTag(value: string): value is "qqimg" | "qqvoice" | "qqvideo" | "qqfile" {
1597
+ return value === "qqimg" || value === "qqvoice" || value === "qqvideo" || value === "qqfile";
1598
+ }
1599
+
1600
+ function inferInlineQqMediaMimeType(
1601
+ fileName: string,
1602
+ tagName: "qqimg" | "qqvoice" | "qqvideo" | "qqfile",
1603
+ ): string {
1604
+ const inferred = inferMimeTypeFromFileName(fileName);
1605
+ if (inferred) {
1606
+ return inferred;
1607
+ }
1608
+ switch (tagName) {
1609
+ case "qqimg":
1610
+ return "image/*";
1611
+ case "qqvoice":
1612
+ return "audio/*";
1613
+ case "qqvideo":
1614
+ return "video/*";
1615
+ case "qqfile":
1616
+ return GENERIC_BINARY_MIME;
1617
+ }
1618
+ }
1619
+
1620
+ function resolveInlineQqMediaAttachment(
1554
1621
  rawValue: string,
1622
+ tagName: "qqimg" | "qqvoice" | "qqvideo" | "qqfile",
1555
1623
  options?: {
1556
1624
  workspaceDir?: string;
1557
1625
  },
@@ -1564,10 +1632,11 @@ function resolveInlineQqimgAttachment(
1564
1632
  if (parsedUrl.protocol === "file:") {
1565
1633
  const filePath = fileURLToPath(parsedUrl);
1566
1634
  const fileBytes = readFileSync(filePath);
1635
+ const fileName = path.basename(filePath) || "attachment";
1567
1636
  return {
1568
1637
  id: `structured-attachment-${randomUUID()}`,
1569
- name: path.basename(filePath) || "attachment",
1570
- mimeType: inferMimeTypeFromFileName(filePath) ?? GENERIC_BINARY_MIME,
1638
+ name: fileName,
1639
+ mimeType: inferInlineQqMediaMimeType(fileName, tagName),
1571
1640
  sizeBytes: fileBytes.byteLength,
1572
1641
  dataBase64: fileBytes.toString("base64"),
1573
1642
  };
@@ -1576,7 +1645,7 @@ function resolveInlineQqimgAttachment(
1576
1645
  return {
1577
1646
  id: `structured-attachment-${randomUUID()}`,
1578
1647
  name: fileName,
1579
- mimeType: inferMimeTypeFromFileName(fileName) ?? GENERIC_BINARY_MIME,
1648
+ mimeType: inferInlineQqMediaMimeType(fileName, tagName),
1580
1649
  sizeBytes: 0,
1581
1650
  uri: parsedUrl.toString(),
1582
1651
  };
@@ -1591,10 +1660,11 @@ function resolveInlineQqimgAttachment(
1591
1660
  return undefined;
1592
1661
  }
1593
1662
  const fileBytes = readFileSync(filePath);
1663
+ const fileName = path.basename(filePath) || "attachment";
1594
1664
  return {
1595
1665
  id: `structured-attachment-${randomUUID()}`,
1596
- name: path.basename(filePath) || "attachment",
1597
- mimeType: inferMimeTypeFromFileName(filePath) ?? GENERIC_BINARY_MIME,
1666
+ name: fileName,
1667
+ mimeType: inferInlineQqMediaMimeType(fileName, tagName),
1598
1668
  sizeBytes: fileBytes.byteLength,
1599
1669
  dataBase64: fileBytes.toString("base64"),
1600
1670
  };
@@ -1865,7 +1935,7 @@ function resolveAttachmentMimeType(attachment: PrivateClawAttachment): string {
1865
1935
  return inferMimeTypeFromFileName(attachment.name) ?? (explicitMimeType || GENERIC_BINARY_MIME);
1866
1936
  }
1867
1937
 
1868
- function inferMimeTypeFromFileName(fileName: string): string | undefined {
1938
+ export function inferMimeTypeFromFileName(fileName: string): string | undefined {
1869
1939
  const extension = getFileExtension(fileName);
1870
1940
  switch (extension) {
1871
1941
  case "png":
package/src/channel.ts ADDED
@@ -0,0 +1,130 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ OpenClawChannelPluginCompat,
4
+ OpenClawOutboundDeliveryResultCompat,
5
+ ReplyPayloadCompat,
6
+ } from "./compat/openclaw.js";
7
+ import type { PrivateClawOpenClawOutboundMessage } from "./types.js";
8
+
9
+ export const PRIVATECLAW_OPENCLAW_CHANNEL_ID = "privateclaw";
10
+ export const PRIVATECLAW_OPENCLAW_ACCOUNT_ID = "default";
11
+
12
+ interface PrivateClawVirtualAccount {
13
+ accountId: string;
14
+ name: string;
15
+ enabled: true;
16
+ configured: true;
17
+ }
18
+
19
+ function resolvePrivateClawAccountId(accountId?: string | null): string {
20
+ const normalized = accountId?.trim();
21
+ return normalized ? normalized : PRIVATECLAW_OPENCLAW_ACCOUNT_ID;
22
+ }
23
+
24
+ function toOutboundMessage(
25
+ payload: ReplyPayloadCompat,
26
+ ): PrivateClawOpenClawOutboundMessage {
27
+ return {
28
+ ...(payload.text?.trim() ? { text: payload.text.trim() } : {}),
29
+ ...(payload.mediaUrl?.trim() ? { mediaUrl: payload.mediaUrl.trim() } : {}),
30
+ ...(payload.mediaUrls?.length ? { mediaUrls: payload.mediaUrls } : {}),
31
+ ...(typeof payload.replyToId === "string" || payload.replyToId === null
32
+ ? { replyToId: payload.replyToId }
33
+ : {}),
34
+ };
35
+ }
36
+
37
+ function buildDeliveryResult(
38
+ sessionId: string,
39
+ ): OpenClawOutboundDeliveryResultCompat {
40
+ return {
41
+ channel: PRIVATECLAW_OPENCLAW_CHANNEL_ID,
42
+ messageId: `privateclaw-outbound-${randomUUID()}`,
43
+ chatId: sessionId,
44
+ timestamp: Date.now(),
45
+ };
46
+ }
47
+
48
+ export function createPrivateClawChannelPlugin(params: {
49
+ deliverOutboundMessage(
50
+ sessionId: string,
51
+ payload: PrivateClawOpenClawOutboundMessage,
52
+ ): Promise<void>;
53
+ }): OpenClawChannelPluginCompat<PrivateClawVirtualAccount> {
54
+ return {
55
+ id: PRIVATECLAW_OPENCLAW_CHANNEL_ID,
56
+ meta: {
57
+ id: PRIVATECLAW_OPENCLAW_CHANNEL_ID,
58
+ label: "PrivateClaw",
59
+ selectionLabel: "PrivateClaw",
60
+ docsPath: "https://privateclaw.us",
61
+ docsLabel: "PrivateClaw docs",
62
+ blurb:
63
+ "Routes paired PrivateClaw app conversations back through the encrypted relay session.",
64
+ showConfigured: false,
65
+ quickstartAllowFrom: false,
66
+ preferSessionLookupForAnnounceTarget: true,
67
+ },
68
+ capabilities: {
69
+ chatTypes: ["direct", "group"],
70
+ reply: true,
71
+ threads: false,
72
+ media: true,
73
+ nativeCommands: false,
74
+ },
75
+ config: {
76
+ listAccountIds: () => [PRIVATECLAW_OPENCLAW_ACCOUNT_ID],
77
+ resolveAccount: (_cfg, accountId) => ({
78
+ accountId: resolvePrivateClawAccountId(accountId),
79
+ name: "PrivateClaw virtual account",
80
+ enabled: true,
81
+ configured: true,
82
+ }),
83
+ defaultAccountId: () => PRIVATECLAW_OPENCLAW_ACCOUNT_ID,
84
+ isEnabled: () => true,
85
+ isConfigured: () => true,
86
+ describeAccount: (account) => ({
87
+ accountId: account.accountId,
88
+ name: account.name,
89
+ enabled: true,
90
+ configured: true,
91
+ linked: true,
92
+ running: true,
93
+ connected: true,
94
+ }),
95
+ },
96
+ commands: {
97
+ skipWhenConfigEmpty: false,
98
+ },
99
+ threading: {
100
+ resolveReplyToMode: () => "all",
101
+ },
102
+ outbound: {
103
+ deliveryMode: "direct",
104
+ sendPayload: async (ctx) => {
105
+ await params.deliverOutboundMessage(ctx.to, toOutboundMessage(ctx.payload));
106
+ return buildDeliveryResult(ctx.to);
107
+ },
108
+ sendText: async (ctx) => {
109
+ await params.deliverOutboundMessage(ctx.to, {
110
+ ...(ctx.text.trim() ? { text: ctx.text } : {}),
111
+ ...(ctx.mediaUrl?.trim() ? { mediaUrl: ctx.mediaUrl.trim() } : {}),
112
+ ...(typeof ctx.replyToId === "string" || ctx.replyToId === null
113
+ ? { replyToId: ctx.replyToId }
114
+ : {}),
115
+ });
116
+ return buildDeliveryResult(ctx.to);
117
+ },
118
+ sendMedia: async (ctx) => {
119
+ await params.deliverOutboundMessage(ctx.to, {
120
+ ...(ctx.text.trim() ? { text: ctx.text } : {}),
121
+ ...(ctx.mediaUrl?.trim() ? { mediaUrl: ctx.mediaUrl.trim() } : {}),
122
+ ...(typeof ctx.replyToId === "string" || ctx.replyToId === null
123
+ ? { replyToId: ctx.replyToId }
124
+ : {}),
125
+ });
126
+ return buildDeliveryResult(ctx.to);
127
+ },
128
+ },
129
+ };
130
+ }