@privateclaw/privateclaw 0.1.17 → 0.1.18

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.
@@ -1,5 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
+ import { readFileSync } from "node:fs";
3
4
  import fs from "node:fs/promises";
4
5
  import os from "node:os";
5
6
  import path from "node:path";
@@ -20,6 +21,9 @@ const XML_ENTITY_PATTERN = /&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);/giu;
20
21
  const PRIVATECLAW_RESPONSE_CONTRACT_VERSION = 1;
21
22
  const PRIVATECLAW_RESPONSE_TAG_START = "<privateclaw-response>";
22
23
  const PRIVATECLAW_RESPONSE_TAG_END = "</privateclaw-response>";
24
+ const LIVE_TRACE_POLL_INTERVAL_MS = 150;
25
+ const MAX_TRACE_ENTRY_CHARS = 3200;
26
+ const MAX_TRACE_SUMMARY_CHARS = 180;
23
27
  const DOCX_MIME_TYPES = new Set([
24
28
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
25
29
  ]);
@@ -35,9 +39,9 @@ const TEXT_LIKE_MIME_TYPES = new Set([
35
39
  "application/x-typescript",
36
40
  "image/svg+xml",
37
41
  ]);
38
- export function parseOpenClawAgentOutput(stdout) {
42
+ export function parseOpenClawAgentOutput(stdout, options) {
39
43
  const parsed = parseOpenClawAgentJson(stdout);
40
- return parseOpenClawAgentResult(parsed);
44
+ return parseOpenClawAgentResult(parsed, options);
41
45
  }
42
46
  export function resolveOpenClawLaunchCommand(options = {}) {
43
47
  const platform = options.platform ?? process.platform;
@@ -65,13 +69,23 @@ export function resolveOpenClawLaunchCommand(options = {}) {
65
69
  };
66
70
  }
67
71
  function parseOpenClawAgentJson(stdout) {
68
- return JSON.parse(stdout);
72
+ const trimmed = stdout.trim();
73
+ try {
74
+ return JSON.parse(trimmed);
75
+ }
76
+ catch (error) {
77
+ const embeddedPayload = extractEmbeddedJsonPayload(trimmed);
78
+ if (!embeddedPayload) {
79
+ throw error;
80
+ }
81
+ return JSON.parse(embeddedPayload);
82
+ }
69
83
  }
70
- function parseOpenClawAgentResult(parsed) {
71
- const result = extractDisplayResult(parsed);
84
+ function parseOpenClawAgentResult(parsed, options) {
85
+ const result = extractDisplayResult(parsed, options);
72
86
  return toBridgeResponse(result.messages, result.data);
73
87
  }
74
- function extractDisplayResult(parsed) {
88
+ function extractDisplayResult(parsed, options) {
75
89
  const payloads = parsed.result?.payloads ?? parsed.payloads ?? [];
76
90
  const hasAlternatePayloadShape = !parsed.status && payloads.length > 0;
77
91
  if (parsed.status && parsed.status !== "ok") {
@@ -84,7 +98,7 @@ function extractDisplayResult(parsed) {
84
98
  if (typeof candidate !== "string") {
85
99
  return [];
86
100
  }
87
- const result = parseStructuredResponseResult(candidate);
101
+ const result = parseStructuredResponseResult(candidate, options);
88
102
  return result ? [result] : [];
89
103
  }));
90
104
  if (structuredResults.length > 0) {
@@ -103,6 +117,7 @@ function extractDisplayResult(parsed) {
103
117
  }
104
118
  export class OpenClawAgentBridge {
105
119
  options;
120
+ supportsThinkingTrace = true;
106
121
  executable;
107
122
  executableArgs;
108
123
  executableUsesShell;
@@ -139,6 +154,9 @@ export class OpenClawAgentBridge {
139
154
  return this.executePrompt(params.sessionId, promptMessage, {
140
155
  includeArtifacts: true,
141
156
  noDisplayFallbackMessage: params.message,
157
+ ...(params.onThinkingTrace
158
+ ? { onThinkingTrace: params.onThinkingTrace }
159
+ : {}),
142
160
  });
143
161
  }
144
162
  async transcribeAudioAttachments(params) {
@@ -162,8 +180,53 @@ export class OpenClawAgentBridge {
162
180
  async executePrompt(sessionId, promptMessage, options) {
163
181
  const args = this.buildArgs(sessionId, promptMessage);
164
182
  this.verboseLog(`exec_start session=${sessionId} promptChars=${promptMessage.length} argCount=${args.length} includeArtifacts=${options?.includeArtifacts !== false} agent=${JSON.stringify(this.options.agentId ?? "default")} channel=${JSON.stringify(this.options.channel ?? "default")} local=${this.options.local === true} thinking=${JSON.stringify(this.options.thinking ?? "default")} timeoutSeconds=${this.options.timeoutSeconds ?? "default"}`);
165
- const sessionLogCursor = await this.captureSessionLogCursor(sessionId);
166
- const stdout = await this.execOpenClaw(args);
183
+ let sessionLogCursor = await this.captureSessionLogCursor(sessionId);
184
+ let latestTraceEntries = [];
185
+ const emitThinkingTrace = async (newEntries) => {
186
+ if (!options?.onThinkingTrace || newEntries.length === 0) {
187
+ return;
188
+ }
189
+ latestTraceEntries = [...latestTraceEntries, ...newEntries];
190
+ await options.onThinkingTrace({
191
+ entries: latestTraceEntries.map((entry) => ({ ...entry })),
192
+ sentAt: latestTraceEntries[latestTraceEntries.length - 1]?.sentAt ?? nowIso(),
193
+ summary: summarizeThinkingTrace(latestTraceEntries),
194
+ });
195
+ };
196
+ const stdoutPromise = this.execOpenClaw(args);
197
+ if (options?.onThinkingTrace) {
198
+ let pending = true;
199
+ void stdoutPromise.then(() => {
200
+ pending = false;
201
+ }, () => {
202
+ pending = false;
203
+ });
204
+ while (pending) {
205
+ await delay(LIVE_TRACE_POLL_INTERVAL_MS);
206
+ if (!pending) {
207
+ break;
208
+ }
209
+ const liveMessages = await this.collectSessionMessages(sessionId, sessionLogCursor, {
210
+ allowTrailingPartial: false,
211
+ });
212
+ sessionLogCursor = liveMessages.nextCursor;
213
+ await emitThinkingTrace(liveMessages.traceEntries);
214
+ }
215
+ }
216
+ let stdout;
217
+ try {
218
+ stdout = await stdoutPromise;
219
+ }
220
+ catch (error) {
221
+ if (options?.onThinkingTrace) {
222
+ const finalTraceDelta = await this.collectSessionMessages(sessionId, sessionLogCursor, {
223
+ allowTrailingPartial: true,
224
+ });
225
+ sessionLogCursor = finalTraceDelta.nextCursor;
226
+ await emitThinkingTrace(finalTraceDelta.traceEntries);
227
+ }
228
+ throw error;
229
+ }
167
230
  this.verboseLog(`exec_complete session=${sessionId} stdoutChars=${stdout.length}`);
168
231
  let parsed;
169
232
  let parseError;
@@ -178,7 +241,10 @@ export class OpenClawAgentBridge {
178
241
  parseError = error;
179
242
  this.log(`openclaw_agent_parse_failed session=${sessionId} stdoutChars=${stdout.length} stdoutPreview=${JSON.stringify(stdout.slice(0, 400))}`);
180
243
  }
181
- const collectedMessages = await this.collectSessionMessages(sessionId, sessionLogCursor);
244
+ const collectedMessages = await this.collectSessionMessages(sessionId, sessionLogCursor, {
245
+ allowTrailingPartial: true,
246
+ });
247
+ await emitThinkingTrace(collectedMessages.traceEntries);
182
248
  const recoveredMessages = [
183
249
  ...collectedMessages.assistantMessages,
184
250
  ...(options?.includeArtifacts === false ? [] : collectedMessages.artifactMessages),
@@ -192,11 +258,19 @@ export class OpenClawAgentBridge {
192
258
  throw parseError;
193
259
  }
194
260
  try {
195
- const response = parseOpenClawAgentResult(parsed);
196
- this.verboseLog(`response_ready session=${sessionId} directMessages=${typeof response === "string" ? 1 : response.messages.length} artifactMessages=${options?.includeArtifacts === false ? 0 : collectedMessages.artifactMessages.length}`);
261
+ const response = parseOpenClawAgentResult(parsed, {
262
+ workspaceDir: this.workspaceDir,
263
+ });
264
+ const authoritativeResponse = collectedMessages.structuredAssistantMessages.length > 0
265
+ ? toBridgeResponse(collectedMessages.structuredAssistantMessages, collectedMessages.assistantData)
266
+ : response;
267
+ if (collectedMessages.structuredAssistantMessages.length > 0) {
268
+ this.log(`session_log_structured_override session=${sessionId} directMessages=${typeof response === "string" ? 1 : response.messages.length} recoveredMessages=${collectedMessages.structuredAssistantMessages.length}`);
269
+ }
270
+ this.verboseLog(`response_ready session=${sessionId} directMessages=${typeof response === "string" ? 1 : response.messages.length} authoritativeMessages=${typeof authoritativeResponse === "string" ? 1 : authoritativeResponse.messages.length} artifactMessages=${options?.includeArtifacts === false ? 0 : collectedMessages.artifactMessages.length}`);
197
271
  return options?.includeArtifacts === false
198
- ? response
199
- : mergeBridgeResponses(response, collectedMessages.artifactMessages);
272
+ ? authoritativeResponse
273
+ : mergeBridgeResponses(authoritativeResponse, collectedMessages.artifactMessages);
200
274
  }
201
275
  catch (error) {
202
276
  if (recoveredMessages.length > 0) {
@@ -225,42 +299,40 @@ export class OpenClawAgentBridge {
225
299
  sizeBytes: stat.size,
226
300
  };
227
301
  }
228
- async collectSessionMessages(sessionId, cursor) {
229
- const sessionLogPath = cursor.path ?? (await this.resolveSessionLogPath(sessionId));
230
- if (!sessionLogPath) {
231
- this.log(`artifact_log_missing session=${sessionId}`);
232
- return {
233
- assistantMessages: [],
234
- artifactMessages: [],
235
- };
236
- }
237
- const sessionLogBuffer = await fs.readFile(sessionLogPath);
238
- const deltaBuffer = cursor.path === sessionLogPath
239
- ? sessionLogBuffer.subarray(Math.min(cursor.sizeBytes, sessionLogBuffer.length))
240
- : sessionLogBuffer;
241
- if (deltaBuffer.length === 0) {
302
+ async collectSessionMessages(sessionId, cursor, options) {
303
+ const { entries, nextCursor } = await this.readSessionLogEntries(sessionId, cursor, options);
304
+ if (entries.length === 0) {
305
+ if (!nextCursor.path) {
306
+ this.log(`artifact_log_missing session=${sessionId}`);
307
+ }
242
308
  return {
243
309
  assistantMessages: [],
310
+ structuredAssistantMessages: [],
244
311
  artifactMessages: [],
312
+ nextCursor,
313
+ traceEntries: [],
245
314
  };
246
315
  }
247
- const entries = deltaBuffer
248
- .toString("utf8")
249
- .split(/\r?\n/gu)
250
- .map((line) => line.trim())
251
- .filter((line) => line !== "")
252
- .map((line) => JSON.parse(line));
253
- const assistantResults = entries.map((entry) => extractAssistantDisplayResult(entry));
254
- const assistantMessages = assistantResults.flatMap((result) => result.messages);
316
+ const assistantResults = entries.map((entry) => extractAssistantDisplayResult(entry, {
317
+ workspaceDir: this.workspaceDir,
318
+ }));
319
+ const assistantMessages = assistantResults.flatMap((result) => result.result.messages);
320
+ const structuredAssistantMessages = assistantResults
321
+ .filter((result) => result.isStructured)
322
+ .flatMap((result) => result.result.messages);
323
+ const traceEntries = entries.flatMap((entry) => {
324
+ const traceEntry = extractThinkingTraceEntry(entry);
325
+ return traceEntry ? [traceEntry] : [];
326
+ });
255
327
  const seenPaths = new Set();
256
328
  const attachments = [];
257
329
  for (const entry of entries) {
258
330
  for (const mediaPath of extractMediaPaths(entry)) {
259
- const normalizedPath = normalizeMediaPath(mediaPath);
331
+ const normalizedPath = normalizeMediaPath(mediaPath, this.workspaceDir);
260
332
  if (seenPaths.has(normalizedPath)) {
261
333
  continue;
262
334
  }
263
- const attachment = await buildAttachmentFromMediaPath(normalizedPath);
335
+ const attachment = await buildAttachmentFromMediaPath(normalizedPath, this.workspaceDir);
264
336
  this.log(`artifact_recovered session=${sessionId} mediaPath=${JSON.stringify(mediaPath)} normalizedPath=${JSON.stringify(normalizedPath)} name=${JSON.stringify(attachment.name)} mimeType=${attachment.mimeType} sizeBytes=${attachment.sizeBytes}`);
265
337
  attachments.push(attachment);
266
338
  seenPaths.add(normalizedPath);
@@ -269,20 +341,80 @@ export class OpenClawAgentBridge {
269
341
  const artifactMessages = attachments.length > 0
270
342
  ? [{ text: "", attachments }]
271
343
  : [];
272
- const assistantData = combineStructuredData(assistantResults).data;
344
+ const assistantData = combineStructuredData(assistantResults
345
+ .filter((result) => result.isStructured)
346
+ .map((result) => result.result)).data;
273
347
  if (attachments.length === 0) {
274
- this.log(`artifact_scan_complete session=${sessionId} entries=${entries.length} assistantRecovered=${assistantMessages.length} recovered=0 logPath=${JSON.stringify(sessionLogPath)}`);
348
+ this.log(`artifact_scan_complete session=${sessionId} entries=${entries.length} assistantRecovered=${assistantMessages.length} recovered=0 logPath=${JSON.stringify(nextCursor.path ?? "missing")}`);
275
349
  return {
276
350
  assistantMessages,
351
+ structuredAssistantMessages,
277
352
  ...(assistantData !== undefined ? { assistantData } : {}),
278
353
  artifactMessages,
354
+ nextCursor,
355
+ traceEntries,
279
356
  };
280
357
  }
281
- this.log(`artifact_scan_complete session=${sessionId} entries=${entries.length} assistantRecovered=${assistantMessages.length} recovered=${attachments.length} logPath=${JSON.stringify(sessionLogPath)}`);
358
+ this.log(`artifact_scan_complete session=${sessionId} entries=${entries.length} assistantRecovered=${assistantMessages.length} recovered=${attachments.length} logPath=${JSON.stringify(nextCursor.path ?? "missing")}`);
282
359
  return {
283
360
  assistantMessages,
361
+ structuredAssistantMessages,
284
362
  ...(assistantData !== undefined ? { assistantData } : {}),
285
363
  artifactMessages,
364
+ nextCursor,
365
+ traceEntries,
366
+ };
367
+ }
368
+ async readSessionLogEntries(sessionId, cursor, options) {
369
+ const sessionLogPath = cursor.path ?? (await this.resolveSessionLogPath(sessionId));
370
+ if (!sessionLogPath) {
371
+ return {
372
+ entries: [],
373
+ nextCursor: cursor,
374
+ };
375
+ }
376
+ const sessionLogBuffer = await fs.readFile(sessionLogPath);
377
+ const startOffset = cursor.path === sessionLogPath
378
+ ? Math.min(cursor.sizeBytes, sessionLogBuffer.length)
379
+ : 0;
380
+ const deltaBuffer = sessionLogBuffer.subarray(startOffset);
381
+ if (deltaBuffer.length === 0) {
382
+ return {
383
+ entries: [],
384
+ nextCursor: {
385
+ path: sessionLogPath,
386
+ sizeBytes: sessionLogBuffer.length,
387
+ },
388
+ };
389
+ }
390
+ const deltaText = deltaBuffer.toString("utf8");
391
+ let parseText = deltaText;
392
+ let nextSize = sessionLogBuffer.length;
393
+ if (!options?.allowTrailingPartial && !deltaText.endsWith("\n")) {
394
+ const lastNewlineIndex = deltaText.lastIndexOf("\n");
395
+ if (lastNewlineIndex < 0) {
396
+ return {
397
+ entries: [],
398
+ nextCursor: {
399
+ path: sessionLogPath,
400
+ sizeBytes: startOffset,
401
+ },
402
+ };
403
+ }
404
+ parseText = deltaText.slice(0, lastNewlineIndex + 1);
405
+ nextSize = startOffset + Buffer.byteLength(parseText, "utf8");
406
+ }
407
+ const entries = parseText
408
+ .split(/\r?\n/gu)
409
+ .map((line) => line.trim())
410
+ .filter((line) => line !== "")
411
+ .map((line) => JSON.parse(line));
412
+ return {
413
+ entries,
414
+ nextCursor: {
415
+ path: sessionLogPath,
416
+ sizeBytes: nextSize,
417
+ },
286
418
  };
287
419
  }
288
420
  async resolveSessionLogPath(sessionId) {
@@ -525,14 +657,66 @@ function buildNoDisplayPayloadNotice(message, parsed) {
525
657
  return `OpenClaw completed the request, but it did not return a text reply through the agent bridge.${extraSummary}`;
526
658
  }
527
659
  function mergeBridgeResponses(primary, supplemental) {
528
- if (supplemental.length === 0) {
660
+ const dedupedSupplemental = dedupeSupplementalMessages(primary, supplemental);
661
+ if (dedupedSupplemental.length === 0) {
529
662
  return primary;
530
663
  }
531
664
  return toBridgeResponse([
532
665
  ...normalizeBridgeResponse(primary),
533
- ...supplemental,
666
+ ...dedupedSupplemental,
534
667
  ], extractBridgeResponseData(primary));
535
668
  }
669
+ function dedupeSupplementalMessages(primary, supplemental) {
670
+ if (supplemental.length === 0) {
671
+ return supplemental;
672
+ }
673
+ const seenInlineData = new Set();
674
+ const seenUris = new Set();
675
+ for (const message of normalizeBridgeResponse(primary)) {
676
+ for (const attachment of message.attachments ?? []) {
677
+ const inlineData = attachment.dataBase64?.trim();
678
+ if (inlineData) {
679
+ seenInlineData.add(`${attachment.mimeType}:${attachment.sizeBytes}:${inlineData}`);
680
+ }
681
+ const uri = attachment.uri?.trim();
682
+ if (uri) {
683
+ seenUris.add(uri);
684
+ }
685
+ }
686
+ }
687
+ return supplemental.flatMap((message) => {
688
+ const dedupedAttachments = (message.attachments ?? []).filter((attachment) => {
689
+ const inlineData = attachment.dataBase64?.trim();
690
+ if (inlineData) {
691
+ const key = `${attachment.mimeType}:${attachment.sizeBytes}:${inlineData}`;
692
+ if (seenInlineData.has(key)) {
693
+ return false;
694
+ }
695
+ seenInlineData.add(key);
696
+ return true;
697
+ }
698
+ const uri = attachment.uri?.trim();
699
+ if (uri) {
700
+ if (seenUris.has(uri)) {
701
+ return false;
702
+ }
703
+ seenUris.add(uri);
704
+ }
705
+ return true;
706
+ });
707
+ if (message.text.trim() === "" && dedupedAttachments.length === 0) {
708
+ return [];
709
+ }
710
+ return [
711
+ {
712
+ text: message.text,
713
+ ...(dedupedAttachments.length > 0
714
+ ? { attachments: dedupedAttachments }
715
+ : {}),
716
+ },
717
+ ];
718
+ });
719
+ }
536
720
  function normalizeBridgeResponse(response) {
537
721
  if (typeof response === "string") {
538
722
  return [{ text: response }];
@@ -567,6 +751,93 @@ function toBridgeResponse(messages, data) {
567
751
  ...(data !== undefined ? { data } : {}),
568
752
  };
569
753
  }
754
+ function nowIso() {
755
+ return new Date().toISOString();
756
+ }
757
+ function delay(ms) {
758
+ return new Promise((resolve) => {
759
+ setTimeout(resolve, ms);
760
+ });
761
+ }
762
+ function truncateThinkingTraceText(text) {
763
+ if (text.length <= MAX_TRACE_ENTRY_CHARS) {
764
+ return text;
765
+ }
766
+ const hiddenChars = text.length - MAX_TRACE_ENTRY_CHARS;
767
+ return [
768
+ text.slice(0, MAX_TRACE_ENTRY_CHARS).trimEnd(),
769
+ "",
770
+ `… truncated ${hiddenChars} more characters`,
771
+ ].join("\n");
772
+ }
773
+ function truncateThinkingSummary(text) {
774
+ const trimmed = text.trim();
775
+ if (trimmed.length <= MAX_TRACE_SUMMARY_CHARS) {
776
+ return trimmed;
777
+ }
778
+ return `${trimmed.slice(0, MAX_TRACE_SUMMARY_CHARS - 1).trimEnd()}…`;
779
+ }
780
+ function readEntryTextContent(entry) {
781
+ return (entry.message?.content ?? [])
782
+ .flatMap((contentItem) => contentItem.type === "text" && typeof contentItem.text === "string"
783
+ ? [contentItem.text.trim()]
784
+ : [])
785
+ .filter((text) => text !== "")
786
+ .join("\n\n");
787
+ }
788
+ function summarizeThinkingTrace(entries) {
789
+ const latestEntry = entries[entries.length - 1];
790
+ if (!latestEntry) {
791
+ return "";
792
+ }
793
+ const firstLine = latestEntry.text
794
+ .split(/\r?\n/gu)
795
+ .map((line) => line.trim())
796
+ .find((line) => line !== "") ??
797
+ latestEntry.title;
798
+ if (latestEntry.kind === "action" && latestEntry.toolName) {
799
+ return truncateThinkingSummary(`${latestEntry.toolName}: ${firstLine}`);
800
+ }
801
+ return truncateThinkingSummary(firstLine);
802
+ }
803
+ function extractThinkingTraceEntry(entry) {
804
+ if (entry.type !== "message" || !entry.message) {
805
+ return undefined;
806
+ }
807
+ const entryId = entry.id?.trim() || `trace-${randomUUID()}`;
808
+ const sentAt = entry.timestamp?.trim() || nowIso();
809
+ if (entry.message.role === "assistant") {
810
+ const text = truncateThinkingTraceText(stripStructuredResponseBlock(readEntryTextContent(entry)));
811
+ if (text === "") {
812
+ return undefined;
813
+ }
814
+ return {
815
+ id: entryId,
816
+ kind: entry.message.isError ? "error" : "thought",
817
+ title: entry.message.isError ? "Assistant error" : "Thinking",
818
+ text,
819
+ sentAt,
820
+ };
821
+ }
822
+ if (entry.message.role !== "toolResult") {
823
+ return undefined;
824
+ }
825
+ const toolName = entry.message.toolName?.trim();
826
+ const toolText = readEntryTextContent(entry).replace(/^MEDIA:.+$/gmu, "").trim();
827
+ return {
828
+ id: entryId,
829
+ kind: entry.message.isError ? "error" : "action",
830
+ title: toolName ? `Tool • ${toolName}` : entry.message.isError ? "Tool error" : "Tool",
831
+ text: truncateThinkingTraceText(toolText ||
832
+ (entry.message.isError
833
+ ? "The tool call failed."
834
+ : toolName
835
+ ? `Tool ${toolName} completed.`
836
+ : "Tool completed.")),
837
+ sentAt,
838
+ ...(toolName ? { toolName } : {}),
839
+ };
840
+ }
570
841
  function extractMediaPaths(entry) {
571
842
  if (entry.type !== "message" || entry.message?.role !== "toolResult" || entry.message.isError) {
572
843
  return [];
@@ -589,25 +860,22 @@ function extractMediaPaths(entry) {
589
860
  }
590
861
  return [...mediaPaths];
591
862
  }
592
- function extractAssistantDisplayResult(entry) {
863
+ function extractAssistantDisplayResult(entry, options) {
593
864
  if (entry.type !== "message" || entry.message?.role !== "assistant" || entry.message.isError) {
594
- return { messages: [] };
865
+ return { result: { messages: [] }, isStructured: false };
595
866
  }
596
- const parts = (entry.message.content ?? [])
597
- .flatMap((contentItem) => contentItem.type === "text" && typeof contentItem.text === "string"
598
- ? [contentItem.text.trim()]
599
- : [])
600
- .filter((text) => text !== "");
601
- if (parts.length === 0) {
602
- return { messages: [] };
867
+ const rawText = readEntryTextContent(entry);
868
+ if (rawText === "") {
869
+ return { result: { messages: [] }, isStructured: false };
603
870
  }
604
- const rawText = parts.join("\n\n");
605
- const structuredResult = parseStructuredResponseResult(rawText);
871
+ const structuredResult = parseStructuredResponseResult(rawText, options?.workspaceDir ? { workspaceDir: options.workspaceDir } : undefined);
606
872
  if (structuredResult) {
607
- return structuredResult;
873
+ return { result: structuredResult, isStructured: true };
608
874
  }
609
875
  const fallbackText = stripStructuredResponseBlock(rawText);
610
- return fallbackText !== "" ? { messages: [{ text: fallbackText }] } : { messages: [] };
876
+ return fallbackText !== ""
877
+ ? { result: { messages: [{ text: fallbackText }] }, isStructured: false }
878
+ : { result: { messages: [] }, isStructured: false };
611
879
  }
612
880
  function appendStructuredResponseContract(prompt) {
613
881
  return `${prompt}\n\n${buildStructuredResponseContractPrompt()}`;
@@ -639,19 +907,83 @@ function buildStructuredResponseContractPrompt() {
639
907
  `- Use this JSON shape: {\"version\":${PRIVATECLAW_RESPONSE_CONTRACT_VERSION},\"messages\":[{\"text\":\"...\"}],\"data\":{}}`,
640
908
  "- Always include at least one messages entry.",
641
909
  "- Put user-visible text only in messages[].text.",
910
+ "- 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\"}]}",
911
+ "- Or use dataBase64 for inline binary: {\"name\":\"file.png\",\"mimeType\":\"image/png\",\"dataBase64\":\"...\"}",
912
+ "- 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.",
642
913
  "- Use data for optional machine-readable extraction results that PrivateClaw may consume in future file-processing flows.",
643
914
  "- Do not wrap the JSON in markdown fences.",
644
915
  ].join("\n");
645
916
  }
646
- function parseStructuredResponseResult(raw) {
917
+ function resolveStructuredAttachments(rawAttachments, options) {
918
+ if (!rawAttachments || rawAttachments.length === 0) {
919
+ return [];
920
+ }
921
+ const workspaceDir = path.resolve(options?.workspaceDir ?? DEFAULT_WORKSPACE_DIR);
922
+ const attachments = [];
923
+ for (const raw of rawAttachments) {
924
+ if (raw.dataBase64?.trim()) {
925
+ const trimmedData = raw.dataBase64.trim();
926
+ attachments.push({
927
+ id: `structured-attachment-${randomUUID()}`,
928
+ name: raw.name ?? "attachment",
929
+ mimeType: raw.mimeType ?? GENERIC_BINARY_MIME,
930
+ sizeBytes: Buffer.byteLength(trimmedData, "base64"),
931
+ dataBase64: trimmedData,
932
+ });
933
+ }
934
+ else if (raw.filePath) {
935
+ try {
936
+ const filePath = resolveStructuredAttachmentFilePath(raw.filePath, workspaceDir);
937
+ if (!filePath) {
938
+ continue;
939
+ }
940
+ const fileBytes = readFileSync(filePath);
941
+ attachments.push({
942
+ id: `structured-attachment-${randomUUID()}`,
943
+ name: raw.name ?? path.basename(filePath) ?? "attachment",
944
+ mimeType: raw.mimeType ?? inferMimeTypeFromFileName(raw.name ?? filePath) ?? GENERIC_BINARY_MIME,
945
+ sizeBytes: fileBytes.byteLength,
946
+ dataBase64: fileBytes.toString("base64"),
947
+ });
948
+ }
949
+ catch {
950
+ // Skip unreadable files
951
+ }
952
+ }
953
+ }
954
+ return attachments;
955
+ }
956
+ function resolveStructuredAttachmentFilePath(rawFilePath, workspaceDir) {
957
+ const trimmedPath = rawFilePath.trim();
958
+ if (trimmedPath === "") {
959
+ return undefined;
960
+ }
961
+ if (path.isAbsolute(trimmedPath)) {
962
+ return path.normalize(trimmedPath);
963
+ }
964
+ const resolvedPath = normalizeMediaPath(trimmedPath, workspaceDir);
965
+ return isPathInsideDirectory(workspaceDir, resolvedPath) ? resolvedPath : undefined;
966
+ }
967
+ function parseStructuredResponseResult(raw, options) {
647
968
  const structured = parseStructuredResponseBlock(raw);
648
969
  if (!structured?.messages || structured.messages.length === 0) {
649
970
  return undefined;
650
971
  }
651
- const messages = structured.messages.flatMap((message) => {
972
+ const messages = [];
973
+ for (const message of structured.messages) {
652
974
  const text = typeof message.text === "string" ? message.text.trim() : "";
653
- return text !== "" ? [{ text }] : [];
654
- });
975
+ const qqimgResult = extractInlineQqimgAttachments(text, options);
976
+ const attachments = [
977
+ ...resolveStructuredAttachments(message.attachments, options),
978
+ ...qqimgResult.attachments,
979
+ ];
980
+ if (qqimgResult.text !== "" || attachments.length > 0) {
981
+ messages.push({
982
+ text: qqimgResult.text,
983
+ ...(attachments.length > 0 ? { attachments } : {}),
984
+ });
985
+ }
986
+ }
655
987
  if (messages.length === 0) {
656
988
  return undefined;
657
989
  }
@@ -661,8 +993,7 @@ function parseStructuredResponseResult(raw) {
661
993
  };
662
994
  }
663
995
  function parseStructuredResponseBlock(raw) {
664
- const match = raw.match(buildStructuredResponseBlockPattern("u"));
665
- const payload = match?.[1]?.trim();
996
+ const payload = extractStructuredResponsePayload(raw);
666
997
  if (!payload) {
667
998
  return undefined;
668
999
  }
@@ -675,11 +1006,101 @@ function parseStructuredResponseBlock(raw) {
675
1006
  return parsed;
676
1007
  }
677
1008
  function stripStructuredResponseBlock(raw) {
678
- return raw.replace(buildStructuredResponseBlockPattern("gu"), "").trim();
1009
+ let stripped = raw;
1010
+ for (const pattern of buildStructuredResponseBlockPatterns("gu")) {
1011
+ stripped = stripped.replace(pattern, "");
1012
+ }
1013
+ return stripped.trim();
679
1014
  }
680
1015
  function buildStructuredResponseBlockPattern(flags) {
681
1016
  return new RegExp(`${escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_START)}([\\s\\S]*?)${escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_END)}`, flags);
682
1017
  }
1018
+ function buildStructuredResponseBlockPatterns(flags) {
1019
+ const startTag = escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_START);
1020
+ return [
1021
+ buildStructuredResponseBlockPattern(flags),
1022
+ new RegExp(`${startTag}([\\s\\S]*?)${startTag}`, flags),
1023
+ ];
1024
+ }
1025
+ function extractStructuredResponsePayload(raw) {
1026
+ for (const pattern of buildStructuredResponseBlockPatterns("u")) {
1027
+ const payload = raw.match(pattern)?.[1]?.trim();
1028
+ if (payload) {
1029
+ return payload;
1030
+ }
1031
+ }
1032
+ return undefined;
1033
+ }
1034
+ function extractInlineQqimgAttachments(text, options) {
1035
+ if (!text.includes("<qqimg>")) {
1036
+ return { text, attachments: [] };
1037
+ }
1038
+ const attachments = [];
1039
+ for (const match of text.matchAll(/<qqimg>([\s\S]*?)<\/qqimg>/giu)) {
1040
+ const rawValue = match[1]?.trim();
1041
+ if (!rawValue) {
1042
+ continue;
1043
+ }
1044
+ const attachment = resolveInlineQqimgAttachment(rawValue, options);
1045
+ if (attachment) {
1046
+ attachments.push(attachment);
1047
+ }
1048
+ }
1049
+ return {
1050
+ text: text
1051
+ .replace(/<qqimg>[\s\S]*?<\/qqimg>/giu, "")
1052
+ .replace(/\n{3,}/gu, "\n\n")
1053
+ .trim(),
1054
+ attachments,
1055
+ };
1056
+ }
1057
+ function resolveInlineQqimgAttachment(rawValue, options) {
1058
+ const workspaceDir = path.resolve(options?.workspaceDir ?? DEFAULT_WORKSPACE_DIR);
1059
+ if (!path.isAbsolute(rawValue)) {
1060
+ try {
1061
+ const parsedUrl = new URL(rawValue);
1062
+ if (parsedUrl.protocol === "file:") {
1063
+ const filePath = fileURLToPath(parsedUrl);
1064
+ const fileBytes = readFileSync(filePath);
1065
+ return {
1066
+ id: `structured-attachment-${randomUUID()}`,
1067
+ name: path.basename(filePath) || "attachment",
1068
+ mimeType: inferMimeTypeFromFileName(filePath) ?? GENERIC_BINARY_MIME,
1069
+ sizeBytes: fileBytes.byteLength,
1070
+ dataBase64: fileBytes.toString("base64"),
1071
+ };
1072
+ }
1073
+ const fileName = path.basename(parsedUrl.pathname) || "attachment";
1074
+ return {
1075
+ id: `structured-attachment-${randomUUID()}`,
1076
+ name: fileName,
1077
+ mimeType: inferMimeTypeFromFileName(fileName) ?? GENERIC_BINARY_MIME,
1078
+ sizeBytes: 0,
1079
+ uri: parsedUrl.toString(),
1080
+ };
1081
+ }
1082
+ catch {
1083
+ // Not a URL. Fall through to local file handling.
1084
+ }
1085
+ }
1086
+ try {
1087
+ const filePath = resolveStructuredAttachmentFilePath(rawValue, workspaceDir);
1088
+ if (!filePath) {
1089
+ return undefined;
1090
+ }
1091
+ const fileBytes = readFileSync(filePath);
1092
+ return {
1093
+ id: `structured-attachment-${randomUUID()}`,
1094
+ name: path.basename(filePath) || "attachment",
1095
+ mimeType: inferMimeTypeFromFileName(filePath) ?? GENERIC_BINARY_MIME,
1096
+ sizeBytes: fileBytes.byteLength,
1097
+ dataBase64: fileBytes.toString("base64"),
1098
+ };
1099
+ }
1100
+ catch {
1101
+ return undefined;
1102
+ }
1103
+ }
683
1104
  function parseStructuredResponseJson(payload) {
684
1105
  try {
685
1106
  return JSON.parse(payload);
@@ -697,6 +1118,67 @@ function parseStructuredResponseJson(payload) {
697
1118
  }
698
1119
  }
699
1120
  }
1121
+ function extractEmbeddedJsonPayload(text) {
1122
+ for (let startIndex = 0; startIndex < text.length; startIndex += 1) {
1123
+ const character = text[startIndex];
1124
+ if (character !== "{" && character !== "[") {
1125
+ continue;
1126
+ }
1127
+ const candidate = sliceBalancedJsonPayload(text, startIndex);
1128
+ if (!candidate) {
1129
+ continue;
1130
+ }
1131
+ try {
1132
+ JSON.parse(candidate);
1133
+ return candidate;
1134
+ }
1135
+ catch {
1136
+ continue;
1137
+ }
1138
+ }
1139
+ return undefined;
1140
+ }
1141
+ function sliceBalancedJsonPayload(text, startIndex) {
1142
+ const expectedClosers = [];
1143
+ let inString = false;
1144
+ let escaped = false;
1145
+ for (let index = startIndex; index < text.length; index += 1) {
1146
+ const character = text[index];
1147
+ if (escaped) {
1148
+ escaped = false;
1149
+ continue;
1150
+ }
1151
+ if (character === "\\") {
1152
+ escaped = true;
1153
+ continue;
1154
+ }
1155
+ if (character === "\"") {
1156
+ inString = !inString;
1157
+ continue;
1158
+ }
1159
+ if (inString) {
1160
+ continue;
1161
+ }
1162
+ if (character === "{") {
1163
+ expectedClosers.push("}");
1164
+ continue;
1165
+ }
1166
+ if (character === "[") {
1167
+ expectedClosers.push("]");
1168
+ continue;
1169
+ }
1170
+ if (character === "}" || character === "]") {
1171
+ const expected = expectedClosers.pop();
1172
+ if (expected !== character) {
1173
+ return undefined;
1174
+ }
1175
+ if (expectedClosers.length === 0) {
1176
+ return text.slice(startIndex, index + 1);
1177
+ }
1178
+ }
1179
+ }
1180
+ return undefined;
1181
+ }
700
1182
  function stripJsonTrailingCommas(payload) {
701
1183
  let normalized = "";
702
1184
  let inString = false;
@@ -763,8 +1245,8 @@ function normalizeStructuredData(value) {
763
1245
  function extractBridgeResponseData(response) {
764
1246
  return typeof response === "string" ? undefined : response.data;
765
1247
  }
766
- async function buildAttachmentFromMediaPath(mediaPath) {
767
- const filePath = normalizeMediaPath(mediaPath);
1248
+ async function buildAttachmentFromMediaPath(mediaPath, workspaceDir = DEFAULT_WORKSPACE_DIR) {
1249
+ const filePath = normalizeMediaPath(mediaPath, workspaceDir);
768
1250
  const fileBytes = await fs.readFile(filePath);
769
1251
  const fileName = path.basename(filePath) || `media-${randomUUID()}`;
770
1252
  return {
@@ -775,12 +1257,16 @@ async function buildAttachmentFromMediaPath(mediaPath) {
775
1257
  dataBase64: fileBytes.toString("base64"),
776
1258
  };
777
1259
  }
778
- function normalizeMediaPath(mediaPath) {
1260
+ function normalizeMediaPath(mediaPath, workspaceDir = DEFAULT_WORKSPACE_DIR) {
779
1261
  const trimmed = mediaPath.trim();
780
1262
  if (trimmed.startsWith("file://")) {
781
- return fileURLToPath(trimmed);
1263
+ return path.resolve(fileURLToPath(trimmed));
782
1264
  }
783
- return path.isAbsolute(trimmed) ? trimmed : path.resolve(trimmed);
1265
+ return path.isAbsolute(trimmed) ? path.resolve(trimmed) : path.resolve(workspaceDir, trimmed);
1266
+ }
1267
+ function isPathInsideDirectory(directory, targetPath) {
1268
+ const relative = path.relative(path.resolve(directory), path.resolve(targetPath));
1269
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
784
1270
  }
785
1271
  function buildVoiceTranscriptionSessionId(sessionId, requestId) {
786
1272
  return [