@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.
- package/README.md +44 -1
- package/dist/audio-transcriber.d.ts +46 -0
- package/dist/audio-transcriber.js +433 -0
- package/dist/audio-transcriber.js.map +1 -0
- 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 +10 -2
- package/dist/bridges/openclaw-agent-bridge.js +632 -73
- package/dist/bridges/openclaw-agent-bridge.js.map +1 -1
- package/dist/cli.js +57 -6
- package/dist/cli.js.map +1 -1
- package/dist/openclaw-plugin.js +150 -51
- package/dist/openclaw-plugin.js.map +1 -1
- package/dist/pair-daemon.d.ts +2 -0
- package/dist/pair-daemon.js +2 -0
- package/dist/pair-daemon.js.map +1 -1
- package/dist/provider.d.ts +14 -1
- package/dist/provider.js +262 -20
- package/dist/provider.js.map +1 -1
- package/dist/session-control.d.ts +7 -0
- package/dist/session-control.js +122 -0
- package/dist/session-control.js.map +1 -1
- package/dist/text.d.ts +2 -0
- package/dist/text.js +3 -1
- package/dist/text.js.map +1 -1
- package/dist/types.d.ts +21 -2
- package/package.json +2 -2
- package/src/audio-transcriber.test.ts +299 -0
- package/src/audio-transcriber.ts +615 -0
- package/src/bridges/openai-compatible-bridge.ts +1 -0
- package/src/bridges/openclaw-agent-bridge.test.ts +644 -7
- package/src/bridges/openclaw-agent-bridge.ts +817 -81
- package/src/cli.ts +73 -5
- package/src/openclaw-plugin.test.ts +12 -2
- package/src/openclaw-plugin.ts +191 -54
- package/src/pair-daemon.ts +4 -0
- package/src/provider.test.ts +679 -0
- package/src/provider.ts +349 -28
- package/src/session-control.test.ts +80 -0
- package/src/session-control.ts +151 -0
- package/src/text.ts +12 -2
- package/src/types.ts +29 -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,8 @@ import type {
|
|
|
10
14
|
BridgeResponse,
|
|
11
15
|
PrivateClawAgentBridge,
|
|
12
16
|
PrivateClawAudioTranscriptionRequest,
|
|
17
|
+
PrivateClawThinkingTraceSnapshot,
|
|
18
|
+
PrivateClawVerboseController,
|
|
13
19
|
} from "../types.js";
|
|
14
20
|
|
|
15
21
|
type OpenClawThinkingLevel = "off" | "minimal" | "low" | "medium" | "high";
|
|
@@ -50,6 +56,8 @@ interface OpenClawSessionLogCursor {
|
|
|
50
56
|
|
|
51
57
|
interface OpenClawSessionLogEntry {
|
|
52
58
|
type?: string;
|
|
59
|
+
id?: string;
|
|
60
|
+
timestamp?: string;
|
|
53
61
|
message?: {
|
|
54
62
|
role?: string;
|
|
55
63
|
toolName?: string;
|
|
@@ -64,8 +72,16 @@ interface OpenClawSessionLogEntry {
|
|
|
64
72
|
};
|
|
65
73
|
}
|
|
66
74
|
|
|
75
|
+
interface PrivateClawStructuredMessageAttachment {
|
|
76
|
+
name?: string;
|
|
77
|
+
mimeType?: string;
|
|
78
|
+
dataBase64?: string;
|
|
79
|
+
filePath?: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
67
82
|
interface PrivateClawStructuredMessage {
|
|
68
83
|
text?: string | null;
|
|
84
|
+
attachments?: PrivateClawStructuredMessageAttachment[];
|
|
69
85
|
}
|
|
70
86
|
|
|
71
87
|
interface PrivateClawStructuredResponse {
|
|
@@ -84,10 +100,23 @@ interface NormalizedBridgeMessage {
|
|
|
84
100
|
readonly attachments?: PrivateClawAttachment[];
|
|
85
101
|
}
|
|
86
102
|
|
|
103
|
+
interface ExtractedAssistantDisplayResult {
|
|
104
|
+
readonly result: NormalizedBridgeResult;
|
|
105
|
+
readonly isStructured: boolean;
|
|
106
|
+
}
|
|
107
|
+
|
|
87
108
|
interface CollectedSessionMessages {
|
|
88
109
|
readonly assistantMessages: NormalizedBridgeMessage[];
|
|
110
|
+
readonly structuredAssistantMessages: NormalizedBridgeMessage[];
|
|
89
111
|
readonly assistantData?: unknown;
|
|
90
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;
|
|
91
120
|
}
|
|
92
121
|
|
|
93
122
|
class OpenClawAgentNoDisplayPayloadError extends Error {
|
|
@@ -117,6 +146,7 @@ export interface OpenClawAgentBridgeOptions {
|
|
|
117
146
|
timeoutSeconds?: number;
|
|
118
147
|
stateDir?: string;
|
|
119
148
|
workspaceDir?: string;
|
|
149
|
+
verboseController?: PrivateClawVerboseController;
|
|
120
150
|
onLog?: (message: string) => void;
|
|
121
151
|
execFileImpl?: OpenClawAgentExecFile;
|
|
122
152
|
}
|
|
@@ -135,6 +165,9 @@ const XML_ENTITY_PATTERN = /&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);/giu;
|
|
|
135
165
|
const PRIVATECLAW_RESPONSE_CONTRACT_VERSION = 1;
|
|
136
166
|
const PRIVATECLAW_RESPONSE_TAG_START = "<privateclaw-response>";
|
|
137
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;
|
|
138
171
|
const DOCX_MIME_TYPES = new Set<string>([
|
|
139
172
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
140
173
|
]);
|
|
@@ -151,9 +184,14 @@ const TEXT_LIKE_MIME_TYPES = new Set<string>([
|
|
|
151
184
|
"image/svg+xml",
|
|
152
185
|
]);
|
|
153
186
|
|
|
154
|
-
export function parseOpenClawAgentOutput(
|
|
187
|
+
export function parseOpenClawAgentOutput(
|
|
188
|
+
stdout: string,
|
|
189
|
+
options?: {
|
|
190
|
+
workspaceDir?: string;
|
|
191
|
+
},
|
|
192
|
+
): BridgeResponse {
|
|
155
193
|
const parsed = parseOpenClawAgentJson(stdout);
|
|
156
|
-
return parseOpenClawAgentResult(parsed);
|
|
194
|
+
return parseOpenClawAgentResult(parsed, options);
|
|
157
195
|
}
|
|
158
196
|
|
|
159
197
|
export function resolveOpenClawLaunchCommand(options: {
|
|
@@ -190,15 +228,34 @@ export function resolveOpenClawLaunchCommand(options: {
|
|
|
190
228
|
}
|
|
191
229
|
|
|
192
230
|
function parseOpenClawAgentJson(stdout: string): OpenClawAgentJsonResult {
|
|
193
|
-
|
|
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
|
+
}
|
|
194
241
|
}
|
|
195
242
|
|
|
196
|
-
function parseOpenClawAgentResult(
|
|
197
|
-
|
|
243
|
+
function parseOpenClawAgentResult(
|
|
244
|
+
parsed: OpenClawAgentJsonResult,
|
|
245
|
+
options?: {
|
|
246
|
+
workspaceDir?: string;
|
|
247
|
+
},
|
|
248
|
+
): BridgeResponse {
|
|
249
|
+
const result = extractDisplayResult(parsed, options);
|
|
198
250
|
return toBridgeResponse(result.messages, result.data);
|
|
199
251
|
}
|
|
200
252
|
|
|
201
|
-
function extractDisplayResult(
|
|
253
|
+
function extractDisplayResult(
|
|
254
|
+
parsed: OpenClawAgentJsonResult,
|
|
255
|
+
options?: {
|
|
256
|
+
workspaceDir?: string;
|
|
257
|
+
},
|
|
258
|
+
): NormalizedBridgeResult {
|
|
202
259
|
const payloads = parsed.result?.payloads ?? parsed.payloads ?? [];
|
|
203
260
|
const hasAlternatePayloadShape = !parsed.status && payloads.length > 0;
|
|
204
261
|
if (parsed.status && parsed.status !== "ok") {
|
|
@@ -217,7 +274,7 @@ function extractDisplayResult(parsed: OpenClawAgentJsonResult): NormalizedBridge
|
|
|
217
274
|
if (typeof candidate !== "string") {
|
|
218
275
|
return [];
|
|
219
276
|
}
|
|
220
|
-
const result = parseStructuredResponseResult(candidate);
|
|
277
|
+
const result = parseStructuredResponseResult(candidate, options);
|
|
221
278
|
return result ? [result] : [];
|
|
222
279
|
}),
|
|
223
280
|
);
|
|
@@ -245,6 +302,7 @@ function extractDisplayResult(parsed: OpenClawAgentJsonResult): NormalizedBridge
|
|
|
245
302
|
}
|
|
246
303
|
|
|
247
304
|
export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
305
|
+
readonly supportsThinkingTrace = true;
|
|
248
306
|
private readonly executable: string;
|
|
249
307
|
private readonly executableArgs: string[];
|
|
250
308
|
private readonly executableUsesShell: boolean;
|
|
@@ -268,10 +326,24 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
268
326
|
this.options.onLog?.(`[bridge] ${message}`);
|
|
269
327
|
}
|
|
270
328
|
|
|
329
|
+
private isVerboseLoggingEnabled(): boolean {
|
|
330
|
+
return this.options.verboseController?.enabled === true;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private verboseLog(message: string): void {
|
|
334
|
+
if (!this.isVerboseLoggingEnabled()) {
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
this.options.onLog?.(`[bridge][verbose] ${message}`);
|
|
338
|
+
}
|
|
339
|
+
|
|
271
340
|
async handleUserMessage(params: {
|
|
272
341
|
sessionId: string;
|
|
273
342
|
message: string;
|
|
274
343
|
attachments?: ReadonlyArray<PrivateClawAttachment>;
|
|
344
|
+
onThinkingTrace?: (
|
|
345
|
+
snapshot: PrivateClawThinkingTraceSnapshot,
|
|
346
|
+
) => void | Promise<void>;
|
|
275
347
|
}): Promise<BridgeResponse> {
|
|
276
348
|
const promptMessage = await this.buildPromptMessage(
|
|
277
349
|
params.sessionId,
|
|
@@ -284,6 +356,9 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
284
356
|
return this.executePrompt(params.sessionId, promptMessage, {
|
|
285
357
|
includeArtifacts: true,
|
|
286
358
|
noDisplayFallbackMessage: params.message,
|
|
359
|
+
...(params.onThinkingTrace
|
|
360
|
+
? { onThinkingTrace: params.onThinkingTrace }
|
|
361
|
+
: {}),
|
|
287
362
|
});
|
|
288
363
|
}
|
|
289
364
|
|
|
@@ -328,11 +403,67 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
328
403
|
options?: {
|
|
329
404
|
includeArtifacts?: boolean;
|
|
330
405
|
noDisplayFallbackMessage?: string;
|
|
406
|
+
onThinkingTrace?: (
|
|
407
|
+
snapshot: PrivateClawThinkingTraceSnapshot,
|
|
408
|
+
) => void | Promise<void>;
|
|
331
409
|
},
|
|
332
410
|
): Promise<BridgeResponse> {
|
|
333
411
|
const args = this.buildArgs(sessionId, promptMessage);
|
|
334
|
-
|
|
335
|
-
|
|
412
|
+
this.verboseLog(
|
|
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"}`,
|
|
414
|
+
);
|
|
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
|
+
}
|
|
466
|
+
this.verboseLog(`exec_complete session=${sessionId} stdoutChars=${stdout.length}`);
|
|
336
467
|
let parsed: OpenClawAgentJsonResult | undefined;
|
|
337
468
|
let parseError: unknown;
|
|
338
469
|
try {
|
|
@@ -351,11 +482,17 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
351
482
|
`openclaw_agent_parse_failed session=${sessionId} stdoutChars=${stdout.length} stdoutPreview=${JSON.stringify(stdout.slice(0, 400))}`,
|
|
352
483
|
);
|
|
353
484
|
}
|
|
354
|
-
const collectedMessages = await this.collectSessionMessages(sessionId, sessionLogCursor
|
|
485
|
+
const collectedMessages = await this.collectSessionMessages(sessionId, sessionLogCursor, {
|
|
486
|
+
allowTrailingPartial: true,
|
|
487
|
+
});
|
|
488
|
+
await emitThinkingTrace(collectedMessages.traceEntries);
|
|
355
489
|
const recoveredMessages = [
|
|
356
490
|
...collectedMessages.assistantMessages,
|
|
357
491
|
...(options?.includeArtifacts === false ? [] : collectedMessages.artifactMessages),
|
|
358
492
|
];
|
|
493
|
+
this.verboseLog(
|
|
494
|
+
`session_log_delta session=${sessionId} assistantRecovered=${collectedMessages.assistantMessages.length} artifactRecovered=${collectedMessages.artifactMessages.length} includeArtifacts=${options?.includeArtifacts !== false}`,
|
|
495
|
+
);
|
|
359
496
|
if (!parsed) {
|
|
360
497
|
if (recoveredMessages.length > 0) {
|
|
361
498
|
this.log(
|
|
@@ -366,10 +503,30 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
366
503
|
throw parseError;
|
|
367
504
|
}
|
|
368
505
|
try {
|
|
369
|
-
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
|
+
}
|
|
521
|
+
this.verboseLog(
|
|
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}`,
|
|
523
|
+
);
|
|
370
524
|
return options?.includeArtifacts === false
|
|
371
|
-
?
|
|
372
|
-
: mergeBridgeResponses(
|
|
525
|
+
? authoritativeResponse
|
|
526
|
+
: mergeBridgeResponses(
|
|
527
|
+
authoritativeResponse,
|
|
528
|
+
collectedMessages.artifactMessages,
|
|
529
|
+
);
|
|
373
530
|
} catch (error) {
|
|
374
531
|
if (recoveredMessages.length > 0) {
|
|
375
532
|
this.log(
|
|
@@ -390,10 +547,14 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
390
547
|
private async captureSessionLogCursor(sessionId: string): Promise<OpenClawSessionLogCursor> {
|
|
391
548
|
const sessionLogPath = await this.resolveSessionLogPath(sessionId);
|
|
392
549
|
if (!sessionLogPath) {
|
|
550
|
+
this.verboseLog(`session_log_cursor_missing session=${sessionId}`);
|
|
393
551
|
return { sizeBytes: 0 };
|
|
394
552
|
}
|
|
395
553
|
|
|
396
554
|
const stat = await fs.stat(sessionLogPath);
|
|
555
|
+
this.verboseLog(
|
|
556
|
+
`session_log_cursor session=${sessionId} logPath=${JSON.stringify(sessionLogPath)} sizeBytes=${stat.size}`,
|
|
557
|
+
);
|
|
397
558
|
return {
|
|
398
559
|
path: sessionLogPath,
|
|
399
560
|
sizeBytes: stat.size,
|
|
@@ -403,47 +564,49 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
403
564
|
private async collectSessionMessages(
|
|
404
565
|
sessionId: string,
|
|
405
566
|
cursor: OpenClawSessionLogCursor,
|
|
567
|
+
options?: {
|
|
568
|
+
allowTrailingPartial?: boolean;
|
|
569
|
+
},
|
|
406
570
|
): Promise<CollectedSessionMessages> {
|
|
407
|
-
const
|
|
408
|
-
if (
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
artifactMessages: [],
|
|
413
|
-
};
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
const sessionLogBuffer = await fs.readFile(sessionLogPath);
|
|
417
|
-
const deltaBuffer =
|
|
418
|
-
cursor.path === sessionLogPath
|
|
419
|
-
? sessionLogBuffer.subarray(Math.min(cursor.sizeBytes, sessionLogBuffer.length))
|
|
420
|
-
: sessionLogBuffer;
|
|
421
|
-
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
|
+
}
|
|
422
576
|
return {
|
|
423
577
|
assistantMessages: [],
|
|
578
|
+
structuredAssistantMessages: [],
|
|
424
579
|
artifactMessages: [],
|
|
580
|
+
nextCursor,
|
|
581
|
+
traceEntries: [],
|
|
425
582
|
};
|
|
426
583
|
}
|
|
427
584
|
|
|
428
|
-
const
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
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
|
+
});
|
|
437
600
|
|
|
438
601
|
const seenPaths = new Set<string>();
|
|
439
602
|
const attachments: PrivateClawAttachment[] = [];
|
|
440
603
|
for (const entry of entries) {
|
|
441
604
|
for (const mediaPath of extractMediaPaths(entry)) {
|
|
442
|
-
const normalizedPath = normalizeMediaPath(mediaPath);
|
|
605
|
+
const normalizedPath = normalizeMediaPath(mediaPath, this.workspaceDir);
|
|
443
606
|
if (seenPaths.has(normalizedPath)) {
|
|
444
607
|
continue;
|
|
445
608
|
}
|
|
446
|
-
const attachment = await buildAttachmentFromMediaPath(normalizedPath);
|
|
609
|
+
const attachment = await buildAttachmentFromMediaPath(normalizedPath, this.workspaceDir);
|
|
447
610
|
this.log(
|
|
448
611
|
`artifact_recovered session=${sessionId} mediaPath=${JSON.stringify(mediaPath)} normalizedPath=${JSON.stringify(normalizedPath)} name=${JSON.stringify(attachment.name)} mimeType=${attachment.mimeType} sizeBytes=${attachment.sizeBytes}`,
|
|
449
612
|
);
|
|
@@ -456,26 +619,99 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
456
619
|
attachments.length > 0
|
|
457
620
|
? [{ text: "", attachments } satisfies NormalizedBridgeMessage]
|
|
458
621
|
: [];
|
|
459
|
-
const assistantData = combineStructuredData(
|
|
622
|
+
const assistantData = combineStructuredData(
|
|
623
|
+
assistantResults
|
|
624
|
+
.filter((result) => result.isStructured)
|
|
625
|
+
.map((result) => result.result),
|
|
626
|
+
).data;
|
|
460
627
|
|
|
461
628
|
if (attachments.length === 0) {
|
|
462
629
|
this.log(
|
|
463
|
-
`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")}`,
|
|
464
631
|
);
|
|
465
632
|
return {
|
|
466
633
|
assistantMessages,
|
|
634
|
+
structuredAssistantMessages,
|
|
467
635
|
...(assistantData !== undefined ? { assistantData } : {}),
|
|
468
636
|
artifactMessages,
|
|
637
|
+
nextCursor,
|
|
638
|
+
traceEntries,
|
|
469
639
|
};
|
|
470
640
|
}
|
|
471
641
|
|
|
472
642
|
this.log(
|
|
473
|
-
`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")}`,
|
|
474
644
|
);
|
|
475
645
|
return {
|
|
476
646
|
assistantMessages,
|
|
647
|
+
structuredAssistantMessages,
|
|
477
648
|
...(assistantData !== undefined ? { assistantData } : {}),
|
|
478
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
|
+
},
|
|
479
715
|
};
|
|
480
716
|
}
|
|
481
717
|
|
|
@@ -490,6 +726,9 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
490
726
|
const candidate = path.join(agentsDir, entry.name, "sessions", `${sessionId}.jsonl`);
|
|
491
727
|
try {
|
|
492
728
|
await fs.access(candidate);
|
|
729
|
+
this.verboseLog(
|
|
730
|
+
`session_log_resolved session=${sessionId} logPath=${JSON.stringify(candidate)}`,
|
|
731
|
+
);
|
|
493
732
|
return candidate;
|
|
494
733
|
} catch (error) {
|
|
495
734
|
if (isNodeError(error) && error.code === "ENOENT") {
|
|
@@ -505,6 +744,7 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
505
744
|
throw error;
|
|
506
745
|
}
|
|
507
746
|
|
|
747
|
+
this.verboseLog(`session_log_not_found session=${sessionId}`);
|
|
508
748
|
return undefined;
|
|
509
749
|
}
|
|
510
750
|
|
|
@@ -549,6 +789,9 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
549
789
|
this.log(
|
|
550
790
|
`prompt_ready session=${sessionId} stagedAttachments=${stagedAttachments.length} textChars=${trimmed.length} contractVersion=${PRIVATECLAW_RESPONSE_CONTRACT_VERSION}`,
|
|
551
791
|
);
|
|
792
|
+
this.verboseLog(
|
|
793
|
+
`prompt_body_ready session=${sessionId} promptChars=${promptMessage.length} trimmedTextChars=${trimmed.length} stagedAttachments=${stagedAttachments.length}`,
|
|
794
|
+
);
|
|
552
795
|
return promptMessage;
|
|
553
796
|
}
|
|
554
797
|
|
|
@@ -797,19 +1040,82 @@ function mergeBridgeResponses(
|
|
|
797
1040
|
primary: BridgeResponse,
|
|
798
1041
|
supplemental: NormalizedBridgeMessage[],
|
|
799
1042
|
): BridgeResponse {
|
|
800
|
-
|
|
1043
|
+
const dedupedSupplemental = dedupeSupplementalMessages(primary, supplemental);
|
|
1044
|
+
if (dedupedSupplemental.length === 0) {
|
|
801
1045
|
return primary;
|
|
802
1046
|
}
|
|
803
1047
|
|
|
804
1048
|
return toBridgeResponse(
|
|
805
1049
|
[
|
|
806
1050
|
...normalizeBridgeResponse(primary),
|
|
807
|
-
...
|
|
1051
|
+
...dedupedSupplemental,
|
|
808
1052
|
],
|
|
809
1053
|
extractBridgeResponseData(primary),
|
|
810
1054
|
);
|
|
811
1055
|
}
|
|
812
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
|
+
|
|
813
1119
|
function normalizeBridgeResponse(response: BridgeResponse): NormalizedBridgeMessage[] {
|
|
814
1120
|
if (typeof response === "string") {
|
|
815
1121
|
return [{ text: response }];
|
|
@@ -856,6 +1162,109 @@ function toBridgeResponse(
|
|
|
856
1162
|
};
|
|
857
1163
|
}
|
|
858
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
|
+
|
|
859
1268
|
function extractMediaPaths(entry: OpenClawSessionLogEntry): string[] {
|
|
860
1269
|
if (entry.type !== "message" || entry.message?.role !== "toolResult" || entry.message.isError) {
|
|
861
1270
|
return [];
|
|
@@ -882,31 +1291,32 @@ function extractMediaPaths(entry: OpenClawSessionLogEntry): string[] {
|
|
|
882
1291
|
return [...mediaPaths];
|
|
883
1292
|
}
|
|
884
1293
|
|
|
885
|
-
function extractAssistantDisplayResult(
|
|
1294
|
+
function extractAssistantDisplayResult(
|
|
1295
|
+
entry: OpenClawSessionLogEntry,
|
|
1296
|
+
options?: {
|
|
1297
|
+
workspaceDir?: string;
|
|
1298
|
+
},
|
|
1299
|
+
): ExtractedAssistantDisplayResult {
|
|
886
1300
|
if (entry.type !== "message" || entry.message?.role !== "assistant" || entry.message.isError) {
|
|
887
|
-
return { messages: [] };
|
|
1301
|
+
return { result: { messages: [] }, isStructured: false };
|
|
888
1302
|
}
|
|
889
1303
|
|
|
890
|
-
const
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
? [contentItem.text.trim()]
|
|
894
|
-
: [],
|
|
895
|
-
)
|
|
896
|
-
.filter((text) => text !== "");
|
|
897
|
-
|
|
898
|
-
if (parts.length === 0) {
|
|
899
|
-
return { messages: [] };
|
|
1304
|
+
const rawText = readEntryTextContent(entry);
|
|
1305
|
+
if (rawText === "") {
|
|
1306
|
+
return { result: { messages: [] }, isStructured: false };
|
|
900
1307
|
}
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
1308
|
+
const structuredResult = parseStructuredResponseResult(
|
|
1309
|
+
rawText,
|
|
1310
|
+
options?.workspaceDir ? { workspaceDir: options.workspaceDir } : undefined,
|
|
1311
|
+
);
|
|
904
1312
|
if (structuredResult) {
|
|
905
|
-
return structuredResult;
|
|
1313
|
+
return { result: structuredResult, isStructured: true };
|
|
906
1314
|
}
|
|
907
1315
|
|
|
908
1316
|
const fallbackText = stripStructuredResponseBlock(rawText);
|
|
909
|
-
return fallbackText !== ""
|
|
1317
|
+
return fallbackText !== ""
|
|
1318
|
+
? { result: { messages: [{ text: fallbackText }] }, isStructured: false }
|
|
1319
|
+
: { result: { messages: [] }, isStructured: false };
|
|
910
1320
|
}
|
|
911
1321
|
|
|
912
1322
|
function appendStructuredResponseContract(prompt: string): string {
|
|
@@ -943,21 +1353,100 @@ function buildStructuredResponseContractPrompt(): string {
|
|
|
943
1353
|
`- Use this JSON shape: {\"version\":${PRIVATECLAW_RESPONSE_CONTRACT_VERSION},\"messages\":[{\"text\":\"...\"}],\"data\":{}}`,
|
|
944
1354
|
"- Always include at least one messages entry.",
|
|
945
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.",
|
|
946
1359
|
"- Use data for optional machine-readable extraction results that PrivateClaw may consume in future file-processing flows.",
|
|
947
1360
|
"- Do not wrap the JSON in markdown fences.",
|
|
948
1361
|
].join("\n");
|
|
949
1362
|
}
|
|
950
1363
|
|
|
951
|
-
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 {
|
|
952
1430
|
const structured = parseStructuredResponseBlock(raw);
|
|
953
1431
|
if (!structured?.messages || structured.messages.length === 0) {
|
|
954
1432
|
return undefined;
|
|
955
1433
|
}
|
|
956
1434
|
|
|
957
|
-
const messages =
|
|
1435
|
+
const messages: NormalizedBridgeMessage[] = [];
|
|
1436
|
+
for (const message of structured.messages) {
|
|
958
1437
|
const text = typeof message.text === "string" ? message.text.trim() : "";
|
|
959
|
-
|
|
960
|
-
|
|
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
|
+
}
|
|
961
1450
|
if (messages.length === 0) {
|
|
962
1451
|
return undefined;
|
|
963
1452
|
}
|
|
@@ -969,25 +1458,28 @@ function parseStructuredResponseResult(raw: string): NormalizedBridgeResult | un
|
|
|
969
1458
|
}
|
|
970
1459
|
|
|
971
1460
|
function parseStructuredResponseBlock(raw: string): PrivateClawStructuredResponse | undefined {
|
|
972
|
-
const
|
|
973
|
-
const payload = match?.[1]?.trim();
|
|
1461
|
+
const payload = extractStructuredResponsePayload(raw);
|
|
974
1462
|
if (!payload) {
|
|
975
1463
|
return undefined;
|
|
976
1464
|
}
|
|
977
1465
|
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
} catch {
|
|
1466
|
+
const parsed = parseStructuredResponseJson(payload);
|
|
1467
|
+
if (
|
|
1468
|
+
!parsed ||
|
|
1469
|
+
parsed.version !== PRIVATECLAW_RESPONSE_CONTRACT_VERSION ||
|
|
1470
|
+
!Array.isArray(parsed.messages)
|
|
1471
|
+
) {
|
|
985
1472
|
return undefined;
|
|
986
1473
|
}
|
|
1474
|
+
return parsed;
|
|
987
1475
|
}
|
|
988
1476
|
|
|
989
1477
|
function stripStructuredResponseBlock(raw: string): string {
|
|
990
|
-
|
|
1478
|
+
let stripped = raw;
|
|
1479
|
+
for (const pattern of buildStructuredResponseBlockPatterns("gu")) {
|
|
1480
|
+
stripped = stripped.replace(pattern, "");
|
|
1481
|
+
}
|
|
1482
|
+
return stripped.trim();
|
|
991
1483
|
}
|
|
992
1484
|
|
|
993
1485
|
function buildStructuredResponseBlockPattern(flags: string): RegExp {
|
|
@@ -997,6 +1489,242 @@ function buildStructuredResponseBlockPattern(flags: string): RegExp {
|
|
|
997
1489
|
);
|
|
998
1490
|
}
|
|
999
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
|
+
|
|
1597
|
+
function parseStructuredResponseJson(
|
|
1598
|
+
payload: string,
|
|
1599
|
+
): PrivateClawStructuredResponse | undefined {
|
|
1600
|
+
try {
|
|
1601
|
+
return JSON.parse(payload) as PrivateClawStructuredResponse;
|
|
1602
|
+
} catch {
|
|
1603
|
+
const normalizedPayload = stripJsonTrailingCommas(payload);
|
|
1604
|
+
if (normalizedPayload === payload) {
|
|
1605
|
+
return undefined;
|
|
1606
|
+
}
|
|
1607
|
+
try {
|
|
1608
|
+
return JSON.parse(normalizedPayload) as PrivateClawStructuredResponse;
|
|
1609
|
+
} catch {
|
|
1610
|
+
return undefined;
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
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
|
+
|
|
1678
|
+
function stripJsonTrailingCommas(payload: string): string {
|
|
1679
|
+
let normalized = "";
|
|
1680
|
+
let inString = false;
|
|
1681
|
+
let escaped = false;
|
|
1682
|
+
|
|
1683
|
+
for (let index = 0; index < payload.length; index += 1) {
|
|
1684
|
+
const character = payload[index]!;
|
|
1685
|
+
|
|
1686
|
+
if (escaped) {
|
|
1687
|
+
normalized += character;
|
|
1688
|
+
escaped = false;
|
|
1689
|
+
continue;
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
if (inString) {
|
|
1693
|
+
normalized += character;
|
|
1694
|
+
if (character === "\\") {
|
|
1695
|
+
escaped = true;
|
|
1696
|
+
} else if (character === '"') {
|
|
1697
|
+
inString = false;
|
|
1698
|
+
}
|
|
1699
|
+
continue;
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
if (character === '"') {
|
|
1703
|
+
normalized += character;
|
|
1704
|
+
inString = true;
|
|
1705
|
+
continue;
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
if (character === ",") {
|
|
1709
|
+
let lookahead = index + 1;
|
|
1710
|
+
while (
|
|
1711
|
+
lookahead < payload.length &&
|
|
1712
|
+
/\s/u.test(payload[lookahead]!)
|
|
1713
|
+
) {
|
|
1714
|
+
lookahead += 1;
|
|
1715
|
+
}
|
|
1716
|
+
const nextCharacter = payload[lookahead];
|
|
1717
|
+
if (nextCharacter === "]" || nextCharacter === "}") {
|
|
1718
|
+
continue;
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1722
|
+
normalized += character;
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
return normalized;
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1000
1728
|
function escapeRegExpLiteral(value: string): string {
|
|
1001
1729
|
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
1002
1730
|
}
|
|
@@ -1028,8 +1756,11 @@ function extractBridgeResponseData(response: BridgeResponse): unknown {
|
|
|
1028
1756
|
return typeof response === "string" ? undefined : response.data;
|
|
1029
1757
|
}
|
|
1030
1758
|
|
|
1031
|
-
async function buildAttachmentFromMediaPath(
|
|
1032
|
-
|
|
1759
|
+
async function buildAttachmentFromMediaPath(
|
|
1760
|
+
mediaPath: string,
|
|
1761
|
+
workspaceDir: string = DEFAULT_WORKSPACE_DIR,
|
|
1762
|
+
): Promise<PrivateClawAttachment> {
|
|
1763
|
+
const filePath = normalizeMediaPath(mediaPath, workspaceDir);
|
|
1033
1764
|
const fileBytes = await fs.readFile(filePath);
|
|
1034
1765
|
const fileName = path.basename(filePath) || `media-${randomUUID()}`;
|
|
1035
1766
|
return {
|
|
@@ -1041,12 +1772,17 @@ async function buildAttachmentFromMediaPath(mediaPath: string): Promise<PrivateC
|
|
|
1041
1772
|
};
|
|
1042
1773
|
}
|
|
1043
1774
|
|
|
1044
|
-
function normalizeMediaPath(mediaPath: string): string {
|
|
1775
|
+
function normalizeMediaPath(mediaPath: string, workspaceDir: string = DEFAULT_WORKSPACE_DIR): string {
|
|
1045
1776
|
const trimmed = mediaPath.trim();
|
|
1046
1777
|
if (trimmed.startsWith("file://")) {
|
|
1047
|
-
return fileURLToPath(trimmed);
|
|
1778
|
+
return path.resolve(fileURLToPath(trimmed));
|
|
1048
1779
|
}
|
|
1049
|
-
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));
|
|
1050
1786
|
}
|
|
1051
1787
|
|
|
1052
1788
|
function buildVoiceTranscriptionSessionId(sessionId: string, requestId: string): string {
|