@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.
- package/dist/bridges/openai-compatible-bridge.js +1 -0
- package/dist/bridges/openai-compatible-bridge.js.map +1 -1
- package/dist/bridges/openclaw-agent-bridge.d.ts +7 -2
- package/dist/bridges/openclaw-agent-bridge.js +554 -68
- package/dist/bridges/openclaw-agent-bridge.js.map +1 -1
- package/dist/provider.d.ts +12 -1
- package/dist/provider.js +159 -6
- package/dist/provider.js.map +1 -1
- package/dist/types.d.ts +13 -2
- package/package.json +2 -2
- package/src/bridges/openai-compatible-bridge.ts +1 -0
- package/src/bridges/openclaw-agent-bridge.test.ts +572 -0
- package/src/bridges/openclaw-agent-bridge.ts +709 -75
- package/src/provider.test.ts +375 -0
- package/src/provider.ts +203 -8
- package/src/types.ts +17 -1
|
@@ -1,6 +1,10 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
PrivateClawAttachment,
|
|
3
|
+
PrivateClawThinkingEntry,
|
|
4
|
+
} from "@privateclaw/protocol";
|
|
2
5
|
import { spawn } from "node:child_process";
|
|
3
6
|
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
4
8
|
import fs from "node:fs/promises";
|
|
5
9
|
import os from "node:os";
|
|
6
10
|
import path from "node:path";
|
|
@@ -10,6 +14,7 @@ import type {
|
|
|
10
14
|
BridgeResponse,
|
|
11
15
|
PrivateClawAgentBridge,
|
|
12
16
|
PrivateClawAudioTranscriptionRequest,
|
|
17
|
+
PrivateClawThinkingTraceSnapshot,
|
|
13
18
|
PrivateClawVerboseController,
|
|
14
19
|
} from "../types.js";
|
|
15
20
|
|
|
@@ -51,6 +56,8 @@ interface OpenClawSessionLogCursor {
|
|
|
51
56
|
|
|
52
57
|
interface OpenClawSessionLogEntry {
|
|
53
58
|
type?: string;
|
|
59
|
+
id?: string;
|
|
60
|
+
timestamp?: string;
|
|
54
61
|
message?: {
|
|
55
62
|
role?: string;
|
|
56
63
|
toolName?: string;
|
|
@@ -65,8 +72,16 @@ interface OpenClawSessionLogEntry {
|
|
|
65
72
|
};
|
|
66
73
|
}
|
|
67
74
|
|
|
75
|
+
interface PrivateClawStructuredMessageAttachment {
|
|
76
|
+
name?: string;
|
|
77
|
+
mimeType?: string;
|
|
78
|
+
dataBase64?: string;
|
|
79
|
+
filePath?: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
68
82
|
interface PrivateClawStructuredMessage {
|
|
69
83
|
text?: string | null;
|
|
84
|
+
attachments?: PrivateClawStructuredMessageAttachment[];
|
|
70
85
|
}
|
|
71
86
|
|
|
72
87
|
interface PrivateClawStructuredResponse {
|
|
@@ -85,10 +100,23 @@ interface NormalizedBridgeMessage {
|
|
|
85
100
|
readonly attachments?: PrivateClawAttachment[];
|
|
86
101
|
}
|
|
87
102
|
|
|
103
|
+
interface ExtractedAssistantDisplayResult {
|
|
104
|
+
readonly result: NormalizedBridgeResult;
|
|
105
|
+
readonly isStructured: boolean;
|
|
106
|
+
}
|
|
107
|
+
|
|
88
108
|
interface CollectedSessionMessages {
|
|
89
109
|
readonly assistantMessages: NormalizedBridgeMessage[];
|
|
110
|
+
readonly structuredAssistantMessages: NormalizedBridgeMessage[];
|
|
90
111
|
readonly assistantData?: unknown;
|
|
91
112
|
readonly artifactMessages: NormalizedBridgeMessage[];
|
|
113
|
+
readonly nextCursor: OpenClawSessionLogCursor;
|
|
114
|
+
readonly traceEntries: PrivateClawThinkingEntry[];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface SessionLogEntriesResult {
|
|
118
|
+
readonly entries: OpenClawSessionLogEntry[];
|
|
119
|
+
readonly nextCursor: OpenClawSessionLogCursor;
|
|
92
120
|
}
|
|
93
121
|
|
|
94
122
|
class OpenClawAgentNoDisplayPayloadError extends Error {
|
|
@@ -137,6 +165,9 @@ const XML_ENTITY_PATTERN = /&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);/giu;
|
|
|
137
165
|
const PRIVATECLAW_RESPONSE_CONTRACT_VERSION = 1;
|
|
138
166
|
const PRIVATECLAW_RESPONSE_TAG_START = "<privateclaw-response>";
|
|
139
167
|
const PRIVATECLAW_RESPONSE_TAG_END = "</privateclaw-response>";
|
|
168
|
+
const LIVE_TRACE_POLL_INTERVAL_MS = 150;
|
|
169
|
+
const MAX_TRACE_ENTRY_CHARS = 3200;
|
|
170
|
+
const MAX_TRACE_SUMMARY_CHARS = 180;
|
|
140
171
|
const DOCX_MIME_TYPES = new Set<string>([
|
|
141
172
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
142
173
|
]);
|
|
@@ -153,9 +184,14 @@ const TEXT_LIKE_MIME_TYPES = new Set<string>([
|
|
|
153
184
|
"image/svg+xml",
|
|
154
185
|
]);
|
|
155
186
|
|
|
156
|
-
export function parseOpenClawAgentOutput(
|
|
187
|
+
export function parseOpenClawAgentOutput(
|
|
188
|
+
stdout: string,
|
|
189
|
+
options?: {
|
|
190
|
+
workspaceDir?: string;
|
|
191
|
+
},
|
|
192
|
+
): BridgeResponse {
|
|
157
193
|
const parsed = parseOpenClawAgentJson(stdout);
|
|
158
|
-
return parseOpenClawAgentResult(parsed);
|
|
194
|
+
return parseOpenClawAgentResult(parsed, options);
|
|
159
195
|
}
|
|
160
196
|
|
|
161
197
|
export function resolveOpenClawLaunchCommand(options: {
|
|
@@ -192,15 +228,34 @@ export function resolveOpenClawLaunchCommand(options: {
|
|
|
192
228
|
}
|
|
193
229
|
|
|
194
230
|
function parseOpenClawAgentJson(stdout: string): OpenClawAgentJsonResult {
|
|
195
|
-
|
|
231
|
+
const trimmed = stdout.trim();
|
|
232
|
+
try {
|
|
233
|
+
return JSON.parse(trimmed) as OpenClawAgentJsonResult;
|
|
234
|
+
} catch (error) {
|
|
235
|
+
const embeddedPayload = extractEmbeddedJsonPayload(trimmed);
|
|
236
|
+
if (!embeddedPayload) {
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
return JSON.parse(embeddedPayload) as OpenClawAgentJsonResult;
|
|
240
|
+
}
|
|
196
241
|
}
|
|
197
242
|
|
|
198
|
-
function parseOpenClawAgentResult(
|
|
199
|
-
|
|
243
|
+
function parseOpenClawAgentResult(
|
|
244
|
+
parsed: OpenClawAgentJsonResult,
|
|
245
|
+
options?: {
|
|
246
|
+
workspaceDir?: string;
|
|
247
|
+
},
|
|
248
|
+
): BridgeResponse {
|
|
249
|
+
const result = extractDisplayResult(parsed, options);
|
|
200
250
|
return toBridgeResponse(result.messages, result.data);
|
|
201
251
|
}
|
|
202
252
|
|
|
203
|
-
function extractDisplayResult(
|
|
253
|
+
function extractDisplayResult(
|
|
254
|
+
parsed: OpenClawAgentJsonResult,
|
|
255
|
+
options?: {
|
|
256
|
+
workspaceDir?: string;
|
|
257
|
+
},
|
|
258
|
+
): NormalizedBridgeResult {
|
|
204
259
|
const payloads = parsed.result?.payloads ?? parsed.payloads ?? [];
|
|
205
260
|
const hasAlternatePayloadShape = !parsed.status && payloads.length > 0;
|
|
206
261
|
if (parsed.status && parsed.status !== "ok") {
|
|
@@ -219,7 +274,7 @@ function extractDisplayResult(parsed: OpenClawAgentJsonResult): NormalizedBridge
|
|
|
219
274
|
if (typeof candidate !== "string") {
|
|
220
275
|
return [];
|
|
221
276
|
}
|
|
222
|
-
const result = parseStructuredResponseResult(candidate);
|
|
277
|
+
const result = parseStructuredResponseResult(candidate, options);
|
|
223
278
|
return result ? [result] : [];
|
|
224
279
|
}),
|
|
225
280
|
);
|
|
@@ -247,6 +302,7 @@ function extractDisplayResult(parsed: OpenClawAgentJsonResult): NormalizedBridge
|
|
|
247
302
|
}
|
|
248
303
|
|
|
249
304
|
export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
305
|
+
readonly supportsThinkingTrace = true;
|
|
250
306
|
private readonly executable: string;
|
|
251
307
|
private readonly executableArgs: string[];
|
|
252
308
|
private readonly executableUsesShell: boolean;
|
|
@@ -285,6 +341,9 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
285
341
|
sessionId: string;
|
|
286
342
|
message: string;
|
|
287
343
|
attachments?: ReadonlyArray<PrivateClawAttachment>;
|
|
344
|
+
onThinkingTrace?: (
|
|
345
|
+
snapshot: PrivateClawThinkingTraceSnapshot,
|
|
346
|
+
) => void | Promise<void>;
|
|
288
347
|
}): Promise<BridgeResponse> {
|
|
289
348
|
const promptMessage = await this.buildPromptMessage(
|
|
290
349
|
params.sessionId,
|
|
@@ -297,6 +356,9 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
297
356
|
return this.executePrompt(params.sessionId, promptMessage, {
|
|
298
357
|
includeArtifacts: true,
|
|
299
358
|
noDisplayFallbackMessage: params.message,
|
|
359
|
+
...(params.onThinkingTrace
|
|
360
|
+
? { onThinkingTrace: params.onThinkingTrace }
|
|
361
|
+
: {}),
|
|
300
362
|
});
|
|
301
363
|
}
|
|
302
364
|
|
|
@@ -341,14 +403,66 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
341
403
|
options?: {
|
|
342
404
|
includeArtifacts?: boolean;
|
|
343
405
|
noDisplayFallbackMessage?: string;
|
|
406
|
+
onThinkingTrace?: (
|
|
407
|
+
snapshot: PrivateClawThinkingTraceSnapshot,
|
|
408
|
+
) => void | Promise<void>;
|
|
344
409
|
},
|
|
345
410
|
): Promise<BridgeResponse> {
|
|
346
411
|
const args = this.buildArgs(sessionId, promptMessage);
|
|
347
412
|
this.verboseLog(
|
|
348
413
|
`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"}`,
|
|
349
414
|
);
|
|
350
|
-
|
|
351
|
-
|
|
415
|
+
let sessionLogCursor = await this.captureSessionLogCursor(sessionId);
|
|
416
|
+
let latestTraceEntries: PrivateClawThinkingEntry[] = [];
|
|
417
|
+
const emitThinkingTrace = async (
|
|
418
|
+
newEntries: ReadonlyArray<PrivateClawThinkingEntry>,
|
|
419
|
+
): Promise<void> => {
|
|
420
|
+
if (!options?.onThinkingTrace || newEntries.length === 0) {
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
latestTraceEntries = [...latestTraceEntries, ...newEntries];
|
|
424
|
+
await options.onThinkingTrace({
|
|
425
|
+
entries: latestTraceEntries.map((entry) => ({ ...entry })),
|
|
426
|
+
sentAt: latestTraceEntries[latestTraceEntries.length - 1]?.sentAt ?? nowIso(),
|
|
427
|
+
summary: summarizeThinkingTrace(latestTraceEntries),
|
|
428
|
+
});
|
|
429
|
+
};
|
|
430
|
+
const stdoutPromise = this.execOpenClaw(args);
|
|
431
|
+
if (options?.onThinkingTrace) {
|
|
432
|
+
let pending = true;
|
|
433
|
+
void stdoutPromise.then(
|
|
434
|
+
() => {
|
|
435
|
+
pending = false;
|
|
436
|
+
},
|
|
437
|
+
() => {
|
|
438
|
+
pending = false;
|
|
439
|
+
},
|
|
440
|
+
);
|
|
441
|
+
while (pending) {
|
|
442
|
+
await delay(LIVE_TRACE_POLL_INTERVAL_MS);
|
|
443
|
+
if (!pending) {
|
|
444
|
+
break;
|
|
445
|
+
}
|
|
446
|
+
const liveMessages = await this.collectSessionMessages(sessionId, sessionLogCursor, {
|
|
447
|
+
allowTrailingPartial: false,
|
|
448
|
+
});
|
|
449
|
+
sessionLogCursor = liveMessages.nextCursor;
|
|
450
|
+
await emitThinkingTrace(liveMessages.traceEntries);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
let stdout: string;
|
|
454
|
+
try {
|
|
455
|
+
stdout = await stdoutPromise;
|
|
456
|
+
} catch (error) {
|
|
457
|
+
if (options?.onThinkingTrace) {
|
|
458
|
+
const finalTraceDelta = await this.collectSessionMessages(sessionId, sessionLogCursor, {
|
|
459
|
+
allowTrailingPartial: true,
|
|
460
|
+
});
|
|
461
|
+
sessionLogCursor = finalTraceDelta.nextCursor;
|
|
462
|
+
await emitThinkingTrace(finalTraceDelta.traceEntries);
|
|
463
|
+
}
|
|
464
|
+
throw error;
|
|
465
|
+
}
|
|
352
466
|
this.verboseLog(`exec_complete session=${sessionId} stdoutChars=${stdout.length}`);
|
|
353
467
|
let parsed: OpenClawAgentJsonResult | undefined;
|
|
354
468
|
let parseError: unknown;
|
|
@@ -368,7 +482,10 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
368
482
|
`openclaw_agent_parse_failed session=${sessionId} stdoutChars=${stdout.length} stdoutPreview=${JSON.stringify(stdout.slice(0, 400))}`,
|
|
369
483
|
);
|
|
370
484
|
}
|
|
371
|
-
const collectedMessages = await this.collectSessionMessages(sessionId, sessionLogCursor
|
|
485
|
+
const collectedMessages = await this.collectSessionMessages(sessionId, sessionLogCursor, {
|
|
486
|
+
allowTrailingPartial: true,
|
|
487
|
+
});
|
|
488
|
+
await emitThinkingTrace(collectedMessages.traceEntries);
|
|
372
489
|
const recoveredMessages = [
|
|
373
490
|
...collectedMessages.assistantMessages,
|
|
374
491
|
...(options?.includeArtifacts === false ? [] : collectedMessages.artifactMessages),
|
|
@@ -386,13 +503,30 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
386
503
|
throw parseError;
|
|
387
504
|
}
|
|
388
505
|
try {
|
|
389
|
-
const response = parseOpenClawAgentResult(parsed
|
|
506
|
+
const response = parseOpenClawAgentResult(parsed, {
|
|
507
|
+
workspaceDir: this.workspaceDir,
|
|
508
|
+
});
|
|
509
|
+
const authoritativeResponse =
|
|
510
|
+
collectedMessages.structuredAssistantMessages.length > 0
|
|
511
|
+
? toBridgeResponse(
|
|
512
|
+
collectedMessages.structuredAssistantMessages,
|
|
513
|
+
collectedMessages.assistantData,
|
|
514
|
+
)
|
|
515
|
+
: response;
|
|
516
|
+
if (collectedMessages.structuredAssistantMessages.length > 0) {
|
|
517
|
+
this.log(
|
|
518
|
+
`session_log_structured_override session=${sessionId} directMessages=${typeof response === "string" ? 1 : response.messages.length} recoveredMessages=${collectedMessages.structuredAssistantMessages.length}`,
|
|
519
|
+
);
|
|
520
|
+
}
|
|
390
521
|
this.verboseLog(
|
|
391
|
-
`response_ready session=${sessionId} directMessages=${typeof response === "string" ? 1 : response.messages.length} artifactMessages=${options?.includeArtifacts === false ? 0 : collectedMessages.artifactMessages.length}`,
|
|
522
|
+
`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}`,
|
|
392
523
|
);
|
|
393
524
|
return options?.includeArtifacts === false
|
|
394
|
-
?
|
|
395
|
-
: mergeBridgeResponses(
|
|
525
|
+
? authoritativeResponse
|
|
526
|
+
: mergeBridgeResponses(
|
|
527
|
+
authoritativeResponse,
|
|
528
|
+
collectedMessages.artifactMessages,
|
|
529
|
+
);
|
|
396
530
|
} catch (error) {
|
|
397
531
|
if (recoveredMessages.length > 0) {
|
|
398
532
|
this.log(
|
|
@@ -430,47 +564,49 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
430
564
|
private async collectSessionMessages(
|
|
431
565
|
sessionId: string,
|
|
432
566
|
cursor: OpenClawSessionLogCursor,
|
|
567
|
+
options?: {
|
|
568
|
+
allowTrailingPartial?: boolean;
|
|
569
|
+
},
|
|
433
570
|
): Promise<CollectedSessionMessages> {
|
|
434
|
-
const
|
|
435
|
-
if (
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
artifactMessages: [],
|
|
440
|
-
};
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
const sessionLogBuffer = await fs.readFile(sessionLogPath);
|
|
444
|
-
const deltaBuffer =
|
|
445
|
-
cursor.path === sessionLogPath
|
|
446
|
-
? sessionLogBuffer.subarray(Math.min(cursor.sizeBytes, sessionLogBuffer.length))
|
|
447
|
-
: sessionLogBuffer;
|
|
448
|
-
if (deltaBuffer.length === 0) {
|
|
571
|
+
const { entries, nextCursor } = await this.readSessionLogEntries(sessionId, cursor, options);
|
|
572
|
+
if (entries.length === 0) {
|
|
573
|
+
if (!nextCursor.path) {
|
|
574
|
+
this.log(`artifact_log_missing session=${sessionId}`);
|
|
575
|
+
}
|
|
449
576
|
return {
|
|
450
577
|
assistantMessages: [],
|
|
578
|
+
structuredAssistantMessages: [],
|
|
451
579
|
artifactMessages: [],
|
|
580
|
+
nextCursor,
|
|
581
|
+
traceEntries: [],
|
|
452
582
|
};
|
|
453
583
|
}
|
|
454
584
|
|
|
455
|
-
const
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
const
|
|
585
|
+
const assistantResults = entries.map((entry) =>
|
|
586
|
+
extractAssistantDisplayResult(entry, {
|
|
587
|
+
workspaceDir: this.workspaceDir,
|
|
588
|
+
}),
|
|
589
|
+
);
|
|
590
|
+
const assistantMessages = assistantResults.flatMap(
|
|
591
|
+
(result) => result.result.messages,
|
|
592
|
+
);
|
|
593
|
+
const structuredAssistantMessages = assistantResults
|
|
594
|
+
.filter((result) => result.isStructured)
|
|
595
|
+
.flatMap((result) => result.result.messages);
|
|
596
|
+
const traceEntries = entries.flatMap((entry) => {
|
|
597
|
+
const traceEntry = extractThinkingTraceEntry(entry);
|
|
598
|
+
return traceEntry ? [traceEntry] : [];
|
|
599
|
+
});
|
|
464
600
|
|
|
465
601
|
const seenPaths = new Set<string>();
|
|
466
602
|
const attachments: PrivateClawAttachment[] = [];
|
|
467
603
|
for (const entry of entries) {
|
|
468
604
|
for (const mediaPath of extractMediaPaths(entry)) {
|
|
469
|
-
const normalizedPath = normalizeMediaPath(mediaPath);
|
|
605
|
+
const normalizedPath = normalizeMediaPath(mediaPath, this.workspaceDir);
|
|
470
606
|
if (seenPaths.has(normalizedPath)) {
|
|
471
607
|
continue;
|
|
472
608
|
}
|
|
473
|
-
const attachment = await buildAttachmentFromMediaPath(normalizedPath);
|
|
609
|
+
const attachment = await buildAttachmentFromMediaPath(normalizedPath, this.workspaceDir);
|
|
474
610
|
this.log(
|
|
475
611
|
`artifact_recovered session=${sessionId} mediaPath=${JSON.stringify(mediaPath)} normalizedPath=${JSON.stringify(normalizedPath)} name=${JSON.stringify(attachment.name)} mimeType=${attachment.mimeType} sizeBytes=${attachment.sizeBytes}`,
|
|
476
612
|
);
|
|
@@ -483,26 +619,99 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
483
619
|
attachments.length > 0
|
|
484
620
|
? [{ text: "", attachments } satisfies NormalizedBridgeMessage]
|
|
485
621
|
: [];
|
|
486
|
-
const assistantData = combineStructuredData(
|
|
622
|
+
const assistantData = combineStructuredData(
|
|
623
|
+
assistantResults
|
|
624
|
+
.filter((result) => result.isStructured)
|
|
625
|
+
.map((result) => result.result),
|
|
626
|
+
).data;
|
|
487
627
|
|
|
488
628
|
if (attachments.length === 0) {
|
|
489
629
|
this.log(
|
|
490
|
-
`artifact_scan_complete session=${sessionId} entries=${entries.length} assistantRecovered=${assistantMessages.length} recovered=0 logPath=${JSON.stringify(
|
|
630
|
+
`artifact_scan_complete session=${sessionId} entries=${entries.length} assistantRecovered=${assistantMessages.length} recovered=0 logPath=${JSON.stringify(nextCursor.path ?? "missing")}`,
|
|
491
631
|
);
|
|
492
632
|
return {
|
|
493
633
|
assistantMessages,
|
|
634
|
+
structuredAssistantMessages,
|
|
494
635
|
...(assistantData !== undefined ? { assistantData } : {}),
|
|
495
636
|
artifactMessages,
|
|
637
|
+
nextCursor,
|
|
638
|
+
traceEntries,
|
|
496
639
|
};
|
|
497
640
|
}
|
|
498
641
|
|
|
499
642
|
this.log(
|
|
500
|
-
`artifact_scan_complete session=${sessionId} entries=${entries.length} assistantRecovered=${assistantMessages.length} recovered=${attachments.length} logPath=${JSON.stringify(
|
|
643
|
+
`artifact_scan_complete session=${sessionId} entries=${entries.length} assistantRecovered=${assistantMessages.length} recovered=${attachments.length} logPath=${JSON.stringify(nextCursor.path ?? "missing")}`,
|
|
501
644
|
);
|
|
502
645
|
return {
|
|
503
646
|
assistantMessages,
|
|
647
|
+
structuredAssistantMessages,
|
|
504
648
|
...(assistantData !== undefined ? { assistantData } : {}),
|
|
505
649
|
artifactMessages,
|
|
650
|
+
nextCursor,
|
|
651
|
+
traceEntries,
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
private async readSessionLogEntries(
|
|
656
|
+
sessionId: string,
|
|
657
|
+
cursor: OpenClawSessionLogCursor,
|
|
658
|
+
options?: {
|
|
659
|
+
allowTrailingPartial?: boolean;
|
|
660
|
+
},
|
|
661
|
+
): Promise<SessionLogEntriesResult> {
|
|
662
|
+
const sessionLogPath = cursor.path ?? (await this.resolveSessionLogPath(sessionId));
|
|
663
|
+
if (!sessionLogPath) {
|
|
664
|
+
return {
|
|
665
|
+
entries: [],
|
|
666
|
+
nextCursor: cursor,
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
const sessionLogBuffer = await fs.readFile(sessionLogPath);
|
|
671
|
+
const startOffset =
|
|
672
|
+
cursor.path === sessionLogPath
|
|
673
|
+
? Math.min(cursor.sizeBytes, sessionLogBuffer.length)
|
|
674
|
+
: 0;
|
|
675
|
+
const deltaBuffer = sessionLogBuffer.subarray(startOffset);
|
|
676
|
+
if (deltaBuffer.length === 0) {
|
|
677
|
+
return {
|
|
678
|
+
entries: [],
|
|
679
|
+
nextCursor: {
|
|
680
|
+
path: sessionLogPath,
|
|
681
|
+
sizeBytes: sessionLogBuffer.length,
|
|
682
|
+
},
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const deltaText = deltaBuffer.toString("utf8");
|
|
687
|
+
let parseText = deltaText;
|
|
688
|
+
let nextSize = sessionLogBuffer.length;
|
|
689
|
+
if (!options?.allowTrailingPartial && !deltaText.endsWith("\n")) {
|
|
690
|
+
const lastNewlineIndex = deltaText.lastIndexOf("\n");
|
|
691
|
+
if (lastNewlineIndex < 0) {
|
|
692
|
+
return {
|
|
693
|
+
entries: [],
|
|
694
|
+
nextCursor: {
|
|
695
|
+
path: sessionLogPath,
|
|
696
|
+
sizeBytes: startOffset,
|
|
697
|
+
},
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
parseText = deltaText.slice(0, lastNewlineIndex + 1);
|
|
701
|
+
nextSize = startOffset + Buffer.byteLength(parseText, "utf8");
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const entries = parseText
|
|
705
|
+
.split(/\r?\n/gu)
|
|
706
|
+
.map((line) => line.trim())
|
|
707
|
+
.filter((line) => line !== "")
|
|
708
|
+
.map((line) => JSON.parse(line) as OpenClawSessionLogEntry);
|
|
709
|
+
return {
|
|
710
|
+
entries,
|
|
711
|
+
nextCursor: {
|
|
712
|
+
path: sessionLogPath,
|
|
713
|
+
sizeBytes: nextSize,
|
|
714
|
+
},
|
|
506
715
|
};
|
|
507
716
|
}
|
|
508
717
|
|
|
@@ -831,19 +1040,82 @@ function mergeBridgeResponses(
|
|
|
831
1040
|
primary: BridgeResponse,
|
|
832
1041
|
supplemental: NormalizedBridgeMessage[],
|
|
833
1042
|
): BridgeResponse {
|
|
834
|
-
|
|
1043
|
+
const dedupedSupplemental = dedupeSupplementalMessages(primary, supplemental);
|
|
1044
|
+
if (dedupedSupplemental.length === 0) {
|
|
835
1045
|
return primary;
|
|
836
1046
|
}
|
|
837
1047
|
|
|
838
1048
|
return toBridgeResponse(
|
|
839
1049
|
[
|
|
840
1050
|
...normalizeBridgeResponse(primary),
|
|
841
|
-
...
|
|
1051
|
+
...dedupedSupplemental,
|
|
842
1052
|
],
|
|
843
1053
|
extractBridgeResponseData(primary),
|
|
844
1054
|
);
|
|
845
1055
|
}
|
|
846
1056
|
|
|
1057
|
+
function dedupeSupplementalMessages(
|
|
1058
|
+
primary: BridgeResponse,
|
|
1059
|
+
supplemental: NormalizedBridgeMessage[],
|
|
1060
|
+
): NormalizedBridgeMessage[] {
|
|
1061
|
+
if (supplemental.length === 0) {
|
|
1062
|
+
return supplemental;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
const seenInlineData = new Set<string>();
|
|
1066
|
+
const seenUris = new Set<string>();
|
|
1067
|
+
for (const message of normalizeBridgeResponse(primary)) {
|
|
1068
|
+
for (const attachment of message.attachments ?? []) {
|
|
1069
|
+
const inlineData = attachment.dataBase64?.trim();
|
|
1070
|
+
if (inlineData) {
|
|
1071
|
+
seenInlineData.add(
|
|
1072
|
+
`${attachment.mimeType}:${attachment.sizeBytes}:${inlineData}`,
|
|
1073
|
+
);
|
|
1074
|
+
}
|
|
1075
|
+
const uri = attachment.uri?.trim();
|
|
1076
|
+
if (uri) {
|
|
1077
|
+
seenUris.add(uri);
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
return supplemental.flatMap((message) => {
|
|
1083
|
+
const dedupedAttachments = (message.attachments ?? []).filter((attachment) => {
|
|
1084
|
+
const inlineData = attachment.dataBase64?.trim();
|
|
1085
|
+
if (inlineData) {
|
|
1086
|
+
const key = `${attachment.mimeType}:${attachment.sizeBytes}:${inlineData}`;
|
|
1087
|
+
if (seenInlineData.has(key)) {
|
|
1088
|
+
return false;
|
|
1089
|
+
}
|
|
1090
|
+
seenInlineData.add(key);
|
|
1091
|
+
return true;
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
const uri = attachment.uri?.trim();
|
|
1095
|
+
if (uri) {
|
|
1096
|
+
if (seenUris.has(uri)) {
|
|
1097
|
+
return false;
|
|
1098
|
+
}
|
|
1099
|
+
seenUris.add(uri);
|
|
1100
|
+
}
|
|
1101
|
+
return true;
|
|
1102
|
+
});
|
|
1103
|
+
|
|
1104
|
+
if (message.text.trim() === "" && dedupedAttachments.length === 0) {
|
|
1105
|
+
return [];
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
return [
|
|
1109
|
+
{
|
|
1110
|
+
text: message.text,
|
|
1111
|
+
...(dedupedAttachments.length > 0
|
|
1112
|
+
? { attachments: dedupedAttachments }
|
|
1113
|
+
: {}),
|
|
1114
|
+
} satisfies NormalizedBridgeMessage,
|
|
1115
|
+
];
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
|
|
847
1119
|
function normalizeBridgeResponse(response: BridgeResponse): NormalizedBridgeMessage[] {
|
|
848
1120
|
if (typeof response === "string") {
|
|
849
1121
|
return [{ text: response }];
|
|
@@ -890,6 +1162,109 @@ function toBridgeResponse(
|
|
|
890
1162
|
};
|
|
891
1163
|
}
|
|
892
1164
|
|
|
1165
|
+
function nowIso(): string {
|
|
1166
|
+
return new Date().toISOString();
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
function delay(ms: number): Promise<void> {
|
|
1170
|
+
return new Promise((resolve) => {
|
|
1171
|
+
setTimeout(resolve, ms);
|
|
1172
|
+
});
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
function truncateThinkingTraceText(text: string): string {
|
|
1176
|
+
if (text.length <= MAX_TRACE_ENTRY_CHARS) {
|
|
1177
|
+
return text;
|
|
1178
|
+
}
|
|
1179
|
+
const hiddenChars = text.length - MAX_TRACE_ENTRY_CHARS;
|
|
1180
|
+
return [
|
|
1181
|
+
text.slice(0, MAX_TRACE_ENTRY_CHARS).trimEnd(),
|
|
1182
|
+
"",
|
|
1183
|
+
`… truncated ${hiddenChars} more characters`,
|
|
1184
|
+
].join("\n");
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
function truncateThinkingSummary(text: string): string {
|
|
1188
|
+
const trimmed = text.trim();
|
|
1189
|
+
if (trimmed.length <= MAX_TRACE_SUMMARY_CHARS) {
|
|
1190
|
+
return trimmed;
|
|
1191
|
+
}
|
|
1192
|
+
return `${trimmed.slice(0, MAX_TRACE_SUMMARY_CHARS - 1).trimEnd()}…`;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
function readEntryTextContent(entry: OpenClawSessionLogEntry): string {
|
|
1196
|
+
return (entry.message?.content ?? [])
|
|
1197
|
+
.flatMap((contentItem) =>
|
|
1198
|
+
contentItem.type === "text" && typeof contentItem.text === "string"
|
|
1199
|
+
? [contentItem.text.trim()]
|
|
1200
|
+
: [],
|
|
1201
|
+
)
|
|
1202
|
+
.filter((text) => text !== "")
|
|
1203
|
+
.join("\n\n");
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
function summarizeThinkingTrace(entries: ReadonlyArray<PrivateClawThinkingEntry>): string {
|
|
1207
|
+
const latestEntry = entries[entries.length - 1];
|
|
1208
|
+
if (!latestEntry) {
|
|
1209
|
+
return "";
|
|
1210
|
+
}
|
|
1211
|
+
const firstLine =
|
|
1212
|
+
latestEntry.text
|
|
1213
|
+
.split(/\r?\n/gu)
|
|
1214
|
+
.map((line: string) => line.trim())
|
|
1215
|
+
.find((line: string) => line !== "") ??
|
|
1216
|
+
latestEntry.title;
|
|
1217
|
+
if (latestEntry.kind === "action" && latestEntry.toolName) {
|
|
1218
|
+
return truncateThinkingSummary(`${latestEntry.toolName}: ${firstLine}`);
|
|
1219
|
+
}
|
|
1220
|
+
return truncateThinkingSummary(firstLine);
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
function extractThinkingTraceEntry(
|
|
1224
|
+
entry: OpenClawSessionLogEntry,
|
|
1225
|
+
): PrivateClawThinkingEntry | undefined {
|
|
1226
|
+
if (entry.type !== "message" || !entry.message) {
|
|
1227
|
+
return undefined;
|
|
1228
|
+
}
|
|
1229
|
+
const entryId = entry.id?.trim() || `trace-${randomUUID()}`;
|
|
1230
|
+
const sentAt = entry.timestamp?.trim() || nowIso();
|
|
1231
|
+
if (entry.message.role === "assistant") {
|
|
1232
|
+
const text = truncateThinkingTraceText(
|
|
1233
|
+
stripStructuredResponseBlock(readEntryTextContent(entry)),
|
|
1234
|
+
);
|
|
1235
|
+
if (text === "") {
|
|
1236
|
+
return undefined;
|
|
1237
|
+
}
|
|
1238
|
+
return {
|
|
1239
|
+
id: entryId,
|
|
1240
|
+
kind: entry.message.isError ? "error" : "thought",
|
|
1241
|
+
title: entry.message.isError ? "Assistant error" : "Thinking",
|
|
1242
|
+
text,
|
|
1243
|
+
sentAt,
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
if (entry.message.role !== "toolResult") {
|
|
1247
|
+
return undefined;
|
|
1248
|
+
}
|
|
1249
|
+
const toolName = entry.message.toolName?.trim();
|
|
1250
|
+
const toolText = readEntryTextContent(entry).replace(/^MEDIA:.+$/gmu, "").trim();
|
|
1251
|
+
return {
|
|
1252
|
+
id: entryId,
|
|
1253
|
+
kind: entry.message.isError ? "error" : "action",
|
|
1254
|
+
title: toolName ? `Tool • ${toolName}` : entry.message.isError ? "Tool error" : "Tool",
|
|
1255
|
+
text: truncateThinkingTraceText(
|
|
1256
|
+
toolText ||
|
|
1257
|
+
(entry.message.isError
|
|
1258
|
+
? "The tool call failed."
|
|
1259
|
+
: toolName
|
|
1260
|
+
? `Tool ${toolName} completed.`
|
|
1261
|
+
: "Tool completed."),
|
|
1262
|
+
),
|
|
1263
|
+
sentAt,
|
|
1264
|
+
...(toolName ? { toolName } : {}),
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
|
|
893
1268
|
function extractMediaPaths(entry: OpenClawSessionLogEntry): string[] {
|
|
894
1269
|
if (entry.type !== "message" || entry.message?.role !== "toolResult" || entry.message.isError) {
|
|
895
1270
|
return [];
|
|
@@ -916,31 +1291,32 @@ function extractMediaPaths(entry: OpenClawSessionLogEntry): string[] {
|
|
|
916
1291
|
return [...mediaPaths];
|
|
917
1292
|
}
|
|
918
1293
|
|
|
919
|
-
function extractAssistantDisplayResult(
|
|
1294
|
+
function extractAssistantDisplayResult(
|
|
1295
|
+
entry: OpenClawSessionLogEntry,
|
|
1296
|
+
options?: {
|
|
1297
|
+
workspaceDir?: string;
|
|
1298
|
+
},
|
|
1299
|
+
): ExtractedAssistantDisplayResult {
|
|
920
1300
|
if (entry.type !== "message" || entry.message?.role !== "assistant" || entry.message.isError) {
|
|
921
|
-
return { messages: [] };
|
|
1301
|
+
return { result: { messages: [] }, isStructured: false };
|
|
922
1302
|
}
|
|
923
1303
|
|
|
924
|
-
const
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
? [contentItem.text.trim()]
|
|
928
|
-
: [],
|
|
929
|
-
)
|
|
930
|
-
.filter((text) => text !== "");
|
|
931
|
-
|
|
932
|
-
if (parts.length === 0) {
|
|
933
|
-
return { messages: [] };
|
|
1304
|
+
const rawText = readEntryTextContent(entry);
|
|
1305
|
+
if (rawText === "") {
|
|
1306
|
+
return { result: { messages: [] }, isStructured: false };
|
|
934
1307
|
}
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
1308
|
+
const structuredResult = parseStructuredResponseResult(
|
|
1309
|
+
rawText,
|
|
1310
|
+
options?.workspaceDir ? { workspaceDir: options.workspaceDir } : undefined,
|
|
1311
|
+
);
|
|
938
1312
|
if (structuredResult) {
|
|
939
|
-
return structuredResult;
|
|
1313
|
+
return { result: structuredResult, isStructured: true };
|
|
940
1314
|
}
|
|
941
1315
|
|
|
942
1316
|
const fallbackText = stripStructuredResponseBlock(rawText);
|
|
943
|
-
return fallbackText !== ""
|
|
1317
|
+
return fallbackText !== ""
|
|
1318
|
+
? { result: { messages: [{ text: fallbackText }] }, isStructured: false }
|
|
1319
|
+
: { result: { messages: [] }, isStructured: false };
|
|
944
1320
|
}
|
|
945
1321
|
|
|
946
1322
|
function appendStructuredResponseContract(prompt: string): string {
|
|
@@ -977,21 +1353,100 @@ function buildStructuredResponseContractPrompt(): string {
|
|
|
977
1353
|
`- Use this JSON shape: {\"version\":${PRIVATECLAW_RESPONSE_CONTRACT_VERSION},\"messages\":[{\"text\":\"...\"}],\"data\":{}}`,
|
|
978
1354
|
"- Always include at least one messages entry.",
|
|
979
1355
|
"- Put user-visible text only in messages[].text.",
|
|
1356
|
+
"- 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\"}]}",
|
|
1357
|
+
"- Or use dataBase64 for inline binary: {\"name\":\"file.png\",\"mimeType\":\"image/png\",\"dataBase64\":\"...\"}",
|
|
1358
|
+
"- 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.",
|
|
980
1359
|
"- Use data for optional machine-readable extraction results that PrivateClaw may consume in future file-processing flows.",
|
|
981
1360
|
"- Do not wrap the JSON in markdown fences.",
|
|
982
1361
|
].join("\n");
|
|
983
1362
|
}
|
|
984
1363
|
|
|
985
|
-
function
|
|
1364
|
+
function resolveStructuredAttachments(
|
|
1365
|
+
rawAttachments?: PrivateClawStructuredMessageAttachment[],
|
|
1366
|
+
options?: {
|
|
1367
|
+
workspaceDir?: string;
|
|
1368
|
+
},
|
|
1369
|
+
): PrivateClawAttachment[] {
|
|
1370
|
+
if (!rawAttachments || rawAttachments.length === 0) {
|
|
1371
|
+
return [];
|
|
1372
|
+
}
|
|
1373
|
+
const workspaceDir = path.resolve(options?.workspaceDir ?? DEFAULT_WORKSPACE_DIR);
|
|
1374
|
+
const attachments: PrivateClawAttachment[] = [];
|
|
1375
|
+
for (const raw of rawAttachments) {
|
|
1376
|
+
if (raw.dataBase64?.trim()) {
|
|
1377
|
+
const trimmedData = raw.dataBase64.trim();
|
|
1378
|
+
attachments.push({
|
|
1379
|
+
id: `structured-attachment-${randomUUID()}`,
|
|
1380
|
+
name: raw.name ?? "attachment",
|
|
1381
|
+
mimeType: raw.mimeType ?? GENERIC_BINARY_MIME,
|
|
1382
|
+
sizeBytes: Buffer.byteLength(trimmedData, "base64"),
|
|
1383
|
+
dataBase64: trimmedData,
|
|
1384
|
+
});
|
|
1385
|
+
} else if (raw.filePath) {
|
|
1386
|
+
try {
|
|
1387
|
+
const filePath = resolveStructuredAttachmentFilePath(raw.filePath, workspaceDir);
|
|
1388
|
+
if (!filePath) {
|
|
1389
|
+
continue;
|
|
1390
|
+
}
|
|
1391
|
+
const fileBytes = readFileSync(filePath);
|
|
1392
|
+
attachments.push({
|
|
1393
|
+
id: `structured-attachment-${randomUUID()}`,
|
|
1394
|
+
name: raw.name ?? path.basename(filePath) ?? "attachment",
|
|
1395
|
+
mimeType: raw.mimeType ?? inferMimeTypeFromFileName(raw.name ?? filePath) ?? GENERIC_BINARY_MIME,
|
|
1396
|
+
sizeBytes: fileBytes.byteLength,
|
|
1397
|
+
dataBase64: fileBytes.toString("base64"),
|
|
1398
|
+
});
|
|
1399
|
+
} catch {
|
|
1400
|
+
// Skip unreadable files
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
return attachments;
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
function resolveStructuredAttachmentFilePath(
|
|
1408
|
+
rawFilePath: string,
|
|
1409
|
+
workspaceDir: string,
|
|
1410
|
+
): string | undefined {
|
|
1411
|
+
const trimmedPath = rawFilePath.trim();
|
|
1412
|
+
if (trimmedPath === "") {
|
|
1413
|
+
return undefined;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
if (path.isAbsolute(trimmedPath)) {
|
|
1417
|
+
return path.normalize(trimmedPath);
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
const resolvedPath = normalizeMediaPath(trimmedPath, workspaceDir);
|
|
1421
|
+
return isPathInsideDirectory(workspaceDir, resolvedPath) ? resolvedPath : undefined;
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
function parseStructuredResponseResult(
|
|
1425
|
+
raw: string,
|
|
1426
|
+
options?: {
|
|
1427
|
+
workspaceDir?: string;
|
|
1428
|
+
},
|
|
1429
|
+
): NormalizedBridgeResult | undefined {
|
|
986
1430
|
const structured = parseStructuredResponseBlock(raw);
|
|
987
1431
|
if (!structured?.messages || structured.messages.length === 0) {
|
|
988
1432
|
return undefined;
|
|
989
1433
|
}
|
|
990
1434
|
|
|
991
|
-
const messages =
|
|
1435
|
+
const messages: NormalizedBridgeMessage[] = [];
|
|
1436
|
+
for (const message of structured.messages) {
|
|
992
1437
|
const text = typeof message.text === "string" ? message.text.trim() : "";
|
|
993
|
-
|
|
994
|
-
|
|
1438
|
+
const qqimgResult = extractInlineQqimgAttachments(text, options);
|
|
1439
|
+
const attachments = [
|
|
1440
|
+
...resolveStructuredAttachments(message.attachments, options),
|
|
1441
|
+
...qqimgResult.attachments,
|
|
1442
|
+
];
|
|
1443
|
+
if (qqimgResult.text !== "" || attachments.length > 0) {
|
|
1444
|
+
messages.push({
|
|
1445
|
+
text: qqimgResult.text,
|
|
1446
|
+
...(attachments.length > 0 ? { attachments } : {}),
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
995
1450
|
if (messages.length === 0) {
|
|
996
1451
|
return undefined;
|
|
997
1452
|
}
|
|
@@ -1003,8 +1458,7 @@ function parseStructuredResponseResult(raw: string): NormalizedBridgeResult | un
|
|
|
1003
1458
|
}
|
|
1004
1459
|
|
|
1005
1460
|
function parseStructuredResponseBlock(raw: string): PrivateClawStructuredResponse | undefined {
|
|
1006
|
-
const
|
|
1007
|
-
const payload = match?.[1]?.trim();
|
|
1461
|
+
const payload = extractStructuredResponsePayload(raw);
|
|
1008
1462
|
if (!payload) {
|
|
1009
1463
|
return undefined;
|
|
1010
1464
|
}
|
|
@@ -1021,7 +1475,11 @@ function parseStructuredResponseBlock(raw: string): PrivateClawStructuredRespons
|
|
|
1021
1475
|
}
|
|
1022
1476
|
|
|
1023
1477
|
function stripStructuredResponseBlock(raw: string): string {
|
|
1024
|
-
|
|
1478
|
+
let stripped = raw;
|
|
1479
|
+
for (const pattern of buildStructuredResponseBlockPatterns("gu")) {
|
|
1480
|
+
stripped = stripped.replace(pattern, "");
|
|
1481
|
+
}
|
|
1482
|
+
return stripped.trim();
|
|
1025
1483
|
}
|
|
1026
1484
|
|
|
1027
1485
|
function buildStructuredResponseBlockPattern(flags: string): RegExp {
|
|
@@ -1031,6 +1489,111 @@ function buildStructuredResponseBlockPattern(flags: string): RegExp {
|
|
|
1031
1489
|
);
|
|
1032
1490
|
}
|
|
1033
1491
|
|
|
1492
|
+
function buildStructuredResponseBlockPatterns(flags: string): RegExp[] {
|
|
1493
|
+
const startTag = escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_START);
|
|
1494
|
+
return [
|
|
1495
|
+
buildStructuredResponseBlockPattern(flags),
|
|
1496
|
+
new RegExp(`${startTag}([\\s\\S]*?)${startTag}`, flags),
|
|
1497
|
+
];
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
function extractStructuredResponsePayload(raw: string): string | undefined {
|
|
1501
|
+
for (const pattern of buildStructuredResponseBlockPatterns("u")) {
|
|
1502
|
+
const payload = raw.match(pattern)?.[1]?.trim();
|
|
1503
|
+
if (payload) {
|
|
1504
|
+
return payload;
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
return undefined;
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
function extractInlineQqimgAttachments(
|
|
1511
|
+
text: string,
|
|
1512
|
+
options?: {
|
|
1513
|
+
workspaceDir?: string;
|
|
1514
|
+
},
|
|
1515
|
+
): {
|
|
1516
|
+
text: string;
|
|
1517
|
+
attachments: PrivateClawAttachment[];
|
|
1518
|
+
} {
|
|
1519
|
+
if (!text.includes("<qqimg>")) {
|
|
1520
|
+
return { text, attachments: [] };
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
const attachments: PrivateClawAttachment[] = [];
|
|
1524
|
+
for (const match of text.matchAll(/<qqimg>([\s\S]*?)<\/qqimg>/giu)) {
|
|
1525
|
+
const rawValue = match[1]?.trim();
|
|
1526
|
+
if (!rawValue) {
|
|
1527
|
+
continue;
|
|
1528
|
+
}
|
|
1529
|
+
const attachment = resolveInlineQqimgAttachment(rawValue, options);
|
|
1530
|
+
if (attachment) {
|
|
1531
|
+
attachments.push(attachment);
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
return {
|
|
1536
|
+
text: text
|
|
1537
|
+
.replace(/<qqimg>[\s\S]*?<\/qqimg>/giu, "")
|
|
1538
|
+
.replace(/\n{3,}/gu, "\n\n")
|
|
1539
|
+
.trim(),
|
|
1540
|
+
attachments,
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
function resolveInlineQqimgAttachment(
|
|
1545
|
+
rawValue: string,
|
|
1546
|
+
options?: {
|
|
1547
|
+
workspaceDir?: string;
|
|
1548
|
+
},
|
|
1549
|
+
): PrivateClawAttachment | undefined {
|
|
1550
|
+
const workspaceDir = path.resolve(options?.workspaceDir ?? DEFAULT_WORKSPACE_DIR);
|
|
1551
|
+
|
|
1552
|
+
if (!path.isAbsolute(rawValue)) {
|
|
1553
|
+
try {
|
|
1554
|
+
const parsedUrl = new URL(rawValue);
|
|
1555
|
+
if (parsedUrl.protocol === "file:") {
|
|
1556
|
+
const filePath = fileURLToPath(parsedUrl);
|
|
1557
|
+
const fileBytes = readFileSync(filePath);
|
|
1558
|
+
return {
|
|
1559
|
+
id: `structured-attachment-${randomUUID()}`,
|
|
1560
|
+
name: path.basename(filePath) || "attachment",
|
|
1561
|
+
mimeType: inferMimeTypeFromFileName(filePath) ?? GENERIC_BINARY_MIME,
|
|
1562
|
+
sizeBytes: fileBytes.byteLength,
|
|
1563
|
+
dataBase64: fileBytes.toString("base64"),
|
|
1564
|
+
};
|
|
1565
|
+
}
|
|
1566
|
+
const fileName = path.basename(parsedUrl.pathname) || "attachment";
|
|
1567
|
+
return {
|
|
1568
|
+
id: `structured-attachment-${randomUUID()}`,
|
|
1569
|
+
name: fileName,
|
|
1570
|
+
mimeType: inferMimeTypeFromFileName(fileName) ?? GENERIC_BINARY_MIME,
|
|
1571
|
+
sizeBytes: 0,
|
|
1572
|
+
uri: parsedUrl.toString(),
|
|
1573
|
+
};
|
|
1574
|
+
} catch {
|
|
1575
|
+
// Not a URL. Fall through to local file handling.
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
try {
|
|
1580
|
+
const filePath = resolveStructuredAttachmentFilePath(rawValue, workspaceDir);
|
|
1581
|
+
if (!filePath) {
|
|
1582
|
+
return undefined;
|
|
1583
|
+
}
|
|
1584
|
+
const fileBytes = readFileSync(filePath);
|
|
1585
|
+
return {
|
|
1586
|
+
id: `structured-attachment-${randomUUID()}`,
|
|
1587
|
+
name: path.basename(filePath) || "attachment",
|
|
1588
|
+
mimeType: inferMimeTypeFromFileName(filePath) ?? GENERIC_BINARY_MIME,
|
|
1589
|
+
sizeBytes: fileBytes.byteLength,
|
|
1590
|
+
dataBase64: fileBytes.toString("base64"),
|
|
1591
|
+
};
|
|
1592
|
+
} catch {
|
|
1593
|
+
return undefined;
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1034
1597
|
function parseStructuredResponseJson(
|
|
1035
1598
|
payload: string,
|
|
1036
1599
|
): PrivateClawStructuredResponse | undefined {
|
|
@@ -1049,6 +1612,69 @@ function parseStructuredResponseJson(
|
|
|
1049
1612
|
}
|
|
1050
1613
|
}
|
|
1051
1614
|
|
|
1615
|
+
function extractEmbeddedJsonPayload(text: string): string | undefined {
|
|
1616
|
+
for (let startIndex = 0; startIndex < text.length; startIndex += 1) {
|
|
1617
|
+
const character = text[startIndex];
|
|
1618
|
+
if (character !== "{" && character !== "[") {
|
|
1619
|
+
continue;
|
|
1620
|
+
}
|
|
1621
|
+
const candidate = sliceBalancedJsonPayload(text, startIndex);
|
|
1622
|
+
if (!candidate) {
|
|
1623
|
+
continue;
|
|
1624
|
+
}
|
|
1625
|
+
try {
|
|
1626
|
+
JSON.parse(candidate);
|
|
1627
|
+
return candidate;
|
|
1628
|
+
} catch {
|
|
1629
|
+
continue;
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
return undefined;
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
function sliceBalancedJsonPayload(text: string, startIndex: number): string | undefined {
|
|
1636
|
+
const expectedClosers: string[] = [];
|
|
1637
|
+
let inString = false;
|
|
1638
|
+
let escaped = false;
|
|
1639
|
+
|
|
1640
|
+
for (let index = startIndex; index < text.length; index += 1) {
|
|
1641
|
+
const character = text[index]!;
|
|
1642
|
+
if (escaped) {
|
|
1643
|
+
escaped = false;
|
|
1644
|
+
continue;
|
|
1645
|
+
}
|
|
1646
|
+
if (character === "\\") {
|
|
1647
|
+
escaped = true;
|
|
1648
|
+
continue;
|
|
1649
|
+
}
|
|
1650
|
+
if (character === "\"") {
|
|
1651
|
+
inString = !inString;
|
|
1652
|
+
continue;
|
|
1653
|
+
}
|
|
1654
|
+
if (inString) {
|
|
1655
|
+
continue;
|
|
1656
|
+
}
|
|
1657
|
+
if (character === "{") {
|
|
1658
|
+
expectedClosers.push("}");
|
|
1659
|
+
continue;
|
|
1660
|
+
}
|
|
1661
|
+
if (character === "[") {
|
|
1662
|
+
expectedClosers.push("]");
|
|
1663
|
+
continue;
|
|
1664
|
+
}
|
|
1665
|
+
if (character === "}" || character === "]") {
|
|
1666
|
+
const expected = expectedClosers.pop();
|
|
1667
|
+
if (expected !== character) {
|
|
1668
|
+
return undefined;
|
|
1669
|
+
}
|
|
1670
|
+
if (expectedClosers.length === 0) {
|
|
1671
|
+
return text.slice(startIndex, index + 1);
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
return undefined;
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1052
1678
|
function stripJsonTrailingCommas(payload: string): string {
|
|
1053
1679
|
let normalized = "";
|
|
1054
1680
|
let inString = false;
|
|
@@ -1130,8 +1756,11 @@ function extractBridgeResponseData(response: BridgeResponse): unknown {
|
|
|
1130
1756
|
return typeof response === "string" ? undefined : response.data;
|
|
1131
1757
|
}
|
|
1132
1758
|
|
|
1133
|
-
async function buildAttachmentFromMediaPath(
|
|
1134
|
-
|
|
1759
|
+
async function buildAttachmentFromMediaPath(
|
|
1760
|
+
mediaPath: string,
|
|
1761
|
+
workspaceDir: string = DEFAULT_WORKSPACE_DIR,
|
|
1762
|
+
): Promise<PrivateClawAttachment> {
|
|
1763
|
+
const filePath = normalizeMediaPath(mediaPath, workspaceDir);
|
|
1135
1764
|
const fileBytes = await fs.readFile(filePath);
|
|
1136
1765
|
const fileName = path.basename(filePath) || `media-${randomUUID()}`;
|
|
1137
1766
|
return {
|
|
@@ -1143,12 +1772,17 @@ async function buildAttachmentFromMediaPath(mediaPath: string): Promise<PrivateC
|
|
|
1143
1772
|
};
|
|
1144
1773
|
}
|
|
1145
1774
|
|
|
1146
|
-
function normalizeMediaPath(mediaPath: string): string {
|
|
1775
|
+
function normalizeMediaPath(mediaPath: string, workspaceDir: string = DEFAULT_WORKSPACE_DIR): string {
|
|
1147
1776
|
const trimmed = mediaPath.trim();
|
|
1148
1777
|
if (trimmed.startsWith("file://")) {
|
|
1149
|
-
return fileURLToPath(trimmed);
|
|
1778
|
+
return path.resolve(fileURLToPath(trimmed));
|
|
1150
1779
|
}
|
|
1151
|
-
return path.isAbsolute(trimmed) ? trimmed : path.resolve(trimmed);
|
|
1780
|
+
return path.isAbsolute(trimmed) ? path.resolve(trimmed) : path.resolve(workspaceDir, trimmed);
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
function isPathInsideDirectory(directory: string, targetPath: string): boolean {
|
|
1784
|
+
const relative = path.relative(path.resolve(directory), path.resolve(targetPath));
|
|
1785
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
1152
1786
|
}
|
|
1153
1787
|
|
|
1154
1788
|
function buildVoiceTranscriptionSessionId(sessionId: string, requestId: string): string {
|