@privateclaw/privateclaw 0.1.16 → 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.
Files changed (42) hide show
  1. package/README.md +44 -1
  2. package/dist/audio-transcriber.d.ts +46 -0
  3. package/dist/audio-transcriber.js +433 -0
  4. package/dist/audio-transcriber.js.map +1 -0
  5. package/dist/bridges/openai-compatible-bridge.js +1 -0
  6. package/dist/bridges/openai-compatible-bridge.js.map +1 -1
  7. package/dist/bridges/openclaw-agent-bridge.d.ts +10 -2
  8. package/dist/bridges/openclaw-agent-bridge.js +632 -73
  9. package/dist/bridges/openclaw-agent-bridge.js.map +1 -1
  10. package/dist/cli.js +57 -6
  11. package/dist/cli.js.map +1 -1
  12. package/dist/openclaw-plugin.js +150 -51
  13. package/dist/openclaw-plugin.js.map +1 -1
  14. package/dist/pair-daemon.d.ts +2 -0
  15. package/dist/pair-daemon.js +2 -0
  16. package/dist/pair-daemon.js.map +1 -1
  17. package/dist/provider.d.ts +14 -1
  18. package/dist/provider.js +262 -20
  19. package/dist/provider.js.map +1 -1
  20. package/dist/session-control.d.ts +7 -0
  21. package/dist/session-control.js +122 -0
  22. package/dist/session-control.js.map +1 -1
  23. package/dist/text.d.ts +2 -0
  24. package/dist/text.js +3 -1
  25. package/dist/text.js.map +1 -1
  26. package/dist/types.d.ts +21 -2
  27. package/package.json +2 -2
  28. package/src/audio-transcriber.test.ts +299 -0
  29. package/src/audio-transcriber.ts +615 -0
  30. package/src/bridges/openai-compatible-bridge.ts +1 -0
  31. package/src/bridges/openclaw-agent-bridge.test.ts +644 -7
  32. package/src/bridges/openclaw-agent-bridge.ts +817 -81
  33. package/src/cli.ts +73 -5
  34. package/src/openclaw-plugin.test.ts +12 -2
  35. package/src/openclaw-plugin.ts +191 -54
  36. package/src/pair-daemon.ts +4 -0
  37. package/src/provider.test.ts +679 -0
  38. package/src/provider.ts +349 -28
  39. package/src/session-control.test.ts +80 -0
  40. package/src/session-control.ts +151 -0
  41. package/src/text.ts +12 -2
  42. package/src/types.ts +29 -1
@@ -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;
@@ -124,12 +139,24 @@ export class OpenClawAgentBridge {
124
139
  log(message) {
125
140
  this.options.onLog?.(`[bridge] ${message}`);
126
141
  }
142
+ isVerboseLoggingEnabled() {
143
+ return this.options.verboseController?.enabled === true;
144
+ }
145
+ verboseLog(message) {
146
+ if (!this.isVerboseLoggingEnabled()) {
147
+ return;
148
+ }
149
+ this.options.onLog?.(`[bridge][verbose] ${message}`);
150
+ }
127
151
  async handleUserMessage(params) {
128
152
  const promptMessage = await this.buildPromptMessage(params.sessionId, params.message, params.attachments);
129
153
  this.log(`handle_user_message session=${params.sessionId} textChars=${params.message.length} attachments=${params.attachments?.length ?? 0} promptChars=${promptMessage.length}`);
130
154
  return this.executePrompt(params.sessionId, promptMessage, {
131
155
  includeArtifacts: true,
132
156
  noDisplayFallbackMessage: params.message,
157
+ ...(params.onThinkingTrace
158
+ ? { onThinkingTrace: params.onThinkingTrace }
159
+ : {}),
133
160
  });
134
161
  }
135
162
  async transcribeAudioAttachments(params) {
@@ -152,8 +179,55 @@ export class OpenClawAgentBridge {
152
179
  }
153
180
  async executePrompt(sessionId, promptMessage, options) {
154
181
  const args = this.buildArgs(sessionId, promptMessage);
155
- const sessionLogCursor = await this.captureSessionLogCursor(sessionId);
156
- const stdout = await this.execOpenClaw(args);
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"}`);
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
+ }
230
+ this.verboseLog(`exec_complete session=${sessionId} stdoutChars=${stdout.length}`);
157
231
  let parsed;
158
232
  let parseError;
159
233
  try {
@@ -167,11 +241,15 @@ export class OpenClawAgentBridge {
167
241
  parseError = error;
168
242
  this.log(`openclaw_agent_parse_failed session=${sessionId} stdoutChars=${stdout.length} stdoutPreview=${JSON.stringify(stdout.slice(0, 400))}`);
169
243
  }
170
- const collectedMessages = await this.collectSessionMessages(sessionId, sessionLogCursor);
244
+ const collectedMessages = await this.collectSessionMessages(sessionId, sessionLogCursor, {
245
+ allowTrailingPartial: true,
246
+ });
247
+ await emitThinkingTrace(collectedMessages.traceEntries);
171
248
  const recoveredMessages = [
172
249
  ...collectedMessages.assistantMessages,
173
250
  ...(options?.includeArtifacts === false ? [] : collectedMessages.artifactMessages),
174
251
  ];
252
+ this.verboseLog(`session_log_delta session=${sessionId} assistantRecovered=${collectedMessages.assistantMessages.length} artifactRecovered=${collectedMessages.artifactMessages.length} includeArtifacts=${options?.includeArtifacts !== false}`);
175
253
  if (!parsed) {
176
254
  if (recoveredMessages.length > 0) {
177
255
  this.log(`session_log_fallback session=${sessionId} reason=parse_failed recoveredMessages=${recoveredMessages.length}`);
@@ -180,10 +258,19 @@ export class OpenClawAgentBridge {
180
258
  throw parseError;
181
259
  }
182
260
  try {
183
- const response = parseOpenClawAgentResult(parsed);
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}`);
184
271
  return options?.includeArtifacts === false
185
- ? response
186
- : mergeBridgeResponses(response, collectedMessages.artifactMessages);
272
+ ? authoritativeResponse
273
+ : mergeBridgeResponses(authoritativeResponse, collectedMessages.artifactMessages);
187
274
  }
188
275
  catch (error) {
189
276
  if (recoveredMessages.length > 0) {
@@ -202,50 +289,50 @@ export class OpenClawAgentBridge {
202
289
  async captureSessionLogCursor(sessionId) {
203
290
  const sessionLogPath = await this.resolveSessionLogPath(sessionId);
204
291
  if (!sessionLogPath) {
292
+ this.verboseLog(`session_log_cursor_missing session=${sessionId}`);
205
293
  return { sizeBytes: 0 };
206
294
  }
207
295
  const stat = await fs.stat(sessionLogPath);
296
+ this.verboseLog(`session_log_cursor session=${sessionId} logPath=${JSON.stringify(sessionLogPath)} sizeBytes=${stat.size}`);
208
297
  return {
209
298
  path: sessionLogPath,
210
299
  sizeBytes: stat.size,
211
300
  };
212
301
  }
213
- async collectSessionMessages(sessionId, cursor) {
214
- const sessionLogPath = cursor.path ?? (await this.resolveSessionLogPath(sessionId));
215
- if (!sessionLogPath) {
216
- this.log(`artifact_log_missing session=${sessionId}`);
217
- return {
218
- assistantMessages: [],
219
- artifactMessages: [],
220
- };
221
- }
222
- const sessionLogBuffer = await fs.readFile(sessionLogPath);
223
- const deltaBuffer = cursor.path === sessionLogPath
224
- ? sessionLogBuffer.subarray(Math.min(cursor.sizeBytes, sessionLogBuffer.length))
225
- : sessionLogBuffer;
226
- 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
+ }
227
308
  return {
228
309
  assistantMessages: [],
310
+ structuredAssistantMessages: [],
229
311
  artifactMessages: [],
312
+ nextCursor,
313
+ traceEntries: [],
230
314
  };
231
315
  }
232
- const entries = deltaBuffer
233
- .toString("utf8")
234
- .split(/\r?\n/gu)
235
- .map((line) => line.trim())
236
- .filter((line) => line !== "")
237
- .map((line) => JSON.parse(line));
238
- const assistantResults = entries.map((entry) => extractAssistantDisplayResult(entry));
239
- 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
+ });
240
327
  const seenPaths = new Set();
241
328
  const attachments = [];
242
329
  for (const entry of entries) {
243
330
  for (const mediaPath of extractMediaPaths(entry)) {
244
- const normalizedPath = normalizeMediaPath(mediaPath);
331
+ const normalizedPath = normalizeMediaPath(mediaPath, this.workspaceDir);
245
332
  if (seenPaths.has(normalizedPath)) {
246
333
  continue;
247
334
  }
248
- const attachment = await buildAttachmentFromMediaPath(normalizedPath);
335
+ const attachment = await buildAttachmentFromMediaPath(normalizedPath, this.workspaceDir);
249
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}`);
250
337
  attachments.push(attachment);
251
338
  seenPaths.add(normalizedPath);
@@ -254,20 +341,80 @@ export class OpenClawAgentBridge {
254
341
  const artifactMessages = attachments.length > 0
255
342
  ? [{ text: "", attachments }]
256
343
  : [];
257
- const assistantData = combineStructuredData(assistantResults).data;
344
+ const assistantData = combineStructuredData(assistantResults
345
+ .filter((result) => result.isStructured)
346
+ .map((result) => result.result)).data;
258
347
  if (attachments.length === 0) {
259
- 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")}`);
260
349
  return {
261
350
  assistantMessages,
351
+ structuredAssistantMessages,
262
352
  ...(assistantData !== undefined ? { assistantData } : {}),
263
353
  artifactMessages,
354
+ nextCursor,
355
+ traceEntries,
264
356
  };
265
357
  }
266
- 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")}`);
267
359
  return {
268
360
  assistantMessages,
361
+ structuredAssistantMessages,
269
362
  ...(assistantData !== undefined ? { assistantData } : {}),
270
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
+ },
271
418
  };
272
419
  }
273
420
  async resolveSessionLogPath(sessionId) {
@@ -281,6 +428,7 @@ export class OpenClawAgentBridge {
281
428
  const candidate = path.join(agentsDir, entry.name, "sessions", `${sessionId}.jsonl`);
282
429
  try {
283
430
  await fs.access(candidate);
431
+ this.verboseLog(`session_log_resolved session=${sessionId} logPath=${JSON.stringify(candidate)}`);
284
432
  return candidate;
285
433
  }
286
434
  catch (error) {
@@ -297,6 +445,7 @@ export class OpenClawAgentBridge {
297
445
  }
298
446
  throw error;
299
447
  }
448
+ this.verboseLog(`session_log_not_found session=${sessionId}`);
300
449
  return undefined;
301
450
  }
302
451
  async buildPromptMessage(sessionId, message, attachments) {
@@ -328,6 +477,7 @@ export class OpenClawAgentBridge {
328
477
  }
329
478
  const promptMessage = appendStructuredResponseContract(promptBody !== "" ? promptBody : "The user sent a message that requires a reply.");
330
479
  this.log(`prompt_ready session=${sessionId} stagedAttachments=${stagedAttachments.length} textChars=${trimmed.length} contractVersion=${PRIVATECLAW_RESPONSE_CONTRACT_VERSION}`);
480
+ this.verboseLog(`prompt_body_ready session=${sessionId} promptChars=${promptMessage.length} trimmedTextChars=${trimmed.length} stagedAttachments=${stagedAttachments.length}`);
331
481
  return promptMessage;
332
482
  }
333
483
  async stageAttachments(sessionId, attachments) {
@@ -507,14 +657,66 @@ function buildNoDisplayPayloadNotice(message, parsed) {
507
657
  return `OpenClaw completed the request, but it did not return a text reply through the agent bridge.${extraSummary}`;
508
658
  }
509
659
  function mergeBridgeResponses(primary, supplemental) {
510
- if (supplemental.length === 0) {
660
+ const dedupedSupplemental = dedupeSupplementalMessages(primary, supplemental);
661
+ if (dedupedSupplemental.length === 0) {
511
662
  return primary;
512
663
  }
513
664
  return toBridgeResponse([
514
665
  ...normalizeBridgeResponse(primary),
515
- ...supplemental,
666
+ ...dedupedSupplemental,
516
667
  ], extractBridgeResponseData(primary));
517
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
+ }
518
720
  function normalizeBridgeResponse(response) {
519
721
  if (typeof response === "string") {
520
722
  return [{ text: response }];
@@ -549,6 +751,93 @@ function toBridgeResponse(messages, data) {
549
751
  ...(data !== undefined ? { data } : {}),
550
752
  };
551
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
+ }
552
841
  function extractMediaPaths(entry) {
553
842
  if (entry.type !== "message" || entry.message?.role !== "toolResult" || entry.message.isError) {
554
843
  return [];
@@ -571,25 +860,22 @@ function extractMediaPaths(entry) {
571
860
  }
572
861
  return [...mediaPaths];
573
862
  }
574
- function extractAssistantDisplayResult(entry) {
863
+ function extractAssistantDisplayResult(entry, options) {
575
864
  if (entry.type !== "message" || entry.message?.role !== "assistant" || entry.message.isError) {
576
- return { messages: [] };
865
+ return { result: { messages: [] }, isStructured: false };
577
866
  }
578
- const parts = (entry.message.content ?? [])
579
- .flatMap((contentItem) => contentItem.type === "text" && typeof contentItem.text === "string"
580
- ? [contentItem.text.trim()]
581
- : [])
582
- .filter((text) => text !== "");
583
- if (parts.length === 0) {
584
- return { messages: [] };
867
+ const rawText = readEntryTextContent(entry);
868
+ if (rawText === "") {
869
+ return { result: { messages: [] }, isStructured: false };
585
870
  }
586
- const rawText = parts.join("\n\n");
587
- const structuredResult = parseStructuredResponseResult(rawText);
871
+ const structuredResult = parseStructuredResponseResult(rawText, options?.workspaceDir ? { workspaceDir: options.workspaceDir } : undefined);
588
872
  if (structuredResult) {
589
- return structuredResult;
873
+ return { result: structuredResult, isStructured: true };
590
874
  }
591
875
  const fallbackText = stripStructuredResponseBlock(rawText);
592
- return fallbackText !== "" ? { messages: [{ text: fallbackText }] } : { messages: [] };
876
+ return fallbackText !== ""
877
+ ? { result: { messages: [{ text: fallbackText }] }, isStructured: false }
878
+ : { result: { messages: [] }, isStructured: false };
593
879
  }
594
880
  function appendStructuredResponseContract(prompt) {
595
881
  return `${prompt}\n\n${buildStructuredResponseContractPrompt()}`;
@@ -621,19 +907,83 @@ function buildStructuredResponseContractPrompt() {
621
907
  `- Use this JSON shape: {\"version\":${PRIVATECLAW_RESPONSE_CONTRACT_VERSION},\"messages\":[{\"text\":\"...\"}],\"data\":{}}`,
622
908
  "- Always include at least one messages entry.",
623
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.",
624
913
  "- Use data for optional machine-readable extraction results that PrivateClaw may consume in future file-processing flows.",
625
914
  "- Do not wrap the JSON in markdown fences.",
626
915
  ].join("\n");
627
916
  }
628
- 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) {
629
968
  const structured = parseStructuredResponseBlock(raw);
630
969
  if (!structured?.messages || structured.messages.length === 0) {
631
970
  return undefined;
632
971
  }
633
- const messages = structured.messages.flatMap((message) => {
972
+ const messages = [];
973
+ for (const message of structured.messages) {
634
974
  const text = typeof message.text === "string" ? message.text.trim() : "";
635
- return text !== "" ? [{ text }] : [];
636
- });
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
+ }
637
987
  if (messages.length === 0) {
638
988
  return undefined;
639
989
  }
@@ -643,27 +993,232 @@ function parseStructuredResponseResult(raw) {
643
993
  };
644
994
  }
645
995
  function parseStructuredResponseBlock(raw) {
646
- const match = raw.match(buildStructuredResponseBlockPattern("u"));
647
- const payload = match?.[1]?.trim();
996
+ const payload = extractStructuredResponsePayload(raw);
648
997
  if (!payload) {
649
998
  return undefined;
650
999
  }
1000
+ const parsed = parseStructuredResponseJson(payload);
1001
+ if (!parsed ||
1002
+ parsed.version !== PRIVATECLAW_RESPONSE_CONTRACT_VERSION ||
1003
+ !Array.isArray(parsed.messages)) {
1004
+ return undefined;
1005
+ }
1006
+ return parsed;
1007
+ }
1008
+ function stripStructuredResponseBlock(raw) {
1009
+ let stripped = raw;
1010
+ for (const pattern of buildStructuredResponseBlockPatterns("gu")) {
1011
+ stripped = stripped.replace(pattern, "");
1012
+ }
1013
+ return stripped.trim();
1014
+ }
1015
+ function buildStructuredResponseBlockPattern(flags) {
1016
+ return new RegExp(`${escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_START)}([\\s\\S]*?)${escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_END)}`, flags);
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
+ }
651
1086
  try {
652
- const parsed = JSON.parse(payload);
653
- if (parsed.version !== PRIVATECLAW_RESPONSE_CONTRACT_VERSION || !Array.isArray(parsed.messages)) {
1087
+ const filePath = resolveStructuredAttachmentFilePath(rawValue, workspaceDir);
1088
+ if (!filePath) {
654
1089
  return undefined;
655
1090
  }
656
- return parsed;
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
+ };
657
1099
  }
658
1100
  catch {
659
1101
  return undefined;
660
1102
  }
661
1103
  }
662
- function stripStructuredResponseBlock(raw) {
663
- return raw.replace(buildStructuredResponseBlockPattern("gu"), "").trim();
1104
+ function parseStructuredResponseJson(payload) {
1105
+ try {
1106
+ return JSON.parse(payload);
1107
+ }
1108
+ catch {
1109
+ const normalizedPayload = stripJsonTrailingCommas(payload);
1110
+ if (normalizedPayload === payload) {
1111
+ return undefined;
1112
+ }
1113
+ try {
1114
+ return JSON.parse(normalizedPayload);
1115
+ }
1116
+ catch {
1117
+ return undefined;
1118
+ }
1119
+ }
664
1120
  }
665
- function buildStructuredResponseBlockPattern(flags) {
666
- return new RegExp(`${escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_START)}([\\s\\S]*?)${escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_END)}`, flags);
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
+ }
1182
+ function stripJsonTrailingCommas(payload) {
1183
+ let normalized = "";
1184
+ let inString = false;
1185
+ let escaped = false;
1186
+ for (let index = 0; index < payload.length; index += 1) {
1187
+ const character = payload[index];
1188
+ if (escaped) {
1189
+ normalized += character;
1190
+ escaped = false;
1191
+ continue;
1192
+ }
1193
+ if (inString) {
1194
+ normalized += character;
1195
+ if (character === "\\") {
1196
+ escaped = true;
1197
+ }
1198
+ else if (character === '"') {
1199
+ inString = false;
1200
+ }
1201
+ continue;
1202
+ }
1203
+ if (character === '"') {
1204
+ normalized += character;
1205
+ inString = true;
1206
+ continue;
1207
+ }
1208
+ if (character === ",") {
1209
+ let lookahead = index + 1;
1210
+ while (lookahead < payload.length &&
1211
+ /\s/u.test(payload[lookahead])) {
1212
+ lookahead += 1;
1213
+ }
1214
+ const nextCharacter = payload[lookahead];
1215
+ if (nextCharacter === "]" || nextCharacter === "}") {
1216
+ continue;
1217
+ }
1218
+ }
1219
+ normalized += character;
1220
+ }
1221
+ return normalized;
667
1222
  }
668
1223
  function escapeRegExpLiteral(value) {
669
1224
  return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
@@ -690,8 +1245,8 @@ function normalizeStructuredData(value) {
690
1245
  function extractBridgeResponseData(response) {
691
1246
  return typeof response === "string" ? undefined : response.data;
692
1247
  }
693
- async function buildAttachmentFromMediaPath(mediaPath) {
694
- const filePath = normalizeMediaPath(mediaPath);
1248
+ async function buildAttachmentFromMediaPath(mediaPath, workspaceDir = DEFAULT_WORKSPACE_DIR) {
1249
+ const filePath = normalizeMediaPath(mediaPath, workspaceDir);
695
1250
  const fileBytes = await fs.readFile(filePath);
696
1251
  const fileName = path.basename(filePath) || `media-${randomUUID()}`;
697
1252
  return {
@@ -702,12 +1257,16 @@ async function buildAttachmentFromMediaPath(mediaPath) {
702
1257
  dataBase64: fileBytes.toString("base64"),
703
1258
  };
704
1259
  }
705
- function normalizeMediaPath(mediaPath) {
1260
+ function normalizeMediaPath(mediaPath, workspaceDir = DEFAULT_WORKSPACE_DIR) {
706
1261
  const trimmed = mediaPath.trim();
707
1262
  if (trimmed.startsWith("file://")) {
708
- return fileURLToPath(trimmed);
1263
+ return path.resolve(fileURLToPath(trimmed));
709
1264
  }
710
- 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));
711
1270
  }
712
1271
  function buildVoiceTranscriptionSessionId(sessionId, requestId) {
713
1272
  return [