@privateclaw/privateclaw 0.1.4 → 0.1.8
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/openclaw-agent-bridge.d.ts +3 -1
- package/dist/bridges/openclaw-agent-bridge.js +231 -48
- package/dist/bridges/openclaw-agent-bridge.js.map +1 -1
- package/dist/cli.js +3 -0
- package/dist/cli.js.map +1 -1
- package/dist/openclaw-plugin.js +5 -3
- package/dist/openclaw-plugin.js.map +1 -1
- package/dist/provider.d.ts +2 -0
- package/dist/provider.js +94 -7
- package/dist/provider.js.map +1 -1
- package/dist/text.d.ts +1 -0
- package/dist/text.js +1 -0
- package/dist/text.js.map +1 -1
- package/dist/types.d.ts +4 -2
- package/openclaw.plugin.json +13 -3
- package/package.json +11 -2
- package/src/bridges/openclaw-agent-bridge.test.ts +180 -2
- package/src/bridges/openclaw-agent-bridge.ts +335 -63
- package/src/cli.ts +3 -0
- package/src/openclaw-plugin.ts +8 -3
- package/src/provider.test.ts +130 -0
- package/src/provider.ts +142 -5
- package/src/text.ts +5 -0
- package/src/types.ts +6 -1
- package/dist/qr-terminal-render.d.ts +0 -7
- package/dist/qr-terminal-render.js +0 -44
- package/dist/qr-terminal-render.js.map +0 -1
|
@@ -32,6 +32,8 @@ interface OpenClawAgentPayload {
|
|
|
32
32
|
interface OpenClawAgentJsonResult {
|
|
33
33
|
status?: string;
|
|
34
34
|
summary?: string;
|
|
35
|
+
payloads?: OpenClawAgentPayload[];
|
|
36
|
+
meta?: Record<string, unknown>;
|
|
35
37
|
result?: {
|
|
36
38
|
payloads?: OpenClawAgentPayload[];
|
|
37
39
|
};
|
|
@@ -58,11 +60,32 @@ interface OpenClawSessionLogEntry {
|
|
|
58
60
|
};
|
|
59
61
|
}
|
|
60
62
|
|
|
63
|
+
interface PrivateClawStructuredMessage {
|
|
64
|
+
text?: string | null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface PrivateClawStructuredResponse {
|
|
68
|
+
version?: number;
|
|
69
|
+
messages?: PrivateClawStructuredMessage[];
|
|
70
|
+
data?: unknown;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface NormalizedBridgeResult {
|
|
74
|
+
readonly messages: NormalizedBridgeMessage[];
|
|
75
|
+
readonly data?: unknown;
|
|
76
|
+
}
|
|
77
|
+
|
|
61
78
|
interface NormalizedBridgeMessage {
|
|
62
79
|
readonly text: string;
|
|
63
80
|
readonly attachments?: PrivateClawAttachment[];
|
|
64
81
|
}
|
|
65
82
|
|
|
83
|
+
interface CollectedSessionMessages {
|
|
84
|
+
readonly assistantMessages: NormalizedBridgeMessage[];
|
|
85
|
+
readonly assistantData?: unknown;
|
|
86
|
+
readonly artifactMessages: NormalizedBridgeMessage[];
|
|
87
|
+
}
|
|
88
|
+
|
|
66
89
|
class OpenClawAgentNoDisplayPayloadError extends Error {
|
|
67
90
|
constructor(readonly parsed: OpenClawAgentJsonResult) {
|
|
68
91
|
super("OpenClaw agent bridge returned no displayable payloads.");
|
|
@@ -90,6 +113,7 @@ export interface OpenClawAgentBridgeOptions {
|
|
|
90
113
|
timeoutSeconds?: number;
|
|
91
114
|
stateDir?: string;
|
|
92
115
|
workspaceDir?: string;
|
|
116
|
+
onLog?: (message: string) => void;
|
|
93
117
|
execFileImpl?: OpenClawAgentExecFile;
|
|
94
118
|
}
|
|
95
119
|
|
|
@@ -104,6 +128,9 @@ const DEFAULT_STATE_DIR = process.env.OPENCLAW_STATE_DIR ?? path.join(os.homedir
|
|
|
104
128
|
const DEFAULT_WORKSPACE_DIR = path.join(DEFAULT_STATE_DIR, "workspace");
|
|
105
129
|
const GENERIC_BINARY_MIME = "application/octet-stream";
|
|
106
130
|
const XML_ENTITY_PATTERN = /&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);/giu;
|
|
131
|
+
const PRIVATECLAW_RESPONSE_CONTRACT_VERSION = 1;
|
|
132
|
+
const PRIVATECLAW_RESPONSE_TAG_START = "<privateclaw-response>";
|
|
133
|
+
const PRIVATECLAW_RESPONSE_TAG_END = "</privateclaw-response>";
|
|
107
134
|
const DOCX_MIME_TYPES = new Set<string>([
|
|
108
135
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
109
136
|
]);
|
|
@@ -163,32 +190,54 @@ function parseOpenClawAgentJson(stdout: string): OpenClawAgentJsonResult {
|
|
|
163
190
|
}
|
|
164
191
|
|
|
165
192
|
function parseOpenClawAgentResult(parsed: OpenClawAgentJsonResult): BridgeResponse {
|
|
166
|
-
const
|
|
167
|
-
return toBridgeResponse(messages);
|
|
193
|
+
const result = extractDisplayResult(parsed);
|
|
194
|
+
return toBridgeResponse(result.messages, result.data);
|
|
168
195
|
}
|
|
169
196
|
|
|
170
|
-
function
|
|
171
|
-
|
|
197
|
+
function extractDisplayResult(parsed: OpenClawAgentJsonResult): NormalizedBridgeResult {
|
|
198
|
+
const payloads = parsed.result?.payloads ?? parsed.payloads ?? [];
|
|
199
|
+
const hasAlternatePayloadShape = !parsed.status && payloads.length > 0;
|
|
200
|
+
if (parsed.status && parsed.status !== "ok") {
|
|
201
|
+
throw new Error(
|
|
202
|
+
`OpenClaw agent bridge returned status ${parsed.status ?? "unknown"}${parsed.summary ? ` (${parsed.summary})` : ""}.`,
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
if (!parsed.status && !hasAlternatePayloadShape) {
|
|
172
206
|
throw new Error(
|
|
173
207
|
`OpenClaw agent bridge returned status ${parsed.status ?? "unknown"}${parsed.summary ? ` (${parsed.summary})` : ""}.`,
|
|
174
208
|
);
|
|
175
209
|
}
|
|
176
210
|
|
|
211
|
+
const structuredResults = payloads.flatMap((payload) =>
|
|
212
|
+
[payload.text, payload.message, payload.summary].flatMap((candidate) => {
|
|
213
|
+
if (typeof candidate !== "string") {
|
|
214
|
+
return [];
|
|
215
|
+
}
|
|
216
|
+
const result = parseStructuredResponseResult(candidate);
|
|
217
|
+
return result ? [result] : [];
|
|
218
|
+
}),
|
|
219
|
+
);
|
|
220
|
+
if (structuredResults.length > 0) {
|
|
221
|
+
return {
|
|
222
|
+
messages: structuredResults.flatMap((result) => result.messages),
|
|
223
|
+
...combineStructuredData(structuredResults),
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
177
227
|
const messages =
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
) ?? [];
|
|
228
|
+
payloads.flatMap((payload) =>
|
|
229
|
+
[payload.text, payload.message, payload.summary].flatMap((candidate) =>
|
|
230
|
+
typeof candidate === "string" && stripStructuredResponseBlock(candidate) !== ""
|
|
231
|
+
? [{ text: stripStructuredResponseBlock(candidate) }]
|
|
232
|
+
: [],
|
|
233
|
+
),
|
|
234
|
+
) ?? [];
|
|
186
235
|
|
|
187
236
|
if (messages.length === 0) {
|
|
188
237
|
throw new OpenClawAgentNoDisplayPayloadError(parsed);
|
|
189
238
|
}
|
|
190
239
|
|
|
191
|
-
return messages;
|
|
240
|
+
return { messages };
|
|
192
241
|
}
|
|
193
242
|
|
|
194
243
|
export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
@@ -211,6 +260,10 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
211
260
|
this.workspaceDir = options.workspaceDir ?? path.join(this.stateDir, "workspace");
|
|
212
261
|
}
|
|
213
262
|
|
|
263
|
+
private log(message: string): void {
|
|
264
|
+
this.options.onLog?.(`[bridge] ${message}`);
|
|
265
|
+
}
|
|
266
|
+
|
|
214
267
|
async handleUserMessage(params: {
|
|
215
268
|
sessionId: string;
|
|
216
269
|
message: string;
|
|
@@ -221,22 +274,55 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
221
274
|
params.message,
|
|
222
275
|
params.attachments,
|
|
223
276
|
);
|
|
277
|
+
this.log(
|
|
278
|
+
`handle_user_message session=${params.sessionId} textChars=${params.message.length} attachments=${params.attachments?.length ?? 0} promptChars=${promptMessage.length}`,
|
|
279
|
+
);
|
|
224
280
|
const args = this.buildArgs(params.sessionId, promptMessage);
|
|
225
281
|
const sessionLogCursor = await this.captureSessionLogCursor(params.sessionId);
|
|
226
282
|
const stdout = await this.execOpenClaw(args);
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
283
|
+
let parsed: OpenClawAgentJsonResult | undefined;
|
|
284
|
+
let parseError: unknown;
|
|
285
|
+
try {
|
|
286
|
+
parsed = parseOpenClawAgentJson(stdout);
|
|
287
|
+
this.log(
|
|
288
|
+
`openclaw_agent_complete session=${params.sessionId} status=${parsed.status ?? "unknown"} summary=${JSON.stringify(parsed.summary ?? "")}`,
|
|
289
|
+
);
|
|
290
|
+
if (!parsed.status) {
|
|
291
|
+
this.log(
|
|
292
|
+
`openclaw_agent_missing_status session=${params.sessionId} topLevelKeys=${Object.keys(parsed).join(",") || "none"}`,
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
} catch (error) {
|
|
296
|
+
parseError = error;
|
|
297
|
+
this.log(
|
|
298
|
+
`openclaw_agent_parse_failed session=${params.sessionId} stdoutChars=${stdout.length} stdoutPreview=${JSON.stringify(stdout.slice(0, 400))}`,
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
const collectedMessages = await this.collectSessionMessages(params.sessionId, sessionLogCursor);
|
|
302
|
+
const recoveredMessages = [
|
|
303
|
+
...collectedMessages.assistantMessages,
|
|
304
|
+
...collectedMessages.artifactMessages,
|
|
305
|
+
];
|
|
306
|
+
if (!parsed) {
|
|
307
|
+
if (recoveredMessages.length > 0) {
|
|
308
|
+
this.log(
|
|
309
|
+
`session_log_fallback session=${params.sessionId} reason=parse_failed recoveredMessages=${recoveredMessages.length}`,
|
|
310
|
+
);
|
|
311
|
+
return toBridgeResponse(recoveredMessages, collectedMessages.assistantData);
|
|
312
|
+
}
|
|
313
|
+
throw parseError;
|
|
314
|
+
}
|
|
232
315
|
try {
|
|
233
316
|
const response = parseOpenClawAgentResult(parsed);
|
|
234
|
-
return mergeBridgeResponses(response, artifactMessages);
|
|
317
|
+
return mergeBridgeResponses(response, collectedMessages.artifactMessages);
|
|
235
318
|
} catch (error) {
|
|
319
|
+
if (recoveredMessages.length > 0) {
|
|
320
|
+
this.log(
|
|
321
|
+
`session_log_fallback session=${params.sessionId} reason=${JSON.stringify(error instanceof Error ? error.message : String(error))} recoveredMessages=${recoveredMessages.length}`,
|
|
322
|
+
);
|
|
323
|
+
return toBridgeResponse(recoveredMessages, collectedMessages.assistantData);
|
|
324
|
+
}
|
|
236
325
|
if (error instanceof OpenClawAgentNoDisplayPayloadError) {
|
|
237
|
-
if (artifactMessages.length > 0) {
|
|
238
|
-
return toBridgeResponse(artifactMessages);
|
|
239
|
-
}
|
|
240
326
|
return buildNoDisplayPayloadNotice(params.message, error.parsed);
|
|
241
327
|
}
|
|
242
328
|
throw error;
|
|
@@ -256,13 +342,17 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
256
342
|
};
|
|
257
343
|
}
|
|
258
344
|
|
|
259
|
-
private async
|
|
345
|
+
private async collectSessionMessages(
|
|
260
346
|
sessionId: string,
|
|
261
347
|
cursor: OpenClawSessionLogCursor,
|
|
262
|
-
): Promise<
|
|
348
|
+
): Promise<CollectedSessionMessages> {
|
|
263
349
|
const sessionLogPath = cursor.path ?? (await this.resolveSessionLogPath(sessionId));
|
|
264
350
|
if (!sessionLogPath) {
|
|
265
|
-
|
|
351
|
+
this.log(`artifact_log_missing session=${sessionId}`);
|
|
352
|
+
return {
|
|
353
|
+
assistantMessages: [],
|
|
354
|
+
artifactMessages: [],
|
|
355
|
+
};
|
|
266
356
|
}
|
|
267
357
|
|
|
268
358
|
const sessionLogBuffer = await fs.readFile(sessionLogPath);
|
|
@@ -271,7 +361,10 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
271
361
|
? sessionLogBuffer.subarray(Math.min(cursor.sizeBytes, sessionLogBuffer.length))
|
|
272
362
|
: sessionLogBuffer;
|
|
273
363
|
if (deltaBuffer.length === 0) {
|
|
274
|
-
return
|
|
364
|
+
return {
|
|
365
|
+
assistantMessages: [],
|
|
366
|
+
artifactMessages: [],
|
|
367
|
+
};
|
|
275
368
|
}
|
|
276
369
|
|
|
277
370
|
const entries = deltaBuffer
|
|
@@ -281,6 +374,9 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
281
374
|
.filter((line) => line !== "")
|
|
282
375
|
.map((line) => JSON.parse(line) as OpenClawSessionLogEntry);
|
|
283
376
|
|
|
377
|
+
const assistantResults = entries.map((entry) => extractAssistantDisplayResult(entry));
|
|
378
|
+
const assistantMessages = assistantResults.flatMap((result) => result.messages);
|
|
379
|
+
|
|
284
380
|
const seenPaths = new Set<string>();
|
|
285
381
|
const attachments: PrivateClawAttachment[] = [];
|
|
286
382
|
for (const entry of entries) {
|
|
@@ -289,16 +385,40 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
289
385
|
if (seenPaths.has(normalizedPath)) {
|
|
290
386
|
continue;
|
|
291
387
|
}
|
|
292
|
-
|
|
388
|
+
const attachment = await buildAttachmentFromMediaPath(normalizedPath);
|
|
389
|
+
this.log(
|
|
390
|
+
`artifact_recovered session=${sessionId} mediaPath=${JSON.stringify(mediaPath)} normalizedPath=${JSON.stringify(normalizedPath)} name=${JSON.stringify(attachment.name)} mimeType=${attachment.mimeType} sizeBytes=${attachment.sizeBytes}`,
|
|
391
|
+
);
|
|
392
|
+
attachments.push(attachment);
|
|
293
393
|
seenPaths.add(normalizedPath);
|
|
294
394
|
}
|
|
295
395
|
}
|
|
296
396
|
|
|
397
|
+
const artifactMessages =
|
|
398
|
+
attachments.length > 0
|
|
399
|
+
? [{ text: "", attachments } satisfies NormalizedBridgeMessage]
|
|
400
|
+
: [];
|
|
401
|
+
const assistantData = combineStructuredData(assistantResults).data;
|
|
402
|
+
|
|
297
403
|
if (attachments.length === 0) {
|
|
298
|
-
|
|
404
|
+
this.log(
|
|
405
|
+
`artifact_scan_complete session=${sessionId} entries=${entries.length} assistantRecovered=${assistantMessages.length} recovered=0 logPath=${JSON.stringify(sessionLogPath)}`,
|
|
406
|
+
);
|
|
407
|
+
return {
|
|
408
|
+
assistantMessages,
|
|
409
|
+
...(assistantData !== undefined ? { assistantData } : {}),
|
|
410
|
+
artifactMessages,
|
|
411
|
+
};
|
|
299
412
|
}
|
|
300
413
|
|
|
301
|
-
|
|
414
|
+
this.log(
|
|
415
|
+
`artifact_scan_complete session=${sessionId} entries=${entries.length} assistantRecovered=${assistantMessages.length} recovered=${attachments.length} logPath=${JSON.stringify(sessionLogPath)}`,
|
|
416
|
+
);
|
|
417
|
+
return {
|
|
418
|
+
assistantMessages,
|
|
419
|
+
...(assistantData !== undefined ? { assistantData } : {}),
|
|
420
|
+
artifactMessages,
|
|
421
|
+
};
|
|
302
422
|
}
|
|
303
423
|
|
|
304
424
|
private async resolveSessionLogPath(sessionId: string): Promise<string | undefined> {
|
|
@@ -337,34 +457,41 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
337
457
|
): Promise<string> {
|
|
338
458
|
const trimmed = message.trim();
|
|
339
459
|
const stagedAttachments = await this.stageAttachments(sessionId, attachments);
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
lines.push(`
|
|
460
|
+
let promptBody = trimmed;
|
|
461
|
+
|
|
462
|
+
if (stagedAttachments.length > 0) {
|
|
463
|
+
const lines = [
|
|
464
|
+
trimmed !== ""
|
|
465
|
+
? trimmed
|
|
466
|
+
: "The user sent one or more file attachments without additional text.",
|
|
467
|
+
"",
|
|
468
|
+
"PrivateClaw staged the attachments into the OpenClaw workspace.",
|
|
469
|
+
"Inspect the staged files before answering, and use the exact paths below instead of guessing a workspace-root filename.",
|
|
470
|
+
"",
|
|
471
|
+
"Staged attachments:",
|
|
472
|
+
];
|
|
473
|
+
|
|
474
|
+
for (const attachment of stagedAttachments) {
|
|
475
|
+
lines.push(`- ${attachment.name}`);
|
|
476
|
+
lines.push(` mimeType: ${attachment.effectiveMimeType}`);
|
|
477
|
+
lines.push(` kind: ${attachment.kind}`);
|
|
478
|
+
lines.push(` workspacePath: ${attachment.workspacePath}`);
|
|
479
|
+
if (attachment.extractedTextWorkspacePath) {
|
|
480
|
+
lines.push(` extractedTextPath: ${attachment.extractedTextWorkspacePath}`);
|
|
481
|
+
}
|
|
482
|
+
lines.push(` instruction: ${attachment.instruction}`);
|
|
363
483
|
}
|
|
364
|
-
|
|
484
|
+
|
|
485
|
+
promptBody = lines.join("\n");
|
|
365
486
|
}
|
|
366
487
|
|
|
367
|
-
|
|
488
|
+
const promptMessage = appendStructuredResponseContract(
|
|
489
|
+
promptBody !== "" ? promptBody : "The user sent a message that requires a reply.",
|
|
490
|
+
);
|
|
491
|
+
this.log(
|
|
492
|
+
`prompt_ready session=${sessionId} stagedAttachments=${stagedAttachments.length} textChars=${trimmed.length} contractVersion=${PRIVATECLAW_RESPONSE_CONTRACT_VERSION}`,
|
|
493
|
+
);
|
|
494
|
+
return promptMessage;
|
|
368
495
|
}
|
|
369
496
|
|
|
370
497
|
private async stageAttachments(
|
|
@@ -377,22 +504,28 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
377
504
|
|
|
378
505
|
const sessionDir = path.join(this.workspaceDir, "privateclaw", sessionId);
|
|
379
506
|
await fs.mkdir(sessionDir, { recursive: true });
|
|
507
|
+
this.log(
|
|
508
|
+
`stage_start session=${sessionId} count=${attachments.length} sessionDir=${JSON.stringify(sessionDir)}`,
|
|
509
|
+
);
|
|
380
510
|
|
|
381
511
|
const staged: StagedAttachment[] = [];
|
|
382
512
|
for (const attachment of attachments) {
|
|
383
513
|
const dataBase64 = attachment.dataBase64?.trim();
|
|
384
514
|
if (!dataBase64) {
|
|
515
|
+
this.log(
|
|
516
|
+
`stage_skip_missing_data session=${sessionId} name=${JSON.stringify(attachment.name)} mimeType=${attachment.mimeType} sizeBytes=${attachment.sizeBytes}`,
|
|
517
|
+
);
|
|
385
518
|
continue;
|
|
386
519
|
}
|
|
387
520
|
|
|
388
521
|
const effectiveMimeType = resolveAttachmentMimeType(attachment);
|
|
522
|
+
const kind = classifyAttachmentKind(attachment.name, effectiveMimeType);
|
|
389
523
|
const uniqueFileName = `${Date.now()}-${randomUUID().slice(0, 8)}-${sanitizeFileName(attachment.name)}`;
|
|
390
524
|
const absolutePath = path.join(sessionDir, uniqueFileName);
|
|
391
525
|
const rawBytes = Buffer.from(dataBase64, "base64");
|
|
392
526
|
await fs.writeFile(absolutePath, rawBytes);
|
|
393
527
|
|
|
394
528
|
const workspacePath = toWorkspacePath(this.workspaceDir, absolutePath);
|
|
395
|
-
const kind = classifyAttachmentKind(attachment.name, effectiveMimeType);
|
|
396
529
|
let extractedTextAbsolutePath: string | undefined;
|
|
397
530
|
let extractedTextWorkspacePath: string | undefined;
|
|
398
531
|
|
|
@@ -406,9 +539,12 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
406
539
|
extractedTextAbsolutePath,
|
|
407
540
|
);
|
|
408
541
|
}
|
|
542
|
+
this.log(
|
|
543
|
+
`stage_docx_extraction session=${sessionId} name=${JSON.stringify(attachment.name)} extracted=${Boolean(extractedTextWorkspacePath)} extractedChars=${extractedText.length}`,
|
|
544
|
+
);
|
|
409
545
|
}
|
|
410
546
|
|
|
411
|
-
|
|
547
|
+
const stagedAttachment = {
|
|
412
548
|
name: attachment.name,
|
|
413
549
|
effectiveMimeType,
|
|
414
550
|
kind,
|
|
@@ -422,9 +558,14 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
|
|
|
422
558
|
workspacePath,
|
|
423
559
|
...(extractedTextWorkspacePath ? { extractedTextWorkspacePath } : {}),
|
|
424
560
|
}),
|
|
425
|
-
}
|
|
561
|
+
} satisfies StagedAttachment;
|
|
562
|
+
this.log(
|
|
563
|
+
`stage_complete session=${sessionId} name=${JSON.stringify(stagedAttachment.name)} kind=${stagedAttachment.kind} mimeType=${stagedAttachment.effectiveMimeType} sizeBytes=${stagedAttachment.sizeBytes} absolutePath=${JSON.stringify(stagedAttachment.absolutePath)} workspacePath=${JSON.stringify(stagedAttachment.workspacePath)}${stagedAttachment.extractedTextWorkspacePath ? ` extractedTextPath=${JSON.stringify(stagedAttachment.extractedTextWorkspacePath)}` : ""}`,
|
|
564
|
+
);
|
|
565
|
+
staged.push(stagedAttachment);
|
|
426
566
|
}
|
|
427
567
|
|
|
568
|
+
this.log(`stage_summary session=${sessionId} staged=${staged.length}`);
|
|
428
569
|
return staged;
|
|
429
570
|
}
|
|
430
571
|
|
|
@@ -602,10 +743,13 @@ function mergeBridgeResponses(
|
|
|
602
743
|
return primary;
|
|
603
744
|
}
|
|
604
745
|
|
|
605
|
-
return toBridgeResponse(
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
746
|
+
return toBridgeResponse(
|
|
747
|
+
[
|
|
748
|
+
...normalizeBridgeResponse(primary),
|
|
749
|
+
...supplemental,
|
|
750
|
+
],
|
|
751
|
+
extractBridgeResponseData(primary),
|
|
752
|
+
);
|
|
609
753
|
}
|
|
610
754
|
|
|
611
755
|
function normalizeBridgeResponse(response: BridgeResponse): NormalizedBridgeMessage[] {
|
|
@@ -623,13 +767,16 @@ function normalizeBridgeResponse(response: BridgeResponse): NormalizedBridgeMess
|
|
|
623
767
|
);
|
|
624
768
|
}
|
|
625
769
|
|
|
626
|
-
function toBridgeResponse(
|
|
770
|
+
function toBridgeResponse(
|
|
771
|
+
messages: NormalizedBridgeMessage[],
|
|
772
|
+
data?: unknown,
|
|
773
|
+
): BridgeResponse {
|
|
627
774
|
if (messages.length === 1) {
|
|
628
775
|
const [message] = messages;
|
|
629
776
|
if (!message) {
|
|
630
777
|
throw new Error("Bridge response did not contain any messages.");
|
|
631
778
|
}
|
|
632
|
-
if (!message.attachments || message.attachments.length === 0) {
|
|
779
|
+
if ((!message.attachments || message.attachments.length === 0) && data === undefined) {
|
|
633
780
|
return message.text;
|
|
634
781
|
}
|
|
635
782
|
}
|
|
@@ -640,6 +787,7 @@ function toBridgeResponse(messages: NormalizedBridgeMessage[]): BridgeResponse {
|
|
|
640
787
|
? message
|
|
641
788
|
: { text: message.text },
|
|
642
789
|
),
|
|
790
|
+
...(data !== undefined ? { data } : {}),
|
|
643
791
|
};
|
|
644
792
|
}
|
|
645
793
|
|
|
@@ -669,6 +817,130 @@ function extractMediaPaths(entry: OpenClawSessionLogEntry): string[] {
|
|
|
669
817
|
return [...mediaPaths];
|
|
670
818
|
}
|
|
671
819
|
|
|
820
|
+
function extractAssistantDisplayResult(entry: OpenClawSessionLogEntry): NormalizedBridgeResult {
|
|
821
|
+
if (entry.type !== "message" || entry.message?.role !== "assistant" || entry.message.isError) {
|
|
822
|
+
return { messages: [] };
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
const parts = (entry.message.content ?? [])
|
|
826
|
+
.flatMap((contentItem) =>
|
|
827
|
+
contentItem.type === "text" && typeof contentItem.text === "string"
|
|
828
|
+
? [contentItem.text.trim()]
|
|
829
|
+
: [],
|
|
830
|
+
)
|
|
831
|
+
.filter((text) => text !== "");
|
|
832
|
+
|
|
833
|
+
if (parts.length === 0) {
|
|
834
|
+
return { messages: [] };
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
const rawText = parts.join("\n\n");
|
|
838
|
+
const structuredResult = parseStructuredResponseResult(rawText);
|
|
839
|
+
if (structuredResult) {
|
|
840
|
+
return structuredResult;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
const fallbackText = stripStructuredResponseBlock(rawText);
|
|
844
|
+
return fallbackText !== "" ? { messages: [{ text: fallbackText }] } : { messages: [] };
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
function appendStructuredResponseContract(prompt: string): string {
|
|
848
|
+
return `${prompt}\n\n${buildStructuredResponseContractPrompt()}`;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
function buildStructuredResponseContractPrompt(): string {
|
|
852
|
+
return [
|
|
853
|
+
"PrivateClaw response contract:",
|
|
854
|
+
`- After you finish your reasoning and tool usage, put the final user-visible result inside exactly one ${PRIVATECLAW_RESPONSE_TAG_START}...${PRIVATECLAW_RESPONSE_TAG_END} block.`,
|
|
855
|
+
"- The block content must be valid JSON.",
|
|
856
|
+
`- Use this JSON shape: {\"version\":${PRIVATECLAW_RESPONSE_CONTRACT_VERSION},\"messages\":[{\"text\":\"...\"}],\"data\":{}}`,
|
|
857
|
+
"- Always include at least one messages entry.",
|
|
858
|
+
"- Put user-visible text only in messages[].text.",
|
|
859
|
+
"- Use data for optional machine-readable extraction results that PrivateClaw may consume in future file-processing flows.",
|
|
860
|
+
"- Do not wrap the JSON in markdown fences.",
|
|
861
|
+
].join("\n");
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
function parseStructuredResponseResult(raw: string): NormalizedBridgeResult | undefined {
|
|
865
|
+
const structured = parseStructuredResponseBlock(raw);
|
|
866
|
+
if (!structured?.messages || structured.messages.length === 0) {
|
|
867
|
+
return undefined;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
const messages = structured.messages.flatMap((message) => {
|
|
871
|
+
const text = typeof message.text === "string" ? message.text.trim() : "";
|
|
872
|
+
return text !== "" ? [{ text }] : [];
|
|
873
|
+
});
|
|
874
|
+
if (messages.length === 0) {
|
|
875
|
+
return undefined;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
return {
|
|
879
|
+
messages,
|
|
880
|
+
...combineStructuredData([{ data: structured.data }]),
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
function parseStructuredResponseBlock(raw: string): PrivateClawStructuredResponse | undefined {
|
|
885
|
+
const match = raw.match(buildStructuredResponseBlockPattern("u"));
|
|
886
|
+
const payload = match?.[1]?.trim();
|
|
887
|
+
if (!payload) {
|
|
888
|
+
return undefined;
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
try {
|
|
892
|
+
const parsed = JSON.parse(payload) as PrivateClawStructuredResponse;
|
|
893
|
+
if (parsed.version !== PRIVATECLAW_RESPONSE_CONTRACT_VERSION || !Array.isArray(parsed.messages)) {
|
|
894
|
+
return undefined;
|
|
895
|
+
}
|
|
896
|
+
return parsed;
|
|
897
|
+
} catch {
|
|
898
|
+
return undefined;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
function stripStructuredResponseBlock(raw: string): string {
|
|
903
|
+
return raw.replace(buildStructuredResponseBlockPattern("gu"), "").trim();
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
function buildStructuredResponseBlockPattern(flags: string): RegExp {
|
|
907
|
+
return new RegExp(
|
|
908
|
+
`${escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_START)}([\\s\\S]*?)${escapeRegExpLiteral(PRIVATECLAW_RESPONSE_TAG_END)}`,
|
|
909
|
+
flags,
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
function escapeRegExpLiteral(value: string): string {
|
|
914
|
+
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
function combineStructuredData(
|
|
918
|
+
results: ReadonlyArray<{ data?: unknown }>,
|
|
919
|
+
): { data?: unknown } {
|
|
920
|
+
const data = [...results]
|
|
921
|
+
.reverse()
|
|
922
|
+
.map((result) => normalizeStructuredData(result.data))
|
|
923
|
+
.find((candidate) => candidate !== undefined);
|
|
924
|
+
return data === undefined ? {} : { data };
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
function normalizeStructuredData(value: unknown): unknown | undefined {
|
|
928
|
+
if (value === undefined || value === null) {
|
|
929
|
+
return undefined;
|
|
930
|
+
}
|
|
931
|
+
if (Array.isArray(value)) {
|
|
932
|
+
return value.length > 0 ? value : undefined;
|
|
933
|
+
}
|
|
934
|
+
if (typeof value === "object") {
|
|
935
|
+
return Object.keys(value as Record<string, unknown>).length > 0 ? value : undefined;
|
|
936
|
+
}
|
|
937
|
+
return value;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
function extractBridgeResponseData(response: BridgeResponse): unknown {
|
|
941
|
+
return typeof response === "string" ? undefined : response.data;
|
|
942
|
+
}
|
|
943
|
+
|
|
672
944
|
async function buildAttachmentFromMediaPath(mediaPath: string): Promise<PrivateClawAttachment> {
|
|
673
945
|
const filePath = normalizeMediaPath(mediaPath);
|
|
674
946
|
const fileBytes = await fs.readFile(filePath);
|
package/src/cli.ts
CHANGED
|
@@ -75,6 +75,9 @@ const bridge =
|
|
|
75
75
|
...(openClawAgentThinking ? { thinking: openClawAgentThinking } : {}),
|
|
76
76
|
...(openClawAgentTimeoutSeconds ? { timeoutSeconds: openClawAgentTimeoutSeconds } : {}),
|
|
77
77
|
...(openClawAgentLocal ? { local: true } : {}),
|
|
78
|
+
onLog: (message) => {
|
|
79
|
+
console.log(`[privateclaw-provider] ${message}`);
|
|
80
|
+
},
|
|
78
81
|
})
|
|
79
82
|
: gatewayChatCompletionsUrl || gatewayBaseUrl
|
|
80
83
|
? new OpenAICompatibleBridge({
|
package/src/openclaw-plugin.ts
CHANGED
|
@@ -246,7 +246,10 @@ function resolvePluginConfig(
|
|
|
246
246
|
};
|
|
247
247
|
}
|
|
248
248
|
|
|
249
|
-
function buildBridge(
|
|
249
|
+
function buildBridge(
|
|
250
|
+
config: ResolvedPrivateClawPluginConfig,
|
|
251
|
+
onLog?: (message: string) => void,
|
|
252
|
+
): PrivateClawAgentBridge {
|
|
250
253
|
if (config.bridgeMode === "webhook") {
|
|
251
254
|
if (!config.webhookUrl) {
|
|
252
255
|
throw new Error(
|
|
@@ -279,6 +282,7 @@ function buildBridge(config: ResolvedPrivateClawPluginConfig): PrivateClawAgentB
|
|
|
279
282
|
...(typeof config.openclawAgentTimeoutSeconds === "number"
|
|
280
283
|
? { timeoutSeconds: config.openclawAgentTimeoutSeconds }
|
|
281
284
|
: {}),
|
|
285
|
+
...(onLog ? { onLog } : {}),
|
|
282
286
|
});
|
|
283
287
|
}
|
|
284
288
|
|
|
@@ -318,11 +322,12 @@ function buildProviderOptions(
|
|
|
318
322
|
api: Pick<OpenClawPluginApiCompat, "logger">,
|
|
319
323
|
): { options: PrivateClawProviderOptions; defaultTtlMs?: number } {
|
|
320
324
|
const relay = resolveRelayEndpoints(pluginConfig.relayBaseUrl);
|
|
325
|
+
const log = (message: string) => api.logger.info(`[privateclaw] ${message}`);
|
|
321
326
|
return {
|
|
322
327
|
options: {
|
|
323
328
|
providerWsUrl: relay.providerWsUrl,
|
|
324
329
|
appWsUrl: relay.appWsUrl,
|
|
325
|
-
bridge: buildBridge(pluginConfig),
|
|
330
|
+
bridge: buildBridge(pluginConfig, log),
|
|
326
331
|
providerLabel: pluginConfig.providerLabel,
|
|
327
332
|
commandsProvider: async () => {
|
|
328
333
|
try {
|
|
@@ -335,7 +340,7 @@ function buildProviderOptions(
|
|
|
335
340
|
}
|
|
336
341
|
},
|
|
337
342
|
...(pluginConfig.welcomeMessage ? { welcomeMessage: pluginConfig.welcomeMessage } : {}),
|
|
338
|
-
onLog:
|
|
343
|
+
onLog: log,
|
|
339
344
|
},
|
|
340
345
|
...(typeof pluginConfig.sessionTtlMs === "number"
|
|
341
346
|
? { defaultTtlMs: pluginConfig.sessionTtlMs }
|