offmute-v2 0.0.1-opus.0

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/cli.js ADDED
@@ -0,0 +1,1529 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { Command } from "commander";
5
+ import { basename as basename3, extname as extname3, join as join4, resolve } from "path";
6
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
7
+
8
+ // src/pipeline.ts
9
+ import { basename as basename2, dirname as dirname3, extname as extname2, join as join3 } from "path";
10
+ import { existsSync as existsSync2 } from "fs";
11
+
12
+ // src/media/ffmpeg.ts
13
+ import { spawn } from "child_process";
14
+ import { mkdir } from "fs/promises";
15
+ import { dirname, join } from "path";
16
+ function run(cmd, args) {
17
+ return new Promise((resolve2, reject) => {
18
+ const child = spawn(cmd, args);
19
+ let stdout = "";
20
+ let stderr = "";
21
+ child.stdout.on("data", (d) => stdout += d.toString());
22
+ child.stderr.on("data", (d) => stderr += d.toString());
23
+ child.on("error", reject);
24
+ child.on("close", (code) => resolve2({ code: code ?? -1, stdout, stderr }));
25
+ });
26
+ }
27
+ async function ensureDir(filePath) {
28
+ await mkdir(dirname(filePath), { recursive: true });
29
+ }
30
+ async function probeMedia(input) {
31
+ const { code, stdout, stderr } = await run("ffprobe", [
32
+ "-v",
33
+ "error",
34
+ "-print_format",
35
+ "json",
36
+ "-show_format",
37
+ "-show_streams",
38
+ input
39
+ ]);
40
+ if (code !== 0) {
41
+ throw new Error(`ffprobe failed (${code}): ${stderr}`);
42
+ }
43
+ const data = JSON.parse(stdout);
44
+ const streams = data.streams ?? [];
45
+ const video = streams.find((s2) => s2["codec_type"] === "video");
46
+ const audio = streams.find((s2) => s2["codec_type"] === "audio");
47
+ const info = {
48
+ durationSeconds: parseFloat(data.format?.duration ?? "0") || 0,
49
+ hasVideo: !!video,
50
+ hasAudio: !!audio,
51
+ sizeBytes: data.format?.size ? parseInt(data.format.size, 10) : void 0
52
+ };
53
+ if (video) {
54
+ info.width = Number(video["width"]) || void 0;
55
+ info.height = Number(video["height"]) || void 0;
56
+ info.videoCodec = video["codec_name"] || void 0;
57
+ }
58
+ if (audio) {
59
+ info.audioCodec = audio["codec_name"] || void 0;
60
+ info.sampleRate = Number(audio["sample_rate"]) || void 0;
61
+ info.channels = Number(audio["channels"]) || void 0;
62
+ }
63
+ return info;
64
+ }
65
+ async function extractAudio(input, output, options = {}) {
66
+ const {
67
+ sampleRate = 16e3,
68
+ channels = 1,
69
+ startSeconds,
70
+ durationSeconds,
71
+ bitrate = "64k",
72
+ overwrite = true
73
+ } = options;
74
+ await ensureDir(output);
75
+ const args = [];
76
+ if (overwrite) args.push("-y");
77
+ if (startSeconds !== void 0) args.push("-ss", String(startSeconds));
78
+ args.push("-i", input);
79
+ if (durationSeconds !== void 0) args.push("-t", String(durationSeconds));
80
+ args.push("-vn", "-ac", String(channels), "-ar", String(sampleRate));
81
+ const ext = output.slice(output.lastIndexOf(".") + 1).toLowerCase();
82
+ if (ext === "mp3") {
83
+ args.push("-c:a", "libmp3lame", "-b:a", bitrate);
84
+ } else if (ext === "opus") {
85
+ args.push("-c:a", "libopus", "-b:a", bitrate);
86
+ } else if (ext === "wav") {
87
+ args.push("-c:a", "pcm_s16le");
88
+ } else if (ext === "flac") {
89
+ args.push("-c:a", "flac");
90
+ } else if (ext === "m4a" || ext === "aac") {
91
+ args.push("-c:a", "aac", "-b:a", bitrate);
92
+ }
93
+ args.push(output);
94
+ const { code, stderr } = await run("ffmpeg", args);
95
+ if (code !== 0) throw new Error(`ffmpeg extractAudio failed (${code}): ${stderr}`);
96
+ return output;
97
+ }
98
+ async function extractKeyframes(input, outputDir, options = {}) {
99
+ const { atSeconds, count, maxSize = 768, durationSeconds, overwrite = true } = options;
100
+ await mkdir(outputDir, { recursive: true });
101
+ let times;
102
+ if (atSeconds && atSeconds.length > 0) {
103
+ times = atSeconds;
104
+ } else if (count && durationSeconds) {
105
+ times = Array.from(
106
+ { length: count },
107
+ (_, i) => Math.max(0.5, (i + 0.5) / count * durationSeconds)
108
+ );
109
+ } else {
110
+ throw new Error("extractKeyframes: provide atSeconds, or count + durationSeconds");
111
+ }
112
+ const paths = [];
113
+ await Promise.all(
114
+ times.map(async (t, i) => {
115
+ const out = join(outputDir, `frame_${String(i).padStart(3, "0")}_${Math.round(t)}s.jpg`);
116
+ const args = [];
117
+ if (overwrite) args.push("-y");
118
+ args.push(
119
+ "-ss",
120
+ String(t),
121
+ "-i",
122
+ input,
123
+ "-frames:v",
124
+ "1",
125
+ "-vf",
126
+ `scale='min(${maxSize},iw)':-2`,
127
+ "-q:v",
128
+ "3",
129
+ out
130
+ );
131
+ const { code, stderr } = await run("ffmpeg", args);
132
+ if (code !== 0) throw new Error(`ffmpeg keyframe @${t}s failed: ${stderr}`);
133
+ paths[i] = out;
134
+ })
135
+ );
136
+ return paths;
137
+ }
138
+
139
+ // src/providers/assemblyai.ts
140
+ import { AssemblyAI } from "assemblyai";
141
+ var s = (ms) => (ms ?? 0) / 1e3;
142
+ async function transcribeWithAssemblyAI(audioPath, options = {}) {
143
+ const apiKey = options.apiKey ?? process.env.ASSEMBLYAI_API_KEY;
144
+ if (!apiKey) throw new Error("Missing ASSEMBLYAI_API_KEY");
145
+ const client = new AssemblyAI({ apiKey });
146
+ const params = {
147
+ audio: audioPath,
148
+ speaker_labels: options.speakerLabels !== false
149
+ };
150
+ if (options.speakersExpected) params["speakers_expected"] = options.speakersExpected;
151
+ if (options.speechModel) params["speech_model"] = options.speechModel;
152
+ if (options.languageCode) params["language_code"] = options.languageCode;
153
+ const t = await client.transcripts.transcribe(params);
154
+ if (t.status === "error") throw new Error(`AssemblyAI failed: ${t.error}`);
155
+ const words = (t.words ?? []).map((w) => ({
156
+ text: w.text,
157
+ start: s(w.start),
158
+ end: s(w.end),
159
+ confidence: w.confidence,
160
+ speaker: w.speaker ?? void 0
161
+ }));
162
+ const utterances = (t.utterances ?? []).map((u) => ({
163
+ text: u.text,
164
+ start: s(u.start),
165
+ end: s(u.end),
166
+ speaker: u.speaker ?? "?",
167
+ confidence: u.confidence,
168
+ words: u.words?.map((w) => ({
169
+ text: w.text,
170
+ start: s(w.start),
171
+ end: s(w.end),
172
+ confidence: w.confidence,
173
+ speaker: w.speaker ?? void 0
174
+ }))
175
+ }));
176
+ const speakerSet = /* @__PURE__ */ new Set();
177
+ for (const u of utterances) speakerSet.add(u.speaker);
178
+ for (const w of words) if (w.speaker) speakerSet.add(w.speaker);
179
+ const asr = {
180
+ provider: "assemblyai",
181
+ model: options.speechModel,
182
+ words,
183
+ utterances,
184
+ speakers: [...speakerSet].sort(),
185
+ durationSeconds: t.audio_duration ?? (words.length ? words[words.length - 1].end : 0),
186
+ language: t.language_code,
187
+ diarized: utterances.length > 0 && speakerSet.size > 0
188
+ };
189
+ return { asr, raw: t };
190
+ }
191
+
192
+ // src/providers/gemini.ts
193
+ import { GoogleGenAI } from "@google/genai";
194
+ import { basename, extname } from "path";
195
+
196
+ // src/core/retry.ts
197
+ function isRetryableError(err) {
198
+ const e = err;
199
+ const code = e?.status ?? e?.code;
200
+ if (typeof code === "number" && [408, 429, 500, 502, 503, 504].includes(code)) return true;
201
+ const msg = (e?.message ?? String(err)).toLowerCase();
202
+ return /unavailable|overloaded|rate.?limit|deadline|timeout|temporar|try again|resource.?exhausted|\b(429|500|502|503|504)\b|internal error|econnreset|etimedout|socket hang|fetch failed|network/.test(
203
+ msg
204
+ );
205
+ }
206
+ async function withRetry(fn, opts = {}) {
207
+ const retries = opts.retries ?? 4;
208
+ const base = opts.baseDelayMs ?? 1e3;
209
+ let lastErr;
210
+ for (let attempt = 0; attempt <= retries; attempt++) {
211
+ try {
212
+ return await fn();
213
+ } catch (err) {
214
+ lastErr = err;
215
+ if (attempt === retries || !isRetryableError(err)) throw err;
216
+ const delayMs = Math.min(3e4, base * 2 ** attempt) + Math.floor(Math.random() * 250);
217
+ opts.onRetry?.({ attempt: attempt + 1, retries, delayMs, error: err });
218
+ await new Promise((r) => setTimeout(r, delayMs));
219
+ }
220
+ }
221
+ throw lastErr;
222
+ }
223
+
224
+ // src/providers/thinking.ts
225
+ var BUDGET_BY_LEVEL = {
226
+ // 2.5: flash can disable (0); pro cannot go below ~128.
227
+ MINIMAL: { flash: 0, pro: 128 },
228
+ LOW: { flash: 2048, pro: 2048 },
229
+ MEDIUM: { flash: 8192, pro: 8192 },
230
+ HIGH: { flash: 24576, pro: 24576 }
231
+ };
232
+ function resolveThinkingConfig(model, level, explicitBudget) {
233
+ const m = model.toLowerCase();
234
+ const isPro = m.includes("pro");
235
+ if (explicitBudget !== void 0 && m.includes("gemini-2.5")) {
236
+ return { thinkingBudget: explicitBudget };
237
+ }
238
+ if (level === void 0) return void 0;
239
+ if (m.includes("gemini-2.5")) {
240
+ return { thinkingBudget: BUDGET_BY_LEVEL[level][isPro ? "pro" : "flash"] };
241
+ }
242
+ if (m.includes("gemini-2")) {
243
+ return void 0;
244
+ }
245
+ if (isPro) {
246
+ return { thinkingLevel: level === "MINIMAL" ? "LOW" : level };
247
+ }
248
+ return { thinkingLevel: level };
249
+ }
250
+ function isThinkingConfigError(err) {
251
+ const msg = (err?.message ?? String(err)).toLowerCase();
252
+ return /thinking[_ ]?(level|budget)|thinking.*(not supported|unsupported)/.test(msg);
253
+ }
254
+
255
+ // src/providers/gemini.ts
256
+ var MIME_BY_EXT = {
257
+ ".mp3": "audio/mp3",
258
+ ".mpga": "audio/mpeg",
259
+ ".wav": "audio/wav",
260
+ ".flac": "audio/flac",
261
+ ".aac": "audio/aac",
262
+ ".m4a": "audio/mp4",
263
+ ".opus": "audio/opus",
264
+ ".ogg": "audio/ogg",
265
+ ".mp4": "video/mp4",
266
+ ".mov": "video/quicktime",
267
+ ".webm": "video/webm",
268
+ ".png": "image/png",
269
+ ".jpg": "image/jpeg",
270
+ ".jpeg": "image/jpeg",
271
+ ".webp": "image/webp"
272
+ };
273
+ function mimeForPath(path) {
274
+ const ext = extname(path).toLowerCase();
275
+ const m = MIME_BY_EXT[ext];
276
+ if (!m) throw new Error(`Unknown mime for ${path}`);
277
+ return m;
278
+ }
279
+ function retry(fn, label, retries) {
280
+ return withRetry(fn, {
281
+ retries,
282
+ onRetry: ({ attempt, retries: n, delayMs, error }) => process.stderr.write(
283
+ `
284
+ [retry ${label} ${attempt}/${n} in ${delayMs}ms] ${error?.message?.slice(0, 90) ?? String(error)}`
285
+ )
286
+ });
287
+ }
288
+ var GeminiClient = class {
289
+ ai;
290
+ /** if set, invoked once per generate() with the prompt/response/usage (for logging). */
291
+ onCall;
292
+ constructor(apiKey) {
293
+ const key = apiKey ?? process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY;
294
+ if (!key) throw new Error("Missing GEMINI_API_KEY / GOOGLE_API_KEY");
295
+ this.ai = new GoogleGenAI({ apiKey: key });
296
+ }
297
+ /** Upload a local file via the Files API and wait until it's ACTIVE. */
298
+ async uploadFile(filePath, mimeType) {
299
+ const mt = mimeType ?? mimeForPath(filePath);
300
+ const uploaded = await retry(
301
+ () => this.ai.files.upload({ file: filePath, config: { mimeType: mt, displayName: basename(filePath) } }),
302
+ `upload ${basename(filePath)}`
303
+ );
304
+ let file = uploaded;
305
+ const name = file.name;
306
+ while (file.state === "PROCESSING") {
307
+ await new Promise((r) => setTimeout(r, 1500));
308
+ file = await this.ai.files.get({ name });
309
+ }
310
+ if (file.state === "FAILED") throw new Error(`Gemini file processing failed: ${name}`);
311
+ return { uri: file.uri, mimeType: file.mimeType ?? mt, name };
312
+ }
313
+ async deleteFile(name) {
314
+ try {
315
+ await this.ai.files.delete({ name });
316
+ } catch {
317
+ }
318
+ }
319
+ /** Generate content from a mix of files (paths or pre-uploaded) and text. */
320
+ async generate(parts, options = {}) {
321
+ const model = options.model ?? "gemini-flash-latest";
322
+ const builtParts = [];
323
+ const toCleanup = [];
324
+ for (const p of parts) {
325
+ if (p.text !== void 0) {
326
+ builtParts.push({ text: p.text });
327
+ } else if (p.uploaded) {
328
+ builtParts.push({ fileData: { fileUri: p.uploaded.uri, mimeType: p.uploaded.mimeType } });
329
+ } else if (p.filePath) {
330
+ const up = await this.uploadFile(p.filePath);
331
+ toCleanup.push(up.name);
332
+ builtParts.push({ fileData: { fileUri: up.uri, mimeType: up.mimeType } });
333
+ }
334
+ }
335
+ const config = {
336
+ temperature: options.temperature ?? 0.2
337
+ };
338
+ if (options.maxOutputTokens) config["maxOutputTokens"] = options.maxOutputTokens;
339
+ if (options.systemInstruction) config["systemInstruction"] = options.systemInstruction;
340
+ if (options.schema) {
341
+ config["responseMimeType"] = "application/json";
342
+ config["responseSchema"] = options.schema;
343
+ }
344
+ const thinking = resolveThinkingConfig(model, options.thinkingLevel, options.thinkingBudget);
345
+ if (thinking) config["thinkingConfig"] = thinking;
346
+ const call = (cfg) => this.ai.models.generateContent({ model, contents: [{ role: "user", parts: builtParts }], config: cfg });
347
+ const promptText = parts.filter((p) => p.text !== void 0).map((p) => p.text).join("\n");
348
+ const fileParts = parts.filter((p) => p.filePath || p.uploaded).length;
349
+ try {
350
+ let resp;
351
+ try {
352
+ resp = await retry(() => call(config), `generate ${model}`, options.retries ?? 4);
353
+ } catch (err) {
354
+ if (isThinkingConfigError(err) && config["thinkingConfig"]) {
355
+ process.stderr.write(`
356
+ [thinking config unsupported for ${model}; retrying without it]`);
357
+ const { thinkingConfig: _drop, ...rest } = config;
358
+ resp = await retry(() => call(rest), `generate ${model} (no-thinking)`, options.retries ?? 4);
359
+ } else {
360
+ this.onCall?.({ label: options.label, model, promptText, fileParts, responseText: "", error: err?.message ?? String(err) });
361
+ throw err;
362
+ }
363
+ }
364
+ const usage = resp.usageMetadata;
365
+ const result = {
366
+ text: resp.text ?? "",
367
+ usage: {
368
+ inputTokens: usage?.promptTokenCount,
369
+ outputTokens: usage?.candidatesTokenCount,
370
+ thoughtsTokens: usage?.thoughtsTokenCount
371
+ },
372
+ model,
373
+ raw: resp
374
+ };
375
+ this.onCall?.({ label: options.label, model, promptText, fileParts, responseText: result.text, usage: result.usage });
376
+ return result;
377
+ } finally {
378
+ await Promise.all(toCleanup.map((n) => this.deleteFile(n)));
379
+ }
380
+ }
381
+ };
382
+
383
+ // src/core/time.ts
384
+ function secondsToSrtTime(seconds) {
385
+ const s2 = Number.isFinite(seconds) ? Math.max(0, seconds) : 0;
386
+ const hours = Math.floor(s2 / 3600);
387
+ const minutes = Math.floor(s2 % 3600 / 60);
388
+ const secs = Math.floor(s2 % 60);
389
+ const ms = Math.round((s2 - Math.floor(s2)) * 1e3);
390
+ let carrySecs = secs;
391
+ let carryMin = minutes;
392
+ let carryHrs = hours;
393
+ let outMs = ms;
394
+ if (outMs === 1e3) {
395
+ outMs = 0;
396
+ carrySecs += 1;
397
+ }
398
+ if (carrySecs === 60) {
399
+ carrySecs = 0;
400
+ carryMin += 1;
401
+ }
402
+ if (carryMin === 60) {
403
+ carryMin = 0;
404
+ carryHrs += 1;
405
+ }
406
+ return `${String(carryHrs).padStart(2, "0")}:${String(carryMin).padStart(2, "0")}:${String(carrySecs).padStart(2, "0")},${String(outMs).padStart(3, "0")}`;
407
+ }
408
+ function relTimeToSeconds(timeStr) {
409
+ const parts = timeStr.trim().split(":");
410
+ if (parts.length < 2 || parts.length > 3) return null;
411
+ const nums = parts.map((p) => parseInt(p, 10));
412
+ if (nums.some((n) => Number.isNaN(n))) return null;
413
+ if (nums.length === 2) {
414
+ const [m2, s3] = nums;
415
+ return m2 * 60 + s3;
416
+ }
417
+ const [h, m, s2] = nums;
418
+ return h * 3600 + m * 60 + s2;
419
+ }
420
+ function secondsToCompact(seconds) {
421
+ const s2 = Math.max(0, Math.floor(seconds));
422
+ const h = Math.floor(s2 / 3600);
423
+ const m = Math.floor(s2 % 3600 / 60);
424
+ const sec = s2 % 60;
425
+ if (h > 0) {
426
+ return `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}`;
427
+ }
428
+ return `${m}:${String(sec).padStart(2, "0")}`;
429
+ }
430
+ function formatSrtTiming(start, end) {
431
+ return `${secondsToSrtTime(start)} --> ${secondsToSrtTime(end)}`;
432
+ }
433
+
434
+ // src/core/prompts.ts
435
+ var DIARIZATION_SYSTEM = `You are an expert meeting transcriptionist and diarizer. You transcribe verbatim (including filler words and false starts), attribute every utterance to the correct speaker, and you are careful and literal. You never invent content you cannot hear.`;
436
+ function buildDiarizationPrompt(input) {
437
+ const { instructions, asrHint, chunk, previousTail } = input;
438
+ const parts = [];
439
+ if (chunk && chunk.total > 1) {
440
+ parts.push(
441
+ `This is part ${chunk.index + 1} of ${chunk.total} of a longer recording. This part starts at ${secondsToCompact(chunk.startSeconds)} in the full recording. Use timestamps RELATIVE to the start of THIS clip ([mm:ss] from 0:00).`
442
+ );
443
+ } else {
444
+ parts.push(`This is a recorded talk/meeting. Produce a complete diarized transcript.`);
445
+ }
446
+ if (instructions) {
447
+ parts.push(`
448
+ IMPORTANT USER INSTRUCTIONS (follow these for speaker labeling and focus):
449
+ ${instructions}`);
450
+ }
451
+ if (asrHint) {
452
+ parts.push(
453
+ `
454
+ A baseline speech-to-text system produced the rough diarization below. Its TIMING is reliable but its SPEAKER LABELS are often wrong (it splits one person into several, merges different people, and misses short interjections). Use it only as a hint \u2014 trust what you HEAR for who is speaking:
455
+
456
+ ${asrHint}`
457
+ );
458
+ }
459
+ if (previousTail) {
460
+ parts.push(
461
+ `
462
+ For speaker continuity only, the previous part ended with the lines below. The start of THIS clip overlaps the previous part \u2014 transcribe EVERYTHING you hear in THIS clip in full (from 0:00), including any overlap; do not skip the beginning:
463
+ ...${previousTail}`
464
+ );
465
+ }
466
+ parts.push(`
467
+ Instructions:
468
+ - Diarize: identify each distinct speaker. Infer real names from context (introductions, people addressing each other) when possible; otherwise label "Speaker 1", "Speaker 2", etc. Keep each speaker's label consistent throughout.
469
+ - Give the start timestamp of every speaker turn in [mm:ss].
470
+ - Add a brief tone/emotion note in parentheses when notable: (laughing), (hesitant), (emphatic), (audience member), etc. Omit when neutral.
471
+ - Transcribe verbatim. Start a new line whenever the speaker changes.
472
+
473
+ Output ONLY the transcript, one line per speaker turn, exactly:
474
+ [mm:ss] Speaker: (tone) text
475
+
476
+ Begin.`);
477
+ return parts.join("\n");
478
+ }
479
+ function buildAsrHint(asr, maxUtterances = 200, maxCharsPerUtterance = 160) {
480
+ const lines = [];
481
+ const utts = asr.utterances.slice(0, maxUtterances);
482
+ for (const u of utts) {
483
+ const text = u.text.length > maxCharsPerUtterance ? u.text.slice(0, maxCharsPerUtterance) + "\u2026" : u.text;
484
+ lines.push(`[${secondsToCompact(u.start)}] ${u.speaker}: ${text}`);
485
+ }
486
+ if (asr.utterances.length > maxUtterances) lines.push(`\u2026 (${asr.utterances.length - maxUtterances} more)`);
487
+ return lines.join("\n");
488
+ }
489
+
490
+ // src/core/align.ts
491
+ function normalizeToken(s2) {
492
+ return s2.toLowerCase().replace(/[^a-z0-9]/g, "");
493
+ }
494
+ function tokenize(text) {
495
+ return text.split(/\s+/).filter((t) => t.length > 0);
496
+ }
497
+ function alignTokens(a, b) {
498
+ const n = a.length;
499
+ const m = b.length;
500
+ const MATCH = 2;
501
+ const MISMATCH = -1;
502
+ const GAP = -1;
503
+ const w = m + 1;
504
+ const score = new Int32Array((n + 1) * w);
505
+ const back = new Uint8Array((n + 1) * w);
506
+ for (let i2 = 1; i2 <= n; i2++) {
507
+ score[i2 * w] = i2 * GAP;
508
+ back[i2 * w] = 1;
509
+ }
510
+ for (let j2 = 1; j2 <= m; j2++) {
511
+ score[j2] = j2 * GAP;
512
+ back[j2] = 2;
513
+ }
514
+ for (let i2 = 1; i2 <= n; i2++) {
515
+ const ai = a[i2 - 1];
516
+ const rowOff = i2 * w;
517
+ const prevRowOff = (i2 - 1) * w;
518
+ for (let j2 = 1; j2 <= m; j2++) {
519
+ const isMatch = ai === b[j2 - 1];
520
+ const diag = score[prevRowOff + j2 - 1] + (isMatch ? MATCH : MISMATCH);
521
+ const up = score[prevRowOff + j2] + GAP;
522
+ const left = score[rowOff + j2 - 1] + GAP;
523
+ let best = diag;
524
+ let dir = 0;
525
+ if (up > best) {
526
+ best = up;
527
+ dir = 1;
528
+ }
529
+ if (left > best) {
530
+ best = left;
531
+ dir = 2;
532
+ }
533
+ score[rowOff + j2] = best;
534
+ back[rowOff + j2] = dir;
535
+ }
536
+ }
537
+ const pairs = [];
538
+ let i = n;
539
+ let j = m;
540
+ while (i > 0 || j > 0) {
541
+ if (i > 0 && j > 0 && back[i * w + j] === 0) {
542
+ pairs.push({ ai: i - 1, bi: j - 1, match: a[i - 1] === b[j - 1] });
543
+ i--;
544
+ j--;
545
+ } else if (i > 0 && (j === 0 || back[i * w + j] === 1)) {
546
+ pairs.push({ ai: i - 1, bi: null, match: false });
547
+ i--;
548
+ } else {
549
+ pairs.push({ ai: null, bi: j - 1, match: false });
550
+ j--;
551
+ }
552
+ }
553
+ pairs.reverse();
554
+ return pairs;
555
+ }
556
+ function alignLlmToAsr(turns, asrWords) {
557
+ const tokens = [];
558
+ turns.forEach((turn, turnIndex) => {
559
+ for (const surface of tokenize(turn.text)) {
560
+ const norm = normalizeToken(surface);
561
+ if (!norm) continue;
562
+ tokens.push({ surface, norm, turnIndex, start: null, end: null, matched: false });
563
+ }
564
+ });
565
+ const asrNorm = asrWords.map((w) => normalizeToken(w.text));
566
+ const pairs = alignTokens(
567
+ tokens.map((t) => t.norm),
568
+ asrNorm
569
+ );
570
+ for (const p of pairs) {
571
+ if (p.ai === null) continue;
572
+ const tok = tokens[p.ai];
573
+ if (p.match && p.bi !== null) {
574
+ const w = asrWords[p.bi];
575
+ tok.start = w.start;
576
+ tok.end = w.end;
577
+ tok.matched = true;
578
+ if (w.speaker) tok.asrSpeaker = w.speaker;
579
+ }
580
+ }
581
+ return tokens;
582
+ }
583
+ function fillTokenTimes(tokens, totalDuration) {
584
+ const n = tokens.length;
585
+ if (n === 0) return tokens;
586
+ const anchors = [];
587
+ for (let i = 0; i < n; i++) if (tokens[i].matched) anchors.push(i);
588
+ if (anchors.length === 0) {
589
+ for (let i = 0; i < n; i++) {
590
+ tokens[i].start = i / n * totalDuration;
591
+ tokens[i].end = (i + 1) / n * totalDuration;
592
+ }
593
+ return tokens;
594
+ }
595
+ const first = anchors[0];
596
+ for (let i = 0; i < first; i++) {
597
+ tokens[i].start = tokens[first].start;
598
+ tokens[i].end = tokens[first].start;
599
+ }
600
+ const last = anchors[anchors.length - 1];
601
+ for (let i = last + 1; i < n; i++) {
602
+ tokens[i].start = tokens[last].end;
603
+ tokens[i].end = tokens[last].end;
604
+ }
605
+ for (let a = 0; a < anchors.length - 1; a++) {
606
+ const lo = anchors[a];
607
+ const hi = anchors[a + 1];
608
+ const t0 = tokens[lo].end ?? tokens[lo].start ?? 0;
609
+ const t1 = tokens[hi].start ?? t0;
610
+ const gap = hi - lo;
611
+ for (let i = lo + 1; i < hi; i++) {
612
+ const frac = (i - lo) / gap;
613
+ const t = t0 + frac * (t1 - t0);
614
+ tokens[i].start = t;
615
+ tokens[i].end = t;
616
+ }
617
+ }
618
+ return tokens;
619
+ }
620
+ var SENTENCE_END = /[.!?…]["')\]]?$/;
621
+ function buildSegmentsFromTokens(turns, tokens, options = {}) {
622
+ const {
623
+ subSegment = false,
624
+ maxChars = 90,
625
+ maxDuration = 7,
626
+ gapSplit = 1,
627
+ minChars = 24
628
+ } = options;
629
+ const byTurn = /* @__PURE__ */ new Map();
630
+ for (const t of tokens) {
631
+ const arr = byTurn.get(t.turnIndex);
632
+ if (arr) arr.push(t);
633
+ else byTurn.set(t.turnIndex, [t]);
634
+ }
635
+ const segments = [];
636
+ for (let turnIndex = 0; turnIndex < turns.length; turnIndex++) {
637
+ const toks = byTurn.get(turnIndex);
638
+ if (!toks || toks.length === 0) continue;
639
+ if (!subSegment) {
640
+ segments.push(makeSegment(turnIndex, toks));
641
+ continue;
642
+ }
643
+ let cur = [];
644
+ let curChars = 0;
645
+ const flush = () => {
646
+ if (cur.length > 0) {
647
+ segments.push(makeSegment(turnIndex, cur));
648
+ cur = [];
649
+ curChars = 0;
650
+ }
651
+ };
652
+ for (let i = 0; i < toks.length; i++) {
653
+ const tok = toks[i];
654
+ cur.push(tok);
655
+ curChars += tok.surface.length + 1;
656
+ const next = toks[i + 1];
657
+ const curStart = cur[0].start ?? 0;
658
+ const curEnd = tok.end ?? curStart;
659
+ const dur = curEnd - curStart;
660
+ const bothMatched = tok.matched && (next?.matched ?? false);
661
+ const gapToNext = bothMatched && next && next.start !== null && tok.end !== null ? next.start - tok.end : 0;
662
+ const sentenceBreak = SENTENCE_END.test(tok.surface) && curChars >= minChars;
663
+ const tooLong = curChars >= maxChars || dur >= maxDuration;
664
+ const bigGap = gapToNext >= gapSplit && curChars >= minChars;
665
+ if (sentenceBreak || tooLong || bigGap) flush();
666
+ }
667
+ flush();
668
+ }
669
+ return segments;
670
+ }
671
+ function asrSpeakerByLabel(tokens, labelByTurn) {
672
+ const out = {};
673
+ for (const tok of tokens) {
674
+ if (!tok.matched || !tok.asrSpeaker) continue;
675
+ const label = labelByTurn[tok.turnIndex];
676
+ if (label === void 0) continue;
677
+ out[label] ??= {};
678
+ out[label][tok.asrSpeaker] = (out[label][tok.asrSpeaker] ?? 0) + 1;
679
+ }
680
+ return out;
681
+ }
682
+ function makeSegment(turnIndex, toks) {
683
+ const matched = toks.filter((t) => t.matched);
684
+ const starts = toks.map((t) => t.start).filter((x) => x !== null);
685
+ const ends = toks.map((t) => t.end).filter((x) => x !== null);
686
+ const start = starts.length ? Math.min(...starts) : 0;
687
+ const end = ends.length ? Math.max(...ends) : start;
688
+ return {
689
+ turnIndex,
690
+ start,
691
+ end: Math.max(end, start),
692
+ text: toks.map((t) => t.surface).join(" "),
693
+ matchRatio: toks.length ? matched.length / toks.length : 0,
694
+ tokenCount: toks.length,
695
+ matchedTokens: matched.length
696
+ };
697
+ }
698
+
699
+ // src/core/speakers.ts
700
+ var PROVISIONAL_RE = /^(speaker|spkr|unknown|unidentified)\b/i;
701
+ function slugLabel(label) {
702
+ return label.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "speaker";
703
+ }
704
+ function isProvisional(label) {
705
+ return PROVISIONAL_RE.test(label.trim());
706
+ }
707
+ function buildSpeakers(rawLabels, options = {}) {
708
+ const { knownSpeakers = {}, resolvedNames = {}, descriptions = {} } = options;
709
+ const labelToId = /* @__PURE__ */ new Map();
710
+ const byId = /* @__PURE__ */ new Map();
711
+ const resolveCanonical = (raw) => {
712
+ if (knownSpeakers[raw]) return knownSpeakers[raw];
713
+ if (resolvedNames[raw]) {
714
+ const resolvedName = resolvedNames[raw];
715
+ return knownSpeakers[resolvedName] ?? resolvedName;
716
+ }
717
+ return raw;
718
+ };
719
+ for (const raw of rawLabels) {
720
+ if (labelToId.has(raw)) continue;
721
+ const canonical = resolveCanonical(raw);
722
+ const id = slugLabel(canonical);
723
+ labelToId.set(raw, id);
724
+ if (!byId.has(id)) {
725
+ byId.set(id, {
726
+ id,
727
+ label: canonical,
728
+ named: !isProvisional(canonical),
729
+ description: descriptions[canonical]
730
+ });
731
+ } else if (descriptions[canonical] && !byId.get(id).description) {
732
+ byId.get(id).description = descriptions[canonical];
733
+ }
734
+ }
735
+ return { speakers: [...byId.values()], labelToId };
736
+ }
737
+
738
+ // src/core/assemble.ts
739
+ function alignTurnsToSegments(turns, asrWords, totalDuration, subSegment) {
740
+ if (!asrWords || asrWords.length === 0) {
741
+ const segments2 = turns.map((t, i) => {
742
+ const start = t.approxStart ?? 0;
743
+ const end = turns[i + 1]?.approxStart ?? totalDuration;
744
+ return {
745
+ start,
746
+ end: Math.max(start, end),
747
+ speakerLabel: t.speaker,
748
+ tone: t.tone,
749
+ text: t.text,
750
+ matchRatio: 0
751
+ };
752
+ });
753
+ return { segments: segments2, voiceDist: {} };
754
+ }
755
+ const tokens = alignLlmToAsr(turns, asrWords);
756
+ fillTokenTimes(tokens, totalDuration);
757
+ const voiceDist = asrSpeakerByLabel(tokens, turns.map((t) => t.speaker));
758
+ const aligned = buildSegmentsFromTokens(turns, tokens, { subSegment });
759
+ const segments = [];
760
+ const toneSeen = /* @__PURE__ */ new Set();
761
+ for (const s2 of aligned) {
762
+ if (s2.matchedTokens === 0 && s2.tokenCount <= 3) continue;
763
+ const turn = turns[s2.turnIndex];
764
+ const firstOfTurn = !toneSeen.has(s2.turnIndex);
765
+ toneSeen.add(s2.turnIndex);
766
+ segments.push({
767
+ start: s2.start,
768
+ end: s2.end,
769
+ speakerLabel: turn.speaker,
770
+ tone: firstOfTurn ? turn.tone : void 0,
771
+ text: s2.text,
772
+ matchRatio: s2.matchRatio
773
+ });
774
+ }
775
+ return { segments, voiceDist };
776
+ }
777
+ function buildTranscript(segments, metadata, options = {}) {
778
+ const { knownSpeakers, resolvedNames, descriptions } = options;
779
+ const { speakers, labelToId } = buildSpeakers(
780
+ segments.map((s2) => s2.speakerLabel),
781
+ { knownSpeakers, resolvedNames, descriptions }
782
+ );
783
+ const transcriptSegments = segments.map((s2, i) => ({
784
+ id: i + 1,
785
+ start: s2.start,
786
+ end: s2.end,
787
+ speakerId: labelToId.get(s2.speakerLabel) ?? s2.speakerLabel,
788
+ text: s2.text,
789
+ tone: s2.tone,
790
+ timingSource: s2.matchRatio > 0 ? "asr" : "llm",
791
+ alignmentConfidence: s2.matchRatio
792
+ }));
793
+ return { segments: transcriptSegments, speakers, metadata };
794
+ }
795
+
796
+ // src/core/chunk.ts
797
+ function calculateChunks(totalSeconds, chunkSeconds, overlapSeconds) {
798
+ if (totalSeconds <= chunkSeconds) {
799
+ return [{ index: 0, startSeconds: 0, endSeconds: totalSeconds }];
800
+ }
801
+ const overlap = Math.max(0, Math.min(overlapSeconds, chunkSeconds * 0.5));
802
+ const step = Math.max(1, chunkSeconds - overlap);
803
+ const chunks = [];
804
+ let start = 0;
805
+ let index = 0;
806
+ while (start < totalSeconds) {
807
+ const end = Math.min(start + chunkSeconds, totalSeconds);
808
+ if (end >= totalSeconds && end - start < chunkSeconds / 3 && chunks.length > 0) {
809
+ chunks[chunks.length - 1].endSeconds = end;
810
+ break;
811
+ }
812
+ chunks.push({ index, startSeconds: start, endSeconds: end });
813
+ index++;
814
+ if (end >= totalSeconds) break;
815
+ start += step;
816
+ }
817
+ return chunks;
818
+ }
819
+ function chunkOwnership(chunks, totalDuration) {
820
+ return chunks.map((c, i) => {
821
+ const prev = chunks[i - 1];
822
+ const next = chunks[i + 1];
823
+ const start = i === 0 || !prev ? 0 : (prev.endSeconds + c.startSeconds) / 2;
824
+ const end = i === chunks.length - 1 || !next ? totalDuration : (c.endSeconds + next.startSeconds) / 2;
825
+ return { start, end };
826
+ });
827
+ }
828
+ function mergeChunkSegments(segments, chunkBoundaries) {
829
+ const sorted = [...segments].sort((a, b) => a.start - b.start || a.end - b.end);
830
+ const kept = [];
831
+ for (const seg of sorted) {
832
+ const dup = kept.find(
833
+ (k) => k.chunkIndex !== seg.chunkIndex && timeOverlapRatio(k, seg) > 0.5 && textSimilar(k.text, seg.text)
834
+ );
835
+ if (!dup) {
836
+ kept.push(seg);
837
+ continue;
838
+ }
839
+ if (segmentScore(seg, chunkBoundaries) > segmentScore(dup, chunkBoundaries)) {
840
+ kept[kept.indexOf(dup)] = seg;
841
+ }
842
+ }
843
+ return kept.sort((a, b) => a.start - b.start);
844
+ }
845
+ function timeOverlapRatio(a, b) {
846
+ const lo = Math.max(a.start, b.start);
847
+ const hi = Math.min(a.end, b.end);
848
+ const inter = Math.max(0, hi - lo);
849
+ const minLen = Math.max(0.01, Math.min(a.end - a.start, b.end - b.start));
850
+ return inter / minLen;
851
+ }
852
+ function textSimilar(a, b) {
853
+ const wa = new Set(a.toLowerCase().replace(/[^a-z0-9 ]/g, "").split(/\s+/).filter(Boolean));
854
+ const wb = new Set(b.toLowerCase().replace(/[^a-z0-9 ]/g, "").split(/\s+/).filter(Boolean));
855
+ if (wa.size === 0 || wb.size === 0) return false;
856
+ let inter = 0;
857
+ for (const w of wa) if (wb.has(w)) inter++;
858
+ const jaccard = inter / (wa.size + wb.size - inter);
859
+ return jaccard > 0.4;
860
+ }
861
+ function segmentScore(seg, chunks) {
862
+ const chunk = chunks[seg.chunkIndex];
863
+ let edgeDistance = 999;
864
+ if (chunk) {
865
+ edgeDistance = Math.min(seg.start - chunk.startSeconds, chunk.endSeconds - seg.end);
866
+ }
867
+ return seg.matchRatio * 10 + Math.min(edgeDistance, 30);
868
+ }
869
+
870
+ // src/core/parse-diarized.ts
871
+ var LINE_RE = /^\s*(?:\[(?<ts>\d{1,2}:\d{2}(?::\d{2})?)\]\s*)?(?<speaker>[^:\[\]]{1,40}?):\s*(?:\((?<tone>[^)]{1,60})\)\s*)?(?<text>.*)$/;
872
+ function parseDiarizedText(raw) {
873
+ const lines = raw.replace(/\r\n/g, "\n").split("\n");
874
+ const out = [];
875
+ for (const line of lines) {
876
+ const trimmed = line.trim();
877
+ if (!trimmed) continue;
878
+ if (/^```/.test(trimmed)) continue;
879
+ const m = trimmed.match(LINE_RE);
880
+ if (m && m.groups && m.groups["text"] !== void 0) {
881
+ const speaker = m.groups["speaker"].trim();
882
+ const tsStr = m.groups["ts"];
883
+ const tone = m.groups["tone"]?.trim();
884
+ const text = m.groups["text"].trim();
885
+ if (speaker.split(/\s+/).length > 6) {
886
+ appendContinuation(out, trimmed);
887
+ continue;
888
+ }
889
+ const approxStart = tsStr ? relTimeToSeconds(tsStr) ?? void 0 : void 0;
890
+ out.push({
891
+ speaker,
892
+ text,
893
+ tone: tone || void 0,
894
+ approxStart
895
+ });
896
+ } else {
897
+ appendContinuation(out, trimmed);
898
+ }
899
+ }
900
+ return out;
901
+ }
902
+ function appendContinuation(out, text) {
903
+ const last = out[out.length - 1];
904
+ if (last) last.text = `${last.text} ${text}`.trim();
905
+ }
906
+
907
+ // src/core/orchestrate.ts
908
+ function sliceAsrWindow(asr, start, end, relative) {
909
+ const off = relative ? start : 0;
910
+ const utterances = asr.utterances.filter((u) => u.end >= start && u.start <= end).map((u) => ({ ...u, start: u.start - off, end: u.end - off }));
911
+ return { ...asr, utterances, words: [] };
912
+ }
913
+ function mergeVoiceDist(target, source) {
914
+ for (const [label, counts] of Object.entries(source)) {
915
+ target[label] ??= {};
916
+ for (const [sp, n] of Object.entries(counts)) target[label][sp] = (target[label][sp] ?? 0) + n;
917
+ }
918
+ }
919
+ var toPlain = (m) => ({
920
+ start: m.start,
921
+ end: m.end,
922
+ speakerLabel: m.speakerLabel,
923
+ tone: m.tone,
924
+ text: m.text,
925
+ matchRatio: m.matchRatio
926
+ });
927
+ async function orchestrateChunks(opts) {
928
+ const { asr, durationSeconds, instructions, subSegment, signal, onProgress, diarizeChunk, onChunk } = opts;
929
+ const timeChunks = durationSeconds <= opts.maxSinglePassSeconds ? [{ index: 0, startSeconds: 0, endSeconds: durationSeconds }] : calculateChunks(durationSeconds, opts.chunkSeconds, opts.overlapSeconds);
930
+ const chunked = timeChunks.length > 1;
931
+ const ownership = chunked ? chunkOwnership(timeChunks, durationSeconds) : null;
932
+ const allTurns = [];
933
+ const mergeable = [];
934
+ const voiceDist = {};
935
+ let previousTail = "";
936
+ for (const ch of timeChunks) {
937
+ signal?.throwIfAborted();
938
+ onProgress?.(chunked ? `Diarizing chunk ${ch.index + 1}/${timeChunks.length}` : `Diarizing`, ch.index, timeChunks.length);
939
+ const windowHint = asr && asr.diarized ? buildAsrHint(sliceAsrWindow(asr, ch.startSeconds, ch.endSeconds, chunked)) : void 0;
940
+ const prompt = buildDiarizationPrompt({
941
+ instructions,
942
+ asrHint: windowHint,
943
+ chunk: chunked ? { index: ch.index, total: timeChunks.length, startSeconds: ch.startSeconds } : void 0,
944
+ previousTail: chunked ? previousTail : void 0
945
+ });
946
+ const rawText = await diarizeChunk({ chunk: ch, index: ch.index, total: timeChunks.length, chunked, prompt });
947
+ const turns = parseDiarizedText(rawText);
948
+ if (turns.length === 0) throw new Error(`No diarized turns parsed from LLM output${chunked ? ` (chunk ${ch.index})` : ""}`);
949
+ previousTail = turns.slice(-3).map((t) => `${t.speaker}: ${t.text}`).join("\n");
950
+ if (chunked) {
951
+ for (const t of turns) if (t.approxStart !== void 0) t.approxStart += ch.startSeconds;
952
+ }
953
+ allTurns.push(...turns);
954
+ if (asr) {
955
+ const windowWords = chunked ? asr.words.filter((w) => w.start >= ch.startSeconds - 2 && w.start <= ch.endSeconds + 2) : asr.words;
956
+ const { segments: segments2, voiceDist: vd } = alignTurnsToSegments(turns, windowWords, durationSeconds, subSegment);
957
+ mergeVoiceDist(voiceDist, vd);
958
+ const own = ownership?.[ch.index];
959
+ for (const s2 of segments2) {
960
+ if (own) {
961
+ const center = (s2.start + s2.end) / 2;
962
+ if (center < own.start || center >= own.end) continue;
963
+ }
964
+ mergeable.push({ ...s2, chunkIndex: ch.index });
965
+ }
966
+ }
967
+ if (onChunk) {
968
+ const segmentsSoFar = [...mergeable].sort((a, b) => a.start - b.start).map(toPlain);
969
+ await onChunk({ index: ch.index, total: timeChunks.length, chunked, rawText, turns, segmentsSoFar });
970
+ }
971
+ }
972
+ let segments;
973
+ if (asr) {
974
+ const merged = chunked ? mergeChunkSegments(mergeable, timeChunks) : mergeable;
975
+ segments = merged.map(toPlain);
976
+ } else {
977
+ segments = alignTurnsToSegments(allTurns, void 0, durationSeconds, subSegment).segments;
978
+ }
979
+ return { segments, allTurns, voiceDist, chunkCount: timeChunks.length };
980
+ }
981
+
982
+ // src/core/srt.ts
983
+ function formatSrt(cues, options = {}) {
984
+ const { includeSpeaker = true } = options;
985
+ return cues.map((cue, i) => {
986
+ const speakerPrefix = includeSpeaker && cue.speaker ? `${cue.speaker}: ` : "";
987
+ return `${i + 1}
988
+ ${formatSrtTiming(cue.start, cue.end)}
989
+ ${speakerPrefix}${cue.text}`;
990
+ }).join("\n\n") + "\n";
991
+ }
992
+
993
+ // src/core/format.ts
994
+ function speakerLabelMap(transcript) {
995
+ const m = /* @__PURE__ */ new Map();
996
+ for (const sp of transcript.speakers) m.set(sp.id, sp.label);
997
+ return m;
998
+ }
999
+ function srtCueText(s2) {
1000
+ return s2.replace(/\r\n?/g, "\n").replace(/\n[ \t]*\n+/g, "\n").trim() || " ";
1001
+ }
1002
+ function toSRT(transcript, options = {}) {
1003
+ const { includeSpeaker = true, includeTone = false } = options;
1004
+ const labels = speakerLabelMap(transcript);
1005
+ const blocks = transcript.segments.map((seg, i) => {
1006
+ const label = labels.get(seg.speakerId) ?? seg.speakerId;
1007
+ const prefix = includeSpeaker ? `${label}: ` : "";
1008
+ const tone = includeTone && seg.tone ? `(${seg.tone}) ` : "";
1009
+ const body = srtCueText(`${prefix}${tone}${seg.text}`);
1010
+ return `${i + 1}
1011
+ ${formatSrtTiming(seg.start, Math.max(seg.start, seg.end))}
1012
+ ${body}`;
1013
+ });
1014
+ return blocks.join("\n\n") + "\n";
1015
+ }
1016
+ function toMarkdown(transcript, options = {}) {
1017
+ const { includeTimestamps = true, includeTone = true, title = "Transcript", mergeBySpeaker = true } = options;
1018
+ const labels = speakerLabelMap(transcript);
1019
+ const out = [];
1020
+ out.push(`# ${title}
1021
+ `);
1022
+ const m = transcript.metadata;
1023
+ out.push(`*Duration: ${secondsToCompact(m.durationSeconds)} \xB7 ${transcript.segments.length} segments \xB7 ${transcript.speakers.length} speakers*`);
1024
+ if (m.asrProvider || m.llmModel) {
1025
+ out.push(`*ASR: ${m.asrProvider ?? "\u2014"} \xB7 LLM: ${m.llmModel ?? "\u2014"}*`);
1026
+ }
1027
+ out.push("");
1028
+ out.push(`## Speakers
1029
+ `);
1030
+ for (const sp of transcript.speakers) {
1031
+ const named = sp.named ? "" : " *(unidentified)*";
1032
+ const desc = sp.description ? ` \u2014 ${sp.description}` : "";
1033
+ out.push(`- **${sp.label}**${named}${desc}`);
1034
+ }
1035
+ out.push(`
1036
+ ## Transcript
1037
+ `);
1038
+ const groups = mergeBySpeaker ? groupBySpeaker(transcript.segments) : transcript.segments.map((s2) => [s2]);
1039
+ for (const group of groups) {
1040
+ const first = group[0];
1041
+ const label = labels.get(first.speakerId) ?? first.speakerId;
1042
+ const ts = includeTimestamps ? `\`[${secondsToCompact(first.start)}]\` ` : "";
1043
+ const text = group.map((s2) => includeTone && s2.tone ? `*(${s2.tone})* ${s2.text}` : s2.text).join(" ");
1044
+ out.push(`${ts}**${label}:** ${text}
1045
+ `);
1046
+ }
1047
+ return out.join("\n");
1048
+ }
1049
+ function groupBySpeaker(segments) {
1050
+ const groups = [];
1051
+ for (const seg of segments) {
1052
+ const last = groups[groups.length - 1];
1053
+ if (last && last[0].speakerId === seg.speakerId) last.push(seg);
1054
+ else groups.push([seg]);
1055
+ }
1056
+ return groups;
1057
+ }
1058
+ function toJSON(transcript) {
1059
+ return JSON.stringify(transcript, null, 2);
1060
+ }
1061
+ function toText(transcript, options = {}) {
1062
+ const { includeTimestamps = true } = options;
1063
+ const labels = speakerLabelMap(transcript);
1064
+ return groupBySpeaker(transcript.segments).map((group) => {
1065
+ const first = group[0];
1066
+ const label = labels.get(first.speakerId) ?? first.speakerId;
1067
+ const ts = includeTimestamps ? `[${secondsToCompact(first.start)}] ` : "";
1068
+ return `${ts}${label}: ${group.map((s2) => s2.text).join(" ")}`;
1069
+ }).join("\n\n") + "\n";
1070
+ }
1071
+
1072
+ // src/node/intermediates.ts
1073
+ import { createHash } from "crypto";
1074
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
1075
+ import { dirname as dirname2, join as join2 } from "path";
1076
+ function mediaKey(filePath) {
1077
+ const st = statSync(filePath);
1078
+ return createHash("sha256").update(`${filePath}:${st.size}:${st.mtimeMs}`).digest("hex").slice(0, 16);
1079
+ }
1080
+ var Intermediates = class {
1081
+ constructor(dir) {
1082
+ this.dir = dir;
1083
+ mkdirSync(dir, { recursive: true });
1084
+ }
1085
+ dir;
1086
+ path(name) {
1087
+ return join2(this.dir, name);
1088
+ }
1089
+ /** Resolve a name to a path, ensuring its parent dir exists (supports "sub/dir/file"). */
1090
+ ensurePath(name) {
1091
+ const p = this.path(name);
1092
+ mkdirSync(dirname2(p), { recursive: true });
1093
+ return p;
1094
+ }
1095
+ has(name) {
1096
+ return existsSync(this.path(name));
1097
+ }
1098
+ readJSON(name) {
1099
+ const p = this.path(name);
1100
+ if (!existsSync(p)) return null;
1101
+ try {
1102
+ return JSON.parse(readFileSync(p, "utf8"));
1103
+ } catch {
1104
+ return null;
1105
+ }
1106
+ }
1107
+ writeJSON(name, data) {
1108
+ writeFileSync(this.ensurePath(name), JSON.stringify(data, null, 2));
1109
+ }
1110
+ readText(name) {
1111
+ const p = this.path(name);
1112
+ return existsSync(p) ? readFileSync(p, "utf8") : null;
1113
+ }
1114
+ writeText(name, data) {
1115
+ writeFileSync(this.ensurePath(name), data);
1116
+ }
1117
+ /** Run `producer` unless a cached JSON exists (and cache is enabled). */
1118
+ async cachedJSON(name, enabled, producer) {
1119
+ if (enabled) {
1120
+ const hit = this.readJSON(name);
1121
+ if (hit !== null) return hit;
1122
+ }
1123
+ const result = await producer();
1124
+ this.writeJSON(name, result);
1125
+ return result;
1126
+ }
1127
+ async cachedText(name, enabled, producer) {
1128
+ if (enabled) {
1129
+ const hit = this.readText(name);
1130
+ if (hit !== null) return hit;
1131
+ }
1132
+ const result = await producer();
1133
+ this.writeText(name, result);
1134
+ return result;
1135
+ }
1136
+ };
1137
+
1138
+ // src/core/identify.ts
1139
+ var IDENTIFY_SCHEMA = {
1140
+ type: "OBJECT",
1141
+ properties: {
1142
+ speakers: {
1143
+ type: "ARRAY",
1144
+ items: {
1145
+ type: "OBJECT",
1146
+ properties: {
1147
+ rawLabels: { type: "ARRAY", items: { type: "STRING" } },
1148
+ name: { type: "STRING" },
1149
+ description: { type: "STRING" }
1150
+ },
1151
+ required: ["rawLabels", "name"]
1152
+ }
1153
+ }
1154
+ },
1155
+ required: ["speakers"]
1156
+ };
1157
+ function buildVoiceHint(dist) {
1158
+ const lines = [];
1159
+ for (const [label, counts] of Object.entries(dist)) {
1160
+ const sorted = Object.entries(counts).sort((a, b) => b[1] - a[1]);
1161
+ const total = sorted.reduce((s2, [, n]) => s2 + n, 0);
1162
+ if (total === 0) continue;
1163
+ const top = sorted.slice(0, 2).map(([sp, n]) => `${sp}=${Math.round(100 * n / total)}%`).join(", ");
1164
+ lines.push(` "${label}" \u2192 voice ${top}`);
1165
+ }
1166
+ return lines.join("\n");
1167
+ }
1168
+ function exampleTurns(turns, perLabel = 2, maxChars = 200) {
1169
+ const byLabel = /* @__PURE__ */ new Map();
1170
+ for (const t of turns) {
1171
+ const arr = byLabel.get(t.speaker);
1172
+ if (arr) arr.push(t);
1173
+ else byLabel.set(t.speaker, [t]);
1174
+ }
1175
+ const lines = [];
1176
+ for (const [label, ts] of byLabel) {
1177
+ const top = [...ts].sort((a, b) => b.text.length - a.text.length).slice(0, perLabel);
1178
+ lines.push(`Label "${label}" (${ts.length} turns). Examples:`);
1179
+ for (const t of top) {
1180
+ const text = t.text.length > maxChars ? t.text.slice(0, maxChars) + "\u2026" : t.text;
1181
+ lines.push(` - ${text}`);
1182
+ }
1183
+ }
1184
+ return lines.join("\n");
1185
+ }
1186
+ function buildIdentifyPrompt(turns, options) {
1187
+ const labels = [...new Set(turns.map((t) => t.speaker))];
1188
+ const examples = exampleTurns(turns);
1189
+ return `Below is a diarized transcript's speaker labels with example utterances. The labels may be inconsistent: the same person can appear under a provisional label (like "Speaker 1") early on and under their real name later, once it became known. Different people may share a generic label.
1190
+
1191
+ Your job: produce the canonical set of speakers.
1192
+ - Merge labels that refer to the SAME person.
1193
+ - Give each canonical speaker a name if it can be inferred from the transcript (someone introduces themselves, or is addressed by name); otherwise keep a clean generic label like "Speaker 1".
1194
+ - Add a short role/description if evident (e.g. "main presenter", "audience member").
1195
+ - Each canonical speaker must be exactly ONE person. NEVER create a catch-all like "Panel", "Multiple", "Various", or "Mixed". If a raw label seems to cover overlapping/multiple voices, assign it to the single most likely dominant speaker (use the voice analysis below).
1196
+ ${options.instructions ? `- Follow these user instructions for naming/grouping: ${options.instructions}
1197
+ ` : ""}
1198
+ Distinct raw labels: ${labels.map((l) => `"${l}"`).join(", ")}
1199
+
1200
+ ${examples}
1201
+ ${options.asrSpeakerByLabel ? `
1202
+ Voice analysis (a separate diarizer clustered the audio into voices A/B/C\u2026; this is a STRONG signal for merging \u2014 labels sharing the same dominant voice are usually the same person, regardless of what they say):
1203
+ ${buildVoiceHint(options.asrSpeakerByLabel)}
1204
+ ` : ""}
1205
+ Respond with ONLY a JSON object (no prose, no code fence) of this shape:
1206
+ {"speakers":[{"rawLabels":["Speaker 1","Rishi"],"name":"Rishi","description":"main presenter"}, ...]}
1207
+ Every raw label above must appear in exactly one speaker's rawLabels.`;
1208
+ }
1209
+ function parseIdentifyJson(text) {
1210
+ let t = text.trim();
1211
+ t = t.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "");
1212
+ const start = t.indexOf("{");
1213
+ const end = t.lastIndexOf("}");
1214
+ if (start === -1 || end === -1 || end < start) return null;
1215
+ try {
1216
+ const obj = JSON.parse(t.slice(start, end + 1));
1217
+ if (obj && Array.isArray(obj.speakers)) return obj;
1218
+ return null;
1219
+ } catch {
1220
+ return null;
1221
+ }
1222
+ }
1223
+ async function identifySpeakersLLM(gen, turns, options = {}) {
1224
+ const prompt = buildIdentifyPrompt(turns, options);
1225
+ const res = await gen.generate([{ text: prompt }], {
1226
+ model: options.llmModel ?? "gemini-flash-latest",
1227
+ temperature: 0,
1228
+ maxOutputTokens: 16384,
1229
+ thinkingLevel: "MINIMAL",
1230
+ schema: IDENTIFY_SCHEMA,
1231
+ label: "identify"
1232
+ });
1233
+ const parsed = parseIdentifyJson(res.text);
1234
+ const resolvedNames = {};
1235
+ const descriptions = {};
1236
+ if (parsed) {
1237
+ for (const sp of parsed.speakers) {
1238
+ if (!sp.name) continue;
1239
+ for (const raw of sp.rawLabels ?? []) resolvedNames[raw] = sp.name;
1240
+ if (sp.description) descriptions[sp.name] = sp.description;
1241
+ }
1242
+ }
1243
+ return { resolvedNames, descriptions };
1244
+ }
1245
+
1246
+ // src/pipeline.ts
1247
+ var VIDEO_EXT = /* @__PURE__ */ new Set([".mp4", ".mov", ".mkv", ".webm", ".avi", ".m4v"]);
1248
+ async function stage(name, fn) {
1249
+ try {
1250
+ return await fn();
1251
+ } catch (e) {
1252
+ const err = e;
1253
+ if (err?.name === "AbortError") throw err;
1254
+ throw new Error(`[${name}] ${err?.message ?? String(e)}`, { cause: err });
1255
+ }
1256
+ }
1257
+ async function transcribe(input, options = {}) {
1258
+ const {
1259
+ instructions,
1260
+ asr: asrProvider = "assemblyai",
1261
+ llmModel = "gemini-flash-latest",
1262
+ llmThinkingLevel = "MINIMAL",
1263
+ keyframeCount = 8,
1264
+ subSegment = true,
1265
+ identifySpeakers = true,
1266
+ knownSpeakers,
1267
+ cache = true,
1268
+ logLlm = true,
1269
+ onProgress,
1270
+ signal,
1271
+ apiKeys
1272
+ } = options;
1273
+ const progress = (stage2, message, pct) => onProgress?.({ stage: stage2, message, pct });
1274
+ const checkAbort = () => signal?.throwIfAborted();
1275
+ checkAbort();
1276
+ if (!existsSync2(input)) throw new Error(`Input not found: ${input}`);
1277
+ const base = basename2(input, extname2(input));
1278
+ const interDir = options.intermediatesDir ?? join3(dirname3(input), `.offmute_${base}`);
1279
+ const inter = new Intermediates(interDir);
1280
+ const sourceSig = {
1281
+ v: 1,
1282
+ key: mediaKey(input),
1283
+ path: input,
1284
+ model: llmModel,
1285
+ instructions: instructions ?? null,
1286
+ thinkingLevel: llmThinkingLevel,
1287
+ asr: asrProvider,
1288
+ subSegment,
1289
+ identify: identifySpeakers
1290
+ };
1291
+ const prevSig = inter.readJSON("source.json");
1292
+ const effectiveCache = cache && !!prevSig && JSON.stringify(prevSig) === JSON.stringify(sourceSig);
1293
+ if (cache && !effectiveCache && prevSig) {
1294
+ progress("probe", "Input/config changed \u2014 ignoring stale cache");
1295
+ }
1296
+ inter.writeJSON("source.json", sourceSig);
1297
+ progress("probe", `Probing ${basename2(input)}`);
1298
+ const info = await inter.cachedJSON("media-info.json", effectiveCache, () => probeMedia(input));
1299
+ const isVideo = info.hasVideo && VIDEO_EXT.has(extname2(input).toLowerCase());
1300
+ const useVideo = (options.useVideo ?? isVideo) && info.hasVideo;
1301
+ progress("preprocess", "Extracting 16k mono audio");
1302
+ const audioPath = inter.path("audio.mp3");
1303
+ if (!effectiveCache || !existsSync2(audioPath)) {
1304
+ await extractAudio(input, audioPath, { sampleRate: 16e3, channels: 1 });
1305
+ }
1306
+ let keyframePaths = [];
1307
+ if (useVideo && keyframeCount > 0) {
1308
+ progress("preprocess", `Extracting ${keyframeCount} keyframes`);
1309
+ const kfDir = inter.path("keyframes");
1310
+ try {
1311
+ if (!effectiveCache || !existsSync2(kfDir)) {
1312
+ keyframePaths = await extractKeyframes(input, kfDir, {
1313
+ count: keyframeCount,
1314
+ durationSeconds: info.durationSeconds
1315
+ });
1316
+ } else {
1317
+ const { readdirSync } = await import("fs");
1318
+ keyframePaths = readdirSync(kfDir).filter((f) => f.endsWith(".jpg")).sort().map((f) => join3(kfDir, f));
1319
+ }
1320
+ } catch (e) {
1321
+ progress("preprocess", `Skipping keyframes (${e.message.slice(0, 60)})`);
1322
+ keyframePaths = [];
1323
+ }
1324
+ }
1325
+ checkAbort();
1326
+ let asr;
1327
+ if (asrProvider === "assemblyai") {
1328
+ progress("asr", "Transcribing for word-level timing (AssemblyAI)");
1329
+ asr = await inter.cachedJSON(
1330
+ "asr.json",
1331
+ effectiveCache,
1332
+ async () => stage("asr", async () => {
1333
+ const { asr: r } = await transcribeWithAssemblyAI(audioPath, {
1334
+ apiKey: apiKeys?.assemblyai,
1335
+ speakerLabels: true,
1336
+ speechModel: options.asrModel
1337
+ });
1338
+ return r;
1339
+ })
1340
+ );
1341
+ }
1342
+ const gemini = new GeminiClient(apiKeys?.gemini);
1343
+ let llmSeq = 0;
1344
+ gemini.onCall = (rec) => {
1345
+ options.onLlmCall?.(rec);
1346
+ if (logLlm) {
1347
+ const n = String(llmSeq++).padStart(2, "0");
1348
+ const stem = `llm/${n}-${rec.label ?? "call"}`;
1349
+ inter.writeText(`${stem}.prompt.txt`, rec.promptText + (rec.fileParts ? `
1350
+
1351
+ [+${rec.fileParts} file part(s)]` : ""));
1352
+ inter.writeText(`${stem}.response.txt`, rec.responseText || `[error] ${rec.error ?? "unknown"}`);
1353
+ inter.writeJSON(`${stem}.meta.json`, { model: rec.model, label: rec.label, usage: rec.usage, fileParts: rec.fileParts, error: rec.error });
1354
+ }
1355
+ };
1356
+ const { segments, allTurns, voiceDist } = await orchestrateChunks({
1357
+ asr,
1358
+ durationSeconds: info.durationSeconds,
1359
+ instructions,
1360
+ subSegment,
1361
+ maxSinglePassSeconds: (options.maxSinglePassMinutes ?? 35) * 60,
1362
+ chunkSeconds: (options.chunkMinutes ?? 15) * 60,
1363
+ overlapSeconds: (options.chunkOverlapMinutes ?? 2) * 60,
1364
+ signal,
1365
+ onProgress: (msg) => progress("diarize", msg),
1366
+ // Node-specific: extract this chunk's audio, call Gemini, cache + log the raw text.
1367
+ diarizeChunk: ({ chunk, chunked, prompt }) => {
1368
+ const rawName = chunked ? `diarize_chunk_${chunk.index}.txt` : "diarize.txt";
1369
+ const label = chunked ? `diarize-chunk-${chunk.index}` : "diarize";
1370
+ return inter.cachedText(
1371
+ rawName,
1372
+ effectiveCache,
1373
+ () => stage(label, async () => {
1374
+ let chunkAudio = audioPath;
1375
+ if (chunked) {
1376
+ chunkAudio = inter.path(`audio_chunk_${chunk.index}.mp3`);
1377
+ if (!effectiveCache || !existsSync2(chunkAudio)) {
1378
+ await extractAudio(audioPath, chunkAudio, { sampleRate: 16e3, channels: 1, startSeconds: chunk.startSeconds, durationSeconds: chunk.endSeconds - chunk.startSeconds });
1379
+ }
1380
+ }
1381
+ const parts = [{ filePath: chunkAudio }, ...keyframePaths.map((p) => ({ filePath: p })), { text: prompt }];
1382
+ const res = await gemini.generate(parts, {
1383
+ model: llmModel,
1384
+ temperature: 0.2,
1385
+ maxOutputTokens: 65536,
1386
+ thinkingLevel: llmThinkingLevel,
1387
+ systemInstruction: DIARIZATION_SYSTEM,
1388
+ label
1389
+ });
1390
+ inter.writeJSON(`${rawName.replace(/\.txt$/, "")}.meta.json`, { model: res.model, usage: res.usage });
1391
+ if (!res.text.trim()) throw new Error(`Diarization returned empty text${chunked ? ` (chunk ${chunk.index})` : ""}`);
1392
+ return res.text;
1393
+ })
1394
+ );
1395
+ },
1396
+ // Node-specific: save raw→parsed + a running partial transcript (resume/inspect).
1397
+ onChunk: ({ index, chunked, turns: turns2, segmentsSoFar }) => {
1398
+ inter.writeJSON(chunked ? `diarize_chunk_${index}.parsed.json` : "diarize.parsed.json", turns2);
1399
+ inter.writeText(
1400
+ "transcript.partial.srt",
1401
+ formatSrt(segmentsSoFar.map((s2) => ({ start: s2.start, end: s2.end, speaker: s2.speakerLabel, text: s2.text })))
1402
+ );
1403
+ }
1404
+ });
1405
+ const turns = allTurns;
1406
+ checkAbort();
1407
+ let resolvedNames;
1408
+ let descriptions;
1409
+ if (identifySpeakers && turns.length > 0) {
1410
+ progress("identify", "Resolving speaker identities");
1411
+ try {
1412
+ const voiceHint = Object.keys(voiceDist).length ? voiceDist : void 0;
1413
+ const ident = await inter.cachedJSON(
1414
+ "identify.json",
1415
+ effectiveCache,
1416
+ () => identifySpeakersLLM(gemini, turns, { instructions, llmModel, asrSpeakerByLabel: voiceHint })
1417
+ );
1418
+ resolvedNames = ident.resolvedNames;
1419
+ descriptions = ident.descriptions;
1420
+ } catch (e) {
1421
+ progress("identify", `Identify pass failed, using raw labels: ${e.message}`);
1422
+ }
1423
+ }
1424
+ const transcript = buildTranscript(
1425
+ segments,
1426
+ {
1427
+ source: basename2(input),
1428
+ durationSeconds: info.durationSeconds,
1429
+ processedAt: (/* @__PURE__ */ new Date()).toISOString(),
1430
+ asrProvider: asr?.provider,
1431
+ llmModel,
1432
+ userInstructions: instructions,
1433
+ language: asr?.language
1434
+ },
1435
+ { knownSpeakers, resolvedNames, descriptions }
1436
+ );
1437
+ progress("format", "Writing outputs");
1438
+ const srt = toSRT(transcript, { includeSpeaker: true });
1439
+ const markdown = toMarkdown(transcript, { title: base });
1440
+ const json = toJSON(transcript);
1441
+ const text = toText(transcript);
1442
+ inter.writeText("transcript.srt", srt);
1443
+ inter.writeText("transcript.md", markdown);
1444
+ inter.writeText("transcript.json", json);
1445
+ progress("done", `Done \u2014 ${transcript.segments.length} segments, ${transcript.speakers.length} speakers`, 100);
1446
+ return { transcript, srt, markdown, json, text, intermediatesDir: interDir, asr };
1447
+ }
1448
+
1449
+ // src/cli.ts
1450
+ var program = new Command();
1451
+ program.name("offmute-v2").description("Timestamp-correct, diarized meeting transcription (multimodal LLM + ASR)").argument("<input>", "audio or video file").option("-i, --instructions <text>", "instructions to guide diarization/speaker labeling").option("-m, --model <model>", "LLM model", "gemini-flash-latest").option("--asr <provider>", "ASR provider for timing: assemblyai | none", "assemblyai").option("--asr-model <model>", "ASR speech model (provider-specific)").option("--no-video", "ignore video (audio only)").option("--keyframes <n>", "number of keyframes for video context", "8").option("--no-sub-segment", "keep whole speaker turns (don't split into display cues)").option("--no-identify", "skip the speaker-identification/merge pass").option("--thinking-level <level>", "LLM thinking level: MINIMAL|LOW|MEDIUM|HIGH", "MINIMAL").option("-o, --out <dir>", "output directory for transcript files", ".").option("--intermediates-dir <dir>", "directory for intermediate artifacts").option("--no-cache", "ignore cached intermediates").option("-f, --format <fmt>", "output format: srt | md | json | text | all", "all").action(async (input, opts) => {
1452
+ const start = Date.now();
1453
+ const base = basename3(input, extname3(input));
1454
+ const outDir = resolve(opts.out);
1455
+ try {
1456
+ mkdirSync2(outDir, { recursive: true });
1457
+ } catch (e) {
1458
+ console.error(`\u2717 Cannot create output directory ${outDir}: ${e.message}`);
1459
+ process.exit(1);
1460
+ }
1461
+ const intermediatesDir = opts.intermediatesDir ? resolve(opts.intermediatesDir) : join4(outDir, `.offmute_${base}`);
1462
+ let stage2 = "";
1463
+ let msg = "";
1464
+ const elapsed = () => ((Date.now() - start) / 1e3).toFixed(0);
1465
+ const render = () => process.stderr.write(`\r[${elapsed()}s] ${stage2}: ${msg}\x1B[K`);
1466
+ const onProgress = (e) => {
1467
+ if (e.stage !== stage2) {
1468
+ if (stage2) process.stderr.write("\n");
1469
+ stage2 = e.stage;
1470
+ msg = e.message;
1471
+ } else {
1472
+ msg = msg ? `${msg} \xB7 ${e.message}` : e.message;
1473
+ }
1474
+ render();
1475
+ };
1476
+ const ticker = setInterval(render, 1e3);
1477
+ try {
1478
+ const result = await transcribe(resolve(input), {
1479
+ instructions: opts.instructions,
1480
+ llmModel: opts.model,
1481
+ asr: opts.asr,
1482
+ asrModel: opts.asrModel,
1483
+ useVideo: opts.video,
1484
+ keyframeCount: parseInt(opts.keyframes, 10),
1485
+ subSegment: opts.subSegment,
1486
+ identifySpeakers: opts.identify,
1487
+ llmThinkingLevel: opts.thinkingLevel,
1488
+ intermediatesDir,
1489
+ cache: opts.cache,
1490
+ onProgress
1491
+ });
1492
+ clearInterval(ticker);
1493
+ const want = (f) => opts.format === "all" || opts.format === f;
1494
+ const written = [];
1495
+ if (want("srt")) {
1496
+ const p = join4(outDir, `${base}.srt`);
1497
+ writeFileSync2(p, result.srt);
1498
+ written.push(p);
1499
+ }
1500
+ if (want("md")) {
1501
+ const p = join4(outDir, `${base}.md`);
1502
+ writeFileSync2(p, result.markdown);
1503
+ written.push(p);
1504
+ }
1505
+ if (want("json")) {
1506
+ const p = join4(outDir, `${base}.json`);
1507
+ writeFileSync2(p, result.json);
1508
+ written.push(p);
1509
+ }
1510
+ if (want("text")) {
1511
+ const p = join4(outDir, `${base}.txt`);
1512
+ writeFileSync2(p, result.text);
1513
+ written.push(p);
1514
+ }
1515
+ process.stderr.write("\n\n");
1516
+ const { transcript } = result;
1517
+ console.log(`\u2713 ${transcript.segments.length} segments \xB7 ${transcript.speakers.length} speakers \xB7 ${(Date.now() - start) / 1e3 | 0}s`);
1518
+ console.log(` Speakers: ${transcript.speakers.map((s2) => s2.label).join(", ")}`);
1519
+ for (const p of written) console.log(` \u2192 ${p}`);
1520
+ console.log(` Intermediates: ${result.intermediatesDir}`);
1521
+ } catch (err) {
1522
+ clearInterval(ticker);
1523
+ process.stderr.write("\n");
1524
+ console.error(`\u2717 ${err.message}`);
1525
+ process.exit(1);
1526
+ }
1527
+ });
1528
+ program.parseAsync();
1529
+ //# sourceMappingURL=cli.js.map