@privateclaw/privateclaw 0.1.15 → 0.1.17
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/openclaw-agent-bridge.d.ts +4 -1
- package/dist/bridges/openclaw-agent-bridge.js +81 -8
- 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 +6 -0
- package/dist/pair-daemon.js +31 -2
- package/dist/pair-daemon.js.map +1 -1
- package/dist/provider.d.ts +2 -0
- package/dist/provider.js +103 -14
- 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 +8 -0
- package/package.json +1 -1
- package/src/audio-transcriber.test.ts +299 -0
- package/src/audio-transcriber.ts +615 -0
- package/src/bridges/openclaw-agent-bridge.test.ts +78 -13
- package/src/bridges/openclaw-agent-bridge.ts +109 -7
- 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.test.ts +48 -0
- package/src/pair-daemon.ts +41 -2
- package/src/provider.test.ts +304 -0
- package/src/provider.ts +146 -20
- 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 +12 -0
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
import { execFile, spawnSync } from "node:child_process";
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import type {
|
|
6
|
+
PrivateClawAudioTranscriber,
|
|
7
|
+
PrivateClawAudioTranscriptionRequest,
|
|
8
|
+
} from "./types.js";
|
|
9
|
+
|
|
10
|
+
export interface PrivateClawSttConfig {
|
|
11
|
+
baseUrl: string;
|
|
12
|
+
model: string;
|
|
13
|
+
apiKey?: string;
|
|
14
|
+
headers?: Record<string, string>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PrivateClawWhisperCliConfig {
|
|
18
|
+
command: string;
|
|
19
|
+
model: string;
|
|
20
|
+
language?: string;
|
|
21
|
+
device?: string;
|
|
22
|
+
modelDir?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface NamedAudioTranscriber {
|
|
26
|
+
label: string;
|
|
27
|
+
transcriber: PrivateClawAudioTranscriber;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface ExecFileTextOptions {
|
|
31
|
+
cwd?: string;
|
|
32
|
+
env?: NodeJS.ProcessEnv;
|
|
33
|
+
maxBuffer?: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
type ExecFileError = NodeJS.ErrnoException & {
|
|
37
|
+
stdout?: string;
|
|
38
|
+
stderr?: string;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
function readString(value: unknown): string | undefined {
|
|
42
|
+
if (typeof value !== "string") {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
const trimmed = value.trim();
|
|
46
|
+
return trimmed === "" ? undefined : trimmed;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function trimTrailingSlashes(value: string): string {
|
|
50
|
+
return value.replace(/\/+$/u, "");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function readStringRecord(value: unknown): Record<string, string> | undefined {
|
|
54
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
const entries = Object.entries(value).flatMap(([key, rawValue]) => {
|
|
58
|
+
const resolvedValue = readString(rawValue);
|
|
59
|
+
return resolvedValue ? [[key, resolvedValue] as const] : [];
|
|
60
|
+
});
|
|
61
|
+
if (entries.length === 0) {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
return Object.fromEntries(entries);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function parseHeaders(value: unknown): Record<string, string> | undefined {
|
|
68
|
+
if (typeof value === "string") {
|
|
69
|
+
const trimmed = value.trim();
|
|
70
|
+
if (trimmed === "") {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
return readStringRecord(JSON.parse(trimmed));
|
|
75
|
+
} catch {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return readStringRecord(value);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function mergeHeaders(
|
|
83
|
+
defaults: Record<string, string> | undefined,
|
|
84
|
+
overrides: Record<string, string> | undefined,
|
|
85
|
+
): Record<string, string> | undefined {
|
|
86
|
+
const merged = {
|
|
87
|
+
...(defaults ?? {}),
|
|
88
|
+
...(overrides ?? {}),
|
|
89
|
+
};
|
|
90
|
+
return Object.keys(merged).length > 0 ? merged : undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function extensionFromMimeType(mimeType: string | undefined): string | undefined {
|
|
94
|
+
switch (mimeType?.trim().toLowerCase()) {
|
|
95
|
+
case "audio/mpeg":
|
|
96
|
+
return ".mp3";
|
|
97
|
+
case "audio/wav":
|
|
98
|
+
case "audio/x-wav":
|
|
99
|
+
return ".wav";
|
|
100
|
+
case "audio/mp4":
|
|
101
|
+
case "audio/aac":
|
|
102
|
+
return ".m4a";
|
|
103
|
+
case "audio/ogg":
|
|
104
|
+
return ".ogg";
|
|
105
|
+
case "audio/webm":
|
|
106
|
+
return ".webm";
|
|
107
|
+
case "audio/x-caf":
|
|
108
|
+
return ".caf";
|
|
109
|
+
default:
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function sanitizeFileName(fileName: string): string {
|
|
115
|
+
return fileName.replace(/[^A-Za-z0-9._-]+/gu, "-").replace(/-+/gu, "-");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function resolveAttachmentFileName(
|
|
119
|
+
request: PrivateClawAudioTranscriptionRequest,
|
|
120
|
+
index: number,
|
|
121
|
+
): string {
|
|
122
|
+
const attachment = request.attachments[index];
|
|
123
|
+
const explicitName = sanitizeFileName(path.basename(attachment?.name?.trim() || ""));
|
|
124
|
+
if (explicitName !== "") {
|
|
125
|
+
return explicitName;
|
|
126
|
+
}
|
|
127
|
+
const extension = extensionFromMimeType(attachment?.mimeType) ?? ".bin";
|
|
128
|
+
return `${request.requestId || "audio"}-${index + 1}${extension}`;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function resolveAttachmentMimeType(
|
|
132
|
+
request: PrivateClawAudioTranscriptionRequest,
|
|
133
|
+
index: number,
|
|
134
|
+
fileName: string,
|
|
135
|
+
): string {
|
|
136
|
+
const explicitMimeType = readString(request.attachments[index]?.mimeType);
|
|
137
|
+
if (explicitMimeType) {
|
|
138
|
+
return explicitMimeType;
|
|
139
|
+
}
|
|
140
|
+
const derivedExtension = path.extname(fileName).toLowerCase();
|
|
141
|
+
switch (derivedExtension) {
|
|
142
|
+
case ".mp3":
|
|
143
|
+
return "audio/mpeg";
|
|
144
|
+
case ".wav":
|
|
145
|
+
return "audio/wav";
|
|
146
|
+
case ".m4a":
|
|
147
|
+
return "audio/mp4";
|
|
148
|
+
case ".aac":
|
|
149
|
+
return "audio/aac";
|
|
150
|
+
case ".ogg":
|
|
151
|
+
return "audio/ogg";
|
|
152
|
+
case ".caf":
|
|
153
|
+
return "audio/x-caf";
|
|
154
|
+
case ".webm":
|
|
155
|
+
return "audio/webm";
|
|
156
|
+
default:
|
|
157
|
+
return "application/octet-stream";
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function coerceText(value: string | Buffer | null | undefined): string {
|
|
162
|
+
if (typeof value === "string") {
|
|
163
|
+
return value;
|
|
164
|
+
}
|
|
165
|
+
if (Buffer.isBuffer(value)) {
|
|
166
|
+
return value.toString("utf8");
|
|
167
|
+
}
|
|
168
|
+
return "";
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function truncateLogDetail(value: string, maxLength = 300): string {
|
|
172
|
+
return value.length > maxLength ? `${value.slice(0, maxLength)}...` : value;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function formatExecError(error: unknown): string {
|
|
176
|
+
if (!(error instanceof Error)) {
|
|
177
|
+
return truncateLogDetail(String(error));
|
|
178
|
+
}
|
|
179
|
+
const execError = error as ExecFileError;
|
|
180
|
+
const details = [
|
|
181
|
+
error.message,
|
|
182
|
+
readString(execError.stderr),
|
|
183
|
+
readString(execError.stdout),
|
|
184
|
+
].filter(Boolean);
|
|
185
|
+
return truncateLogDetail(details.join(" | "));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function execFileText(
|
|
189
|
+
execFileImpl: typeof execFile,
|
|
190
|
+
file: string,
|
|
191
|
+
args: ReadonlyArray<string>,
|
|
192
|
+
options?: ExecFileTextOptions,
|
|
193
|
+
): Promise<{ stdout: string; stderr: string }> {
|
|
194
|
+
return new Promise((resolve, reject) => {
|
|
195
|
+
execFileImpl(
|
|
196
|
+
file,
|
|
197
|
+
[...args],
|
|
198
|
+
{
|
|
199
|
+
encoding: "utf8",
|
|
200
|
+
...(options ?? {}),
|
|
201
|
+
},
|
|
202
|
+
(error, stdout, stderr) => {
|
|
203
|
+
const resolvedStdout = coerceText(stdout);
|
|
204
|
+
const resolvedStderr = coerceText(stderr);
|
|
205
|
+
if (error) {
|
|
206
|
+
const execError = error as ExecFileError;
|
|
207
|
+
execError.stdout = resolvedStdout;
|
|
208
|
+
execError.stderr = resolvedStderr;
|
|
209
|
+
reject(execError);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
resolve({
|
|
213
|
+
stdout: resolvedStdout,
|
|
214
|
+
stderr: resolvedStderr,
|
|
215
|
+
});
|
|
216
|
+
},
|
|
217
|
+
);
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function parseWhisperTranscriptJson(payload: string): string | null {
|
|
222
|
+
const parsed = JSON.parse(payload) as {
|
|
223
|
+
text?: unknown;
|
|
224
|
+
segments?: Array<{ text?: unknown }>;
|
|
225
|
+
};
|
|
226
|
+
const directText = readString(parsed.text);
|
|
227
|
+
if (directText) {
|
|
228
|
+
return directText;
|
|
229
|
+
}
|
|
230
|
+
const segmentText = Array.isArray(parsed.segments)
|
|
231
|
+
? parsed.segments.flatMap((segment) => {
|
|
232
|
+
const value = readString(segment?.text);
|
|
233
|
+
return value ? [value] : [];
|
|
234
|
+
})
|
|
235
|
+
: [];
|
|
236
|
+
const combined = segmentText.join("").trim();
|
|
237
|
+
return combined === "" ? null : combined;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function buildWhisperOutputFilePath(outputDir: string, fileName: string): string {
|
|
241
|
+
return path.join(
|
|
242
|
+
outputDir,
|
|
243
|
+
`${path.basename(fileName, path.extname(fileName))}.json`,
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function resolvePrivateClawSttConfig(params: {
|
|
248
|
+
rootConfig?: unknown;
|
|
249
|
+
baseUrl?: unknown;
|
|
250
|
+
apiKey?: unknown;
|
|
251
|
+
headers?: unknown;
|
|
252
|
+
model?: unknown;
|
|
253
|
+
provider?: unknown;
|
|
254
|
+
}): PrivateClawSttConfig | undefined {
|
|
255
|
+
const rootConfig = (params.rootConfig ?? {}) as Record<string, unknown>;
|
|
256
|
+
const audioModelEntry = (
|
|
257
|
+
(rootConfig.tools as Record<string, unknown> | undefined)?.media as
|
|
258
|
+
| Record<string, unknown>
|
|
259
|
+
| undefined
|
|
260
|
+
)?.audio as Record<string, unknown> | undefined;
|
|
261
|
+
const firstAudioModel = Array.isArray(audioModelEntry?.models)
|
|
262
|
+
? (audioModelEntry?.models[0] as Record<string, unknown> | undefined)
|
|
263
|
+
: undefined;
|
|
264
|
+
const providerId =
|
|
265
|
+
readString(params.provider) ??
|
|
266
|
+
readString(firstAudioModel?.provider) ??
|
|
267
|
+
"openai";
|
|
268
|
+
const providers = (
|
|
269
|
+
rootConfig.models as Record<string, unknown> | undefined
|
|
270
|
+
)?.providers as Record<string, unknown> | undefined;
|
|
271
|
+
const providerConfig = (providers?.[providerId] ?? {}) as Record<string, unknown>;
|
|
272
|
+
|
|
273
|
+
const baseUrl =
|
|
274
|
+
readString(params.baseUrl) ??
|
|
275
|
+
readString(firstAudioModel?.baseUrl) ??
|
|
276
|
+
readString(providerConfig.baseUrl);
|
|
277
|
+
const apiKey =
|
|
278
|
+
readString(params.apiKey) ??
|
|
279
|
+
readString(firstAudioModel?.apiKey) ??
|
|
280
|
+
readString(providerConfig.apiKey);
|
|
281
|
+
const headers = mergeHeaders(
|
|
282
|
+
apiKey ? { Authorization: `Bearer ${apiKey}` } : undefined,
|
|
283
|
+
parseHeaders(params.headers) ??
|
|
284
|
+
parseHeaders(firstAudioModel?.headers) ??
|
|
285
|
+
parseHeaders(providerConfig.headers),
|
|
286
|
+
);
|
|
287
|
+
const model =
|
|
288
|
+
readString(params.model) ??
|
|
289
|
+
readString(firstAudioModel?.model) ??
|
|
290
|
+
"whisper-1";
|
|
291
|
+
|
|
292
|
+
if (!baseUrl) {
|
|
293
|
+
return undefined;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return {
|
|
297
|
+
baseUrl: trimTrailingSlashes(baseUrl),
|
|
298
|
+
model,
|
|
299
|
+
...(apiKey ? { apiKey } : {}),
|
|
300
|
+
...(headers ? { headers } : {}),
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function resolvePrivateClawWhisperCliConfig(params?: {
|
|
305
|
+
env?: NodeJS.ProcessEnv;
|
|
306
|
+
command?: unknown;
|
|
307
|
+
model?: unknown;
|
|
308
|
+
language?: unknown;
|
|
309
|
+
device?: unknown;
|
|
310
|
+
modelDir?: unknown;
|
|
311
|
+
spawnSyncImpl?: typeof spawnSync;
|
|
312
|
+
}): PrivateClawWhisperCliConfig | undefined {
|
|
313
|
+
const env = params?.env ?? process.env;
|
|
314
|
+
const command =
|
|
315
|
+
readString(params?.command) ??
|
|
316
|
+
readString(env.PRIVATECLAW_WHISPER_BIN) ??
|
|
317
|
+
"whisper";
|
|
318
|
+
const spawnSyncImpl = params?.spawnSyncImpl ?? spawnSync;
|
|
319
|
+
const probe = spawnSyncImpl(command, ["--help"], {
|
|
320
|
+
encoding: "utf8",
|
|
321
|
+
stdio: "pipe",
|
|
322
|
+
timeout: 10_000,
|
|
323
|
+
env,
|
|
324
|
+
});
|
|
325
|
+
if (probe.error) {
|
|
326
|
+
return undefined;
|
|
327
|
+
}
|
|
328
|
+
const helpText = `${coerceText(probe.stdout)}\n${coerceText(probe.stderr)}`;
|
|
329
|
+
if ((probe.status ?? 1) !== 0 || !/usage:\s*whisper\b/iu.test(helpText)) {
|
|
330
|
+
return undefined;
|
|
331
|
+
}
|
|
332
|
+
const model =
|
|
333
|
+
readString(params?.model) ??
|
|
334
|
+
readString(env.PRIVATECLAW_WHISPER_MODEL) ??
|
|
335
|
+
"turbo";
|
|
336
|
+
const language =
|
|
337
|
+
readString(params?.language) ??
|
|
338
|
+
readString(env.PRIVATECLAW_WHISPER_LANGUAGE);
|
|
339
|
+
const device =
|
|
340
|
+
readString(params?.device) ??
|
|
341
|
+
readString(env.PRIVATECLAW_WHISPER_DEVICE);
|
|
342
|
+
const modelDir =
|
|
343
|
+
readString(params?.modelDir) ??
|
|
344
|
+
readString(env.PRIVATECLAW_WHISPER_MODEL_DIR);
|
|
345
|
+
|
|
346
|
+
return {
|
|
347
|
+
command,
|
|
348
|
+
model,
|
|
349
|
+
...(language ? { language } : {}),
|
|
350
|
+
...(device ? { device } : {}),
|
|
351
|
+
...(modelDir ? { modelDir } : {}),
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function transcribeSingleAttachment(params: {
|
|
356
|
+
request: PrivateClawAudioTranscriptionRequest;
|
|
357
|
+
index: number;
|
|
358
|
+
sttConfig: PrivateClawSttConfig;
|
|
359
|
+
onLog?: (message: string) => void;
|
|
360
|
+
}): Promise<string | null> {
|
|
361
|
+
const fileName = resolveAttachmentFileName(params.request, params.index);
|
|
362
|
+
const mimeType = resolveAttachmentMimeType(params.request, params.index, fileName);
|
|
363
|
+
const dataBase64 = readString(params.request.attachments[params.index]?.dataBase64);
|
|
364
|
+
if (!dataBase64) {
|
|
365
|
+
throw new Error(`Missing base64 audio payload for ${fileName}.`);
|
|
366
|
+
}
|
|
367
|
+
const fileBytes = Buffer.from(dataBase64, "base64");
|
|
368
|
+
|
|
369
|
+
const form = new FormData();
|
|
370
|
+
form.append("file", new Blob([fileBytes], { type: mimeType }), fileName);
|
|
371
|
+
form.append("model", params.sttConfig.model);
|
|
372
|
+
|
|
373
|
+
params.onLog?.(
|
|
374
|
+
`[stt] transcribe_start session=${params.request.sessionId} request=${params.request.requestId} file=${JSON.stringify(fileName)} mimeType=${mimeType} sizeBytes=${fileBytes.length} model=${params.sttConfig.model}`,
|
|
375
|
+
);
|
|
376
|
+
|
|
377
|
+
const response = await fetch(`${params.sttConfig.baseUrl}/audio/transcriptions`, {
|
|
378
|
+
method: "POST",
|
|
379
|
+
...(params.sttConfig.headers ? { headers: params.sttConfig.headers } : {}),
|
|
380
|
+
body: form,
|
|
381
|
+
});
|
|
382
|
+
if (!response.ok) {
|
|
383
|
+
const detail = await response.text().catch(() => "");
|
|
384
|
+
throw new Error(
|
|
385
|
+
`STT failed for ${fileName} (HTTP ${response.status}): ${detail.slice(0, 300)}`,
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const result = (await response.json()) as { text?: string };
|
|
390
|
+
const transcript = result.text?.trim() || null;
|
|
391
|
+
params.onLog?.(
|
|
392
|
+
`[stt] transcribe_complete session=${params.request.sessionId} request=${params.request.requestId} file=${JSON.stringify(fileName)} transcriptChars=${transcript?.length ?? 0}`,
|
|
393
|
+
);
|
|
394
|
+
return transcript;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async function transcribeSingleAttachmentWithWhisperCli(params: {
|
|
398
|
+
request: PrivateClawAudioTranscriptionRequest;
|
|
399
|
+
index: number;
|
|
400
|
+
whisperConfig: PrivateClawWhisperCliConfig;
|
|
401
|
+
onLog?: (message: string) => void;
|
|
402
|
+
execFileImpl?: typeof execFile;
|
|
403
|
+
}): Promise<string | null> {
|
|
404
|
+
const fileName = resolveAttachmentFileName(params.request, params.index);
|
|
405
|
+
const mimeType = resolveAttachmentMimeType(params.request, params.index, fileName);
|
|
406
|
+
const dataBase64 = readString(params.request.attachments[params.index]?.dataBase64);
|
|
407
|
+
if (!dataBase64) {
|
|
408
|
+
throw new Error(`Missing base64 audio payload for ${fileName}.`);
|
|
409
|
+
}
|
|
410
|
+
const fileBytes = Buffer.from(dataBase64, "base64");
|
|
411
|
+
const execFileImpl = params.execFileImpl ?? execFile;
|
|
412
|
+
const tempDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-whisper-stt-"));
|
|
413
|
+
const inputPath = path.join(tempDir, fileName);
|
|
414
|
+
const outputPath = buildWhisperOutputFilePath(tempDir, fileName);
|
|
415
|
+
|
|
416
|
+
try {
|
|
417
|
+
await writeFile(inputPath, fileBytes);
|
|
418
|
+
const args = [
|
|
419
|
+
inputPath,
|
|
420
|
+
"--model",
|
|
421
|
+
params.whisperConfig.model,
|
|
422
|
+
"--output_dir",
|
|
423
|
+
tempDir,
|
|
424
|
+
"--output_format",
|
|
425
|
+
"json",
|
|
426
|
+
"--task",
|
|
427
|
+
"transcribe",
|
|
428
|
+
"--verbose",
|
|
429
|
+
"False",
|
|
430
|
+
...(params.whisperConfig.language
|
|
431
|
+
? ["--language", params.whisperConfig.language]
|
|
432
|
+
: []),
|
|
433
|
+
...(params.whisperConfig.device
|
|
434
|
+
? ["--device", params.whisperConfig.device]
|
|
435
|
+
: []),
|
|
436
|
+
...(params.whisperConfig.modelDir
|
|
437
|
+
? ["--model_dir", params.whisperConfig.modelDir]
|
|
438
|
+
: []),
|
|
439
|
+
];
|
|
440
|
+
params.onLog?.(
|
|
441
|
+
`[stt] whisper_transcribe_start session=${params.request.sessionId} request=${params.request.requestId} file=${JSON.stringify(fileName)} mimeType=${mimeType} sizeBytes=${fileBytes.length} command=${JSON.stringify(params.whisperConfig.command)} model=${JSON.stringify(params.whisperConfig.model)}`,
|
|
442
|
+
);
|
|
443
|
+
await execFileText(execFileImpl, params.whisperConfig.command, args, {
|
|
444
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
445
|
+
});
|
|
446
|
+
const transcriptPayload = await readFile(outputPath, "utf8");
|
|
447
|
+
const transcript = parseWhisperTranscriptJson(transcriptPayload);
|
|
448
|
+
params.onLog?.(
|
|
449
|
+
`[stt] whisper_transcribe_complete session=${params.request.sessionId} request=${params.request.requestId} file=${JSON.stringify(fileName)} transcriptChars=${transcript?.length ?? 0}`,
|
|
450
|
+
);
|
|
451
|
+
return transcript;
|
|
452
|
+
} catch (error) {
|
|
453
|
+
throw new Error(`whisper CLI failed for ${fileName}: ${formatExecError(error)}`);
|
|
454
|
+
} finally {
|
|
455
|
+
await rm(tempDir, { recursive: true, force: true });
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function createFallbackAudioTranscriber(
|
|
460
|
+
candidates: ReadonlyArray<NamedAudioTranscriber>,
|
|
461
|
+
params?: { onLog?: (message: string) => void },
|
|
462
|
+
): PrivateClawAudioTranscriber {
|
|
463
|
+
return {
|
|
464
|
+
async transcribeAudioAttachments(
|
|
465
|
+
request: PrivateClawAudioTranscriptionRequest,
|
|
466
|
+
): Promise<string> {
|
|
467
|
+
const failures: string[] = [];
|
|
468
|
+
for (let index = 0; index < candidates.length; index += 1) {
|
|
469
|
+
const candidate = candidates[index]!;
|
|
470
|
+
const nextCandidate = candidates[index + 1];
|
|
471
|
+
params?.onLog?.(
|
|
472
|
+
`[stt] provider_stt_try session=${request.sessionId} request=${request.requestId} via=${JSON.stringify(candidate.label)}`,
|
|
473
|
+
);
|
|
474
|
+
try {
|
|
475
|
+
const transcript = (await candidate.transcriber.transcribeAudioAttachments(request))
|
|
476
|
+
.trim();
|
|
477
|
+
if (transcript === "") {
|
|
478
|
+
throw new Error(`${candidate.label} returned an empty transcript.`);
|
|
479
|
+
}
|
|
480
|
+
params?.onLog?.(
|
|
481
|
+
`[stt] provider_stt_success session=${request.sessionId} request=${request.requestId} via=${JSON.stringify(candidate.label)} transcriptChars=${transcript.length}`,
|
|
482
|
+
);
|
|
483
|
+
return transcript;
|
|
484
|
+
} catch (error) {
|
|
485
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
486
|
+
failures.push(`${candidate.label}: ${detail}`);
|
|
487
|
+
params?.onLog?.(
|
|
488
|
+
`[stt] provider_stt_failed session=${request.sessionId} request=${request.requestId} via=${JSON.stringify(candidate.label)} error=${JSON.stringify(truncateLogDetail(detail))}${nextCandidate ? ` next=${JSON.stringify(nextCandidate.label)}` : ""}`,
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
throw new Error(
|
|
493
|
+
`All provider-side STT backends failed for ${request.requestId}: ${failures.join(" | ")}`,
|
|
494
|
+
);
|
|
495
|
+
},
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
export function createOpenAICompatibleAudioTranscriber(
|
|
500
|
+
sttConfig: PrivateClawSttConfig,
|
|
501
|
+
params?: { onLog?: (message: string) => void },
|
|
502
|
+
): PrivateClawAudioTranscriber {
|
|
503
|
+
return {
|
|
504
|
+
async transcribeAudioAttachments(
|
|
505
|
+
request: PrivateClawAudioTranscriptionRequest,
|
|
506
|
+
): Promise<string> {
|
|
507
|
+
const transcripts: string[] = [];
|
|
508
|
+
for (let index = 0; index < request.attachments.length; index += 1) {
|
|
509
|
+
const transcript = await transcribeSingleAttachment({
|
|
510
|
+
request,
|
|
511
|
+
index,
|
|
512
|
+
sttConfig,
|
|
513
|
+
...(params?.onLog ? { onLog: params.onLog } : {}),
|
|
514
|
+
});
|
|
515
|
+
if (transcript) {
|
|
516
|
+
transcripts.push(transcript);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
return transcripts.join("\n\n").trim();
|
|
520
|
+
},
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export function createWhisperCliAudioTranscriber(
|
|
525
|
+
whisperConfig: PrivateClawWhisperCliConfig,
|
|
526
|
+
params?: {
|
|
527
|
+
onLog?: (message: string) => void;
|
|
528
|
+
execFileImpl?: typeof execFile;
|
|
529
|
+
},
|
|
530
|
+
): PrivateClawAudioTranscriber {
|
|
531
|
+
return {
|
|
532
|
+
async transcribeAudioAttachments(
|
|
533
|
+
request: PrivateClawAudioTranscriptionRequest,
|
|
534
|
+
): Promise<string> {
|
|
535
|
+
const transcripts: string[] = [];
|
|
536
|
+
for (let index = 0; index < request.attachments.length; index += 1) {
|
|
537
|
+
const transcript = await transcribeSingleAttachmentWithWhisperCli({
|
|
538
|
+
request,
|
|
539
|
+
index,
|
|
540
|
+
whisperConfig,
|
|
541
|
+
...(params?.onLog ? { onLog: params.onLog } : {}),
|
|
542
|
+
...(params?.execFileImpl ? { execFileImpl: params.execFileImpl } : {}),
|
|
543
|
+
});
|
|
544
|
+
if (transcript) {
|
|
545
|
+
transcripts.push(transcript);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
return transcripts.join("\n\n").trim();
|
|
549
|
+
},
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
export function buildPreferredAudioTranscriber(params?: {
|
|
554
|
+
rootConfig?: unknown;
|
|
555
|
+
env?: NodeJS.ProcessEnv;
|
|
556
|
+
onLog?: (message: string) => void;
|
|
557
|
+
whisperSpawnSyncImpl?: typeof spawnSync;
|
|
558
|
+
whisperExecFileImpl?: typeof execFile;
|
|
559
|
+
}): PrivateClawAudioTranscriber | undefined {
|
|
560
|
+
const env = params?.env ?? process.env;
|
|
561
|
+
const candidates: NamedAudioTranscriber[] = [];
|
|
562
|
+
const whisperCommand = readString(env.PRIVATECLAW_WHISPER_BIN) ?? "whisper";
|
|
563
|
+
const whisperConfig = resolvePrivateClawWhisperCliConfig({
|
|
564
|
+
env,
|
|
565
|
+
...(params?.whisperSpawnSyncImpl
|
|
566
|
+
? { spawnSyncImpl: params.whisperSpawnSyncImpl }
|
|
567
|
+
: {}),
|
|
568
|
+
});
|
|
569
|
+
if (whisperConfig) {
|
|
570
|
+
params?.onLog?.(
|
|
571
|
+
`[stt] whisper_cli_enabled command=${JSON.stringify(whisperConfig.command)} model=${JSON.stringify(whisperConfig.model)}${whisperConfig.language ? ` language=${JSON.stringify(whisperConfig.language)}` : ""}${whisperConfig.device ? ` device=${JSON.stringify(whisperConfig.device)}` : ""}`,
|
|
572
|
+
);
|
|
573
|
+
candidates.push({
|
|
574
|
+
label: "whisper-cli",
|
|
575
|
+
transcriber: createWhisperCliAudioTranscriber(whisperConfig, {
|
|
576
|
+
...(params?.onLog ? { onLog: params.onLog } : {}),
|
|
577
|
+
...(params?.whisperExecFileImpl
|
|
578
|
+
? { execFileImpl: params.whisperExecFileImpl }
|
|
579
|
+
: {}),
|
|
580
|
+
}),
|
|
581
|
+
});
|
|
582
|
+
} else {
|
|
583
|
+
params?.onLog?.(
|
|
584
|
+
`[stt] whisper_cli_unavailable command=${JSON.stringify(whisperCommand)}`,
|
|
585
|
+
);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const sttConfig = resolvePrivateClawSttConfig({
|
|
589
|
+
rootConfig: params?.rootConfig,
|
|
590
|
+
baseUrl: env.PRIVATECLAW_STT_BASE_URL,
|
|
591
|
+
apiKey: env.PRIVATECLAW_STT_API_KEY,
|
|
592
|
+
headers: env.PRIVATECLAW_STT_HEADERS,
|
|
593
|
+
model: env.PRIVATECLAW_STT_MODEL,
|
|
594
|
+
provider: env.PRIVATECLAW_STT_PROVIDER,
|
|
595
|
+
});
|
|
596
|
+
if (sttConfig) {
|
|
597
|
+
params?.onLog?.(
|
|
598
|
+
`[stt] direct_stt_enabled baseUrl=${JSON.stringify(sttConfig.baseUrl)} model=${JSON.stringify(sttConfig.model)}`,
|
|
599
|
+
);
|
|
600
|
+
candidates.push({
|
|
601
|
+
label: "provider-config",
|
|
602
|
+
transcriber: createOpenAICompatibleAudioTranscriber(sttConfig, {
|
|
603
|
+
...(params?.onLog ? { onLog: params.onLog } : {}),
|
|
604
|
+
}),
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
if (candidates.length === 0) {
|
|
609
|
+
return undefined;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
return createFallbackAudioTranscriber(candidates, {
|
|
613
|
+
...(params?.onLog ? { onLog: params.onLog } : {}),
|
|
614
|
+
});
|
|
615
|
+
}
|