offmute-v2 0.0.5 → 0.1.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 CHANGED
@@ -2,12 +2,12 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { Command } from "commander";
5
- import { readFileSync as readFileSync2 } from "fs";
5
+ import { readFileSync as readFileSync6 } from "fs";
6
6
  import { fileURLToPath } from "url";
7
- import { dirname as dirname4, join } from "path";
7
+ import { dirname as dirname5, join as join5, basename as basename6, resolve as resolve4 } from "path";
8
8
 
9
9
  // src/core/pipeline.ts
10
- import { existsSync as existsSync2, mkdirSync, readFileSync, writeFileSync } from "fs";
10
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
11
11
 
12
12
  // src/core/config.ts
13
13
  import { createHash } from "crypto";
@@ -45,20 +45,23 @@ function resolveKeys(injected) {
45
45
  deepseek: injected?.deepseek || env.DEEPSEEK_API_KEY,
46
46
  groq: injected?.groq || env.GROQ_API_KEY,
47
47
  assemblyai: injected?.assemblyai || env.ASSEMBLYAI_API_KEY,
48
- anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY
48
+ anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY,
49
+ zai: injected?.zai || env.ZAI_API_KEY || env.GLM_API_KEY,
50
+ kimi: injected?.kimi || env.KIMI_API_KEY || env.MOONSHOT_API_KEY,
51
+ elevenlabs: injected?.elevenlabs || env.ELEVENLABS_API_KEY
49
52
  };
50
53
  }
51
- function resolveOptions(opts2) {
54
+ function resolveOptions(opts) {
52
55
  return {
53
- input: opts2.input,
56
+ input: opts.input,
54
57
  // Default: write next to the input file (e.g. meeting.md beside meeting.mp4) — no ./output folder.
55
- outputDir: opts2.outputDir ?? dirname(resolve(opts2.input)),
56
- intermediatesDir: opts2.intermediatesDir ?? deriveIntermediatesDir(opts2.input),
57
- instructions: opts2.instructions,
58
- knownSpeakers: opts2.knownSpeakers,
58
+ outputDir: opts.outputDir ?? dirname(resolve(opts.input)),
59
+ intermediatesDir: opts.intermediatesDir ?? deriveIntermediatesDir(opts.input),
60
+ instructions: opts.instructions,
61
+ knownSpeakers: opts.knownSpeakers,
59
62
  passes: (() => {
60
- const p = opts2.passes ?? DEFAULT_PASSES;
61
- if ((opts2.diarizationLevel ?? 2) >= 3 && !p.includes("identify")) {
63
+ const p = opts.passes ?? DEFAULT_PASSES;
64
+ if ((opts.diarizationLevel ?? 3) >= 3 && !p.includes("identify")) {
62
65
  const out = [...p];
63
66
  const fi = out.indexOf("finalize");
64
67
  if (fi >= 0) out.splice(fi, 0, "identify");
@@ -67,44 +70,51 @@ function resolveOptions(opts2) {
67
70
  }
68
71
  return p;
69
72
  })(),
70
- chunkDurationSec: opts2.chunkDurationSec ?? 600,
71
- chunkOverlapSec: opts2.chunkOverlapSec ?? 60,
72
- screenshotCount: opts2.screenshotCount ?? 6,
73
- concurrency: opts2.concurrency ?? 4,
74
- saveIntermediates: opts2.saveIntermediates ?? true,
75
- formats: opts2.formats ?? ["md"],
76
- diarizationLevel: opts2.diarizationLevel ?? 2,
77
- apiKeys: opts2.apiKeys,
78
- model: opts2.model,
79
- reasoner: opts2.reasoner,
80
- timestampedProvider: opts2.timestampedProvider,
81
- force: opts2.force ?? false,
82
- onlyChunk: opts2.onlyChunk,
83
- showProgress: opts2.showProgress ?? true,
84
- llmLog: opts2.llmLog ?? true,
85
- logLevel: opts2.logLevel ?? "info"
73
+ chunkDurationSec: opts.chunkDurationSec ?? 600,
74
+ chunkOverlapSec: opts.chunkOverlapSec ?? 60,
75
+ screenshotCount: opts.screenshotCount ?? 6,
76
+ concurrency: opts.concurrency ?? 4,
77
+ saveIntermediates: opts.saveIntermediates ?? true,
78
+ formats: opts.formats ?? ["md"],
79
+ mdStyle: opts.mdStyle ?? "merged",
80
+ summary: opts.summary ?? false,
81
+ // Level 3 is the default: display names must come from the VERIFIED identify pass.
82
+ // (A describe-pass roster once bound names to the wrong voices and level 2 shipped
83
+ // them unchecked — the Jay-call flip. Level 2 now shows honest Speaker A/B labels.)
84
+ diarizationLevel: opts.diarizationLevel ?? 3,
85
+ identifyMode: opts.identifyMode ?? "dual",
86
+ apiKeys: opts.apiKeys,
87
+ model: opts.model,
88
+ reasoner: opts.reasoner,
89
+ timestampedProvider: opts.timestampedProvider,
90
+ force: opts.force ?? false,
91
+ onlyChunk: opts.onlyChunk,
92
+ showProgress: opts.showProgress ?? true,
93
+ llmLog: opts.llmLog ?? true,
94
+ logLevel: opts.logLevel ?? "info",
95
+ signal: opts.signal
86
96
  };
87
97
  }
88
- function deriveIntermediatesDir(input2) {
89
- const abs = resolve(input2);
98
+ function deriveIntermediatesDir(input) {
99
+ const abs = resolve(input);
90
100
  const hash = createHash("sha1").update(abs).digest("hex").slice(0, 8);
91
- const base = basename(input2, extOf(input2)) || "input";
101
+ const base = basename(input, extOf(input)) || "input";
92
102
  return `${tmpdir()}/offmute-v2-${base}-${hash}`;
93
103
  }
94
104
  function extOf(p) {
95
105
  const i = p.lastIndexOf(".");
96
106
  return i >= 0 ? p.slice(i) : "";
97
107
  }
98
- function inputSignature(input2) {
108
+ function inputSignature(input) {
99
109
  let size = 0;
100
110
  let mtime = 0;
101
111
  try {
102
- const st = statSync(input2);
112
+ const st = statSync(input);
103
113
  size = st.size;
104
114
  mtime = Math.floor(st.mtimeMs);
105
115
  } catch {
106
116
  }
107
- return createHash("sha1").update(`${resolve(input2)}|${size}|${mtime}`).digest("hex");
117
+ return createHash("sha1").update(`${resolve(input)}|${size}|${mtime}`).digest("hex");
108
118
  }
109
119
  function configSignature(o) {
110
120
  const relevant = {
@@ -115,7 +125,7 @@ function configSignature(o) {
115
125
  chunkDurationSec: o.chunkDurationSec ?? 600,
116
126
  chunkOverlapSec: o.chunkOverlapSec ?? 60,
117
127
  screenshotCount: o.screenshotCount ?? 6,
118
- diarizationLevel: o.diarizationLevel ?? 2,
128
+ diarizationLevel: o.diarizationLevel ?? 3,
119
129
  timestampedProvider: o.timestampedProvider ?? "assemblyai"
120
130
  };
121
131
  return createHash("sha1").update(JSON.stringify(relevant)).digest("hex");
@@ -150,17 +160,19 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
150
160
  // src/utils/logger.ts
151
161
  var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
152
162
  var currentLevel = "info";
153
- function setLogLevel(level2) {
154
- currentLevel = level2;
163
+ var sink = null;
164
+ function setLogLevel(level) {
165
+ currentLevel = level;
155
166
  }
156
- function log(level2, msg, extra) {
157
- if (LEVELS[level2] < LEVELS[currentLevel]) return;
158
- const ts = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
159
- const prefix = `[${ts}] ${level2.toUpperCase().padEnd(5)}`;
167
+ function log(level, msg, extra) {
168
+ if (LEVELS[level] < LEVELS[currentLevel]) return;
169
+ if (sink && extra === void 0 && sink(level, msg)) return;
170
+ const ts2 = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
171
+ const prefix = `[${ts2}] ${level.toUpperCase().padEnd(5)}`;
160
172
  if (extra !== void 0) {
161
- console[level2 === "error" ? "error" : "log"](prefix, msg, extra);
173
+ console[level === "error" ? "error" : "log"](prefix, msg, extra);
162
174
  } else {
163
- console[level2 === "error" ? "error" : "log"](prefix, msg);
175
+ console[level === "error" ? "error" : "log"](prefix, msg);
164
176
  }
165
177
  }
166
178
  var logger = {
@@ -168,7 +180,10 @@ var logger = {
168
180
  info: (msg, extra) => log("info", msg, extra),
169
181
  warn: (msg, extra) => log("warn", msg, extra),
170
182
  error: (msg, extra) => log("error", msg, extra),
171
- setLevel: setLogLevel
183
+ setLevel: setLogLevel,
184
+ setSink: (s) => {
185
+ sink = s;
186
+ }
172
187
  };
173
188
 
174
189
  // src/audio/ffmpeg.ts
@@ -176,7 +191,7 @@ import { spawn } from "child_process";
176
191
  import { mkdir } from "fs/promises";
177
192
  import { dirname as dirname2 } from "path";
178
193
  function run(cmd, args, _opts = {}) {
179
- return new Promise((resolve3, reject) => {
194
+ return new Promise((resolve5, reject) => {
180
195
  const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
181
196
  let stdout = "";
182
197
  let stderr = "";
@@ -184,7 +199,7 @@ function run(cmd, args, _opts = {}) {
184
199
  child.stderr.on("data", (d) => stderr += d.toString());
185
200
  child.on("error", reject);
186
201
  child.on("close", (code) => {
187
- if (code === 0) resolve3({ stdout, stderr });
202
+ if (code === 0) resolve5({ stdout, stderr });
188
203
  else {
189
204
  const tail = stderr.slice(-800);
190
205
  reject(new Error(`${cmd} exited ${code}: ${tail}`));
@@ -201,7 +216,7 @@ async function checkFfmpeg() {
201
216
  return false;
202
217
  }
203
218
  }
204
- async function probe(input2) {
219
+ async function probe(input) {
205
220
  const { stdout } = await run("ffprobe", [
206
221
  "-v",
207
222
  "error",
@@ -209,7 +224,7 @@ async function probe(input2) {
209
224
  "-show_streams",
210
225
  "-of",
211
226
  "json",
212
- input2
227
+ input
213
228
  ]);
214
229
  const data = JSON.parse(stdout);
215
230
  const streams = data.streams || [];
@@ -228,28 +243,28 @@ async function probe(input2) {
228
243
  sizeBytes: parseInt(data.format?.size || "0", 10) || void 0
229
244
  };
230
245
  }
231
- function audioArgs(opts2) {
232
- const sampleRate = opts2.sampleRate ?? 16e3;
233
- const channels = opts2.channels ?? 1;
234
- const format = opts2.format ?? "flac";
246
+ function audioArgs(opts) {
247
+ const sampleRate = opts.sampleRate ?? 16e3;
248
+ const channels = opts.channels ?? 1;
249
+ const format = opts.format ?? "flac";
235
250
  const common = ["-vn", "-ac", String(channels), "-ar", String(sampleRate)];
236
251
  switch (format) {
237
252
  case "flac":
238
253
  return [...common, "-c:a", "flac"];
239
254
  case "mp3":
240
- return [...common, "-c:a", "libmp3lame", "-b:a", opts2.bitrate ?? "64k"];
255
+ return [...common, "-c:a", "libmp3lame", "-b:a", opts.bitrate ?? "64k"];
241
256
  case "opus":
242
- return [...common, "-c:a", "libopus", "-b:a", opts2.bitrate ?? "48k"];
257
+ return [...common, "-c:a", "libopus", "-b:a", opts.bitrate ?? "48k"];
243
258
  case "wav":
244
259
  return [...common, "-c:a", "pcm_s16le"];
245
260
  }
246
261
  }
247
- async function extractAudio(input2, output, opts2 = {}) {
262
+ async function extractAudio(input, output, opts = {}) {
248
263
  await mkdir(dirname2(output), { recursive: true });
249
- const args = ["-y", "-i", input2, ...audioArgs(opts2), output];
264
+ const args = ["-y", "-i", input, ...audioArgs(opts), output];
250
265
  await run("ffmpeg", args);
251
266
  }
252
- async function extractChunk(input2, output, startSec, endSec, opts2 = {}) {
267
+ async function extractChunk(input, output, startSec, endSec, opts = {}) {
253
268
  await mkdir(dirname2(output), { recursive: true });
254
269
  const duration = Math.max(0, endSec - startSec);
255
270
  const args = [
@@ -257,19 +272,19 @@ async function extractChunk(input2, output, startSec, endSec, opts2 = {}) {
257
272
  "-ss",
258
273
  startSec.toFixed(3),
259
274
  "-i",
260
- input2,
275
+ input,
261
276
  "-t",
262
277
  duration.toFixed(3),
263
- ...audioArgs(opts2),
278
+ ...audioArgs(opts),
264
279
  output
265
280
  ];
266
281
  await run("ffmpeg", args);
267
282
  }
268
- async function getSceneChangeTimes(input2, threshold) {
283
+ async function getSceneChangeTimes(input, threshold) {
269
284
  try {
270
285
  const { stderr } = await run("ffmpeg", [
271
286
  "-i",
272
- input2,
287
+ input,
273
288
  "-vf",
274
289
  `select='gt(scene,${threshold})',showinfo`,
275
290
  "-vsync",
@@ -288,12 +303,12 @@ async function getSceneChangeTimes(input2, threshold) {
288
303
  return [];
289
304
  }
290
305
  }
291
- async function extractKeyframes(input2, outputDir, count, opts2 = {}) {
306
+ async function extractKeyframes(input, outputDir, count, opts = {}) {
292
307
  await mkdir(outputDir, { recursive: true });
293
- const width = opts2.width ?? 1280;
294
- const { duration } = await probe(input2);
308
+ const width = opts.width ?? 1280;
309
+ const { duration } = await probe(input);
295
310
  if (!duration) return [];
296
- const sceneTimes = await getSceneChangeTimes(input2, opts2.sceneThreshold ?? 0.3);
311
+ const sceneTimes = await getSceneChangeTimes(input, opts.sceneThreshold ?? 0.3);
297
312
  const times = [];
298
313
  if (sceneTimes.length >= count) {
299
314
  const step = sceneTimes.length / count;
@@ -320,7 +335,7 @@ async function extractKeyframes(input2, outputDir, count, opts2 = {}) {
320
335
  "-ss",
321
336
  t.toFixed(3),
322
337
  "-i",
323
- input2,
338
+ input,
324
339
  "-frames:v",
325
340
  "1",
326
341
  "-vf",
@@ -333,12 +348,12 @@ async function extractKeyframes(input2, outputDir, count, opts2 = {}) {
333
348
  }
334
349
  return out;
335
350
  }
336
- async function detectSilence(input2, opts2 = {}) {
337
- const noise = opts2.noiseDb ?? -30;
338
- const minDur = opts2.minDuration ?? 0.3;
351
+ async function detectSilence(input, opts = {}) {
352
+ const noise = opts.noiseDb ?? -30;
353
+ const minDur = opts.minDuration ?? 0.3;
339
354
  const { stderr } = await run("ffmpeg", [
340
355
  "-i",
341
- input2,
356
+ input,
342
357
  "-af",
343
358
  `silencedetect=noise=${noise}dB:d=${minDur}`,
344
359
  "-f",
@@ -381,10 +396,35 @@ import { basename as basename2 } from "path";
381
396
  // src/providers/llm-log.ts
382
397
  import { appendFileSync } from "fs";
383
398
  var logPath = null;
399
+ var usageRecords = /* @__PURE__ */ new Map();
384
400
  function setLlmLogPath(path) {
385
401
  logPath = path ?? null;
386
402
  }
403
+ function resetLlmUsage() {
404
+ usageRecords = /* @__PURE__ */ new Map();
405
+ }
406
+ function getLlmUsage() {
407
+ return [...usageRecords.values()];
408
+ }
387
409
  function logLlmCall(entry) {
410
+ try {
411
+ const key = `${entry.model}|${entry.kind ?? ""}`;
412
+ const rec = usageRecords.get(key) ?? {
413
+ provider: entry.provider,
414
+ model: entry.model,
415
+ kind: entry.kind,
416
+ inputTokens: 0,
417
+ outputTokens: 0,
418
+ calls: 0,
419
+ errors: 0
420
+ };
421
+ rec.inputTokens += entry.usage?.inputTokens ?? 0;
422
+ rec.outputTokens += entry.usage?.outputTokens ?? 0;
423
+ rec.calls += 1;
424
+ if (entry.error) rec.errors += 1;
425
+ usageRecords.set(key, rec);
426
+ } catch {
427
+ }
388
428
  if (!logPath) return;
389
429
  try {
390
430
  appendFileSync(logPath, JSON.stringify(entry) + "\n", { encoding: "utf-8" });
@@ -392,7 +432,39 @@ function logLlmCall(entry) {
392
432
  }
393
433
  }
394
434
 
435
+ // src/utils/retry.ts
436
+ var TRANSIENT_RE = /fetch failed|network|ENOTFOUND|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|socket|aborted|HTTP (?:429|5\d\d)|status (?:429|5\d\d)|\b(?:429|500|502|503|504)\b/i;
437
+ function isTransient(err) {
438
+ const msg = err instanceof Error ? `${err.message} ${err.cause ?? ""}` : String(err);
439
+ return TRANSIENT_RE.test(msg);
440
+ }
441
+ async function withRetry(label, fn, opts = {}) {
442
+ const retries = opts.retries ?? 5;
443
+ const base = opts.baseDelayMs ?? 2e3;
444
+ let lastErr;
445
+ for (let attempt = 0; attempt <= retries; attempt++) {
446
+ try {
447
+ return await fn();
448
+ } catch (err) {
449
+ lastErr = err;
450
+ if (attempt === retries || !isTransient(err)) throw err;
451
+ const delay = base * 2 ** attempt * (0.7 + Math.random() * 0.6);
452
+ logger.warn(
453
+ `[${label}] transient failure (${err instanceof Error ? err.message : err}) \u2014 retry ${attempt + 1}/${retries} in ${(delay / 1e3).toFixed(1)}s`
454
+ );
455
+ await new Promise((r) => setTimeout(r, delay));
456
+ }
457
+ }
458
+ throw lastErr;
459
+ }
460
+
395
461
  // src/providers/gemini.ts
462
+ var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
463
+ var originalWarn = console.warn.bind(console);
464
+ console.warn = (...args) => {
465
+ if (typeof args[0] === "string" && args[0].startsWith(SDK_KEY_WARNING)) return;
466
+ originalWarn(...args);
467
+ };
396
468
  var MIME_BY_EXT = {
397
469
  ".flac": "audio/flac",
398
470
  ".mp3": "audio/mp3",
@@ -434,11 +506,16 @@ var GeminiClient = class {
434
506
  constructor(apiKey) {
435
507
  this.ai = new GoogleGenAI({ apiKey });
436
508
  }
437
- /** Upload a file and wait until it's done processing. */
509
+ /** Upload a file and wait until it's done processing. Uploads ride one long HTTP
510
+ * request each — the retry loop in generate() doesn't cover them, and transient
511
+ * "fetch failed" blips here killed live runs, so they get their own retry. */
438
512
  async upload(path, mimeType) {
439
513
  const mt = mimeType || detectMime(path);
440
514
  logger.debug(`[gemini] uploading ${basename2(path)} (${mt})...`);
441
- let file = await this.ai.files.upload({ file: path, config: { mimeType: mt } });
515
+ let file = await withRetry(
516
+ `gemini upload ${basename2(path)}`,
517
+ () => this.ai.files.upload({ file: path, config: { mimeType: mt } })
518
+ );
442
519
  let tries = 0;
443
520
  while (file.state === "PROCESSING" && tries < 120) {
444
521
  await sleep(2e3);
@@ -452,7 +529,7 @@ var GeminiClient = class {
452
529
  return file;
453
530
  }
454
531
  /** Generate content from a prompt + uploaded files. */
455
- async generate(model, prompt, files, opts2 = {}) {
532
+ async generate(model, prompt, files, opts = {}) {
456
533
  const {
457
534
  maxRetries = 3,
458
535
  retryDelayMs = 2e3,
@@ -460,7 +537,7 @@ var GeminiClient = class {
460
537
  maxOutputTokens = 65536,
461
538
  responseSchema,
462
539
  systemInstruction
463
- } = opts2;
540
+ } = opts;
464
541
  const uploaded = [];
465
542
  try {
466
543
  for (const f of files) {
@@ -504,8 +581,8 @@ var GeminiClient = class {
504
581
  ts: new Date(t0).toISOString(),
505
582
  provider: "gemini",
506
583
  model,
507
- kind: opts2.logKind,
508
- chunk: opts2.logChunk,
584
+ kind: opts.logKind,
585
+ chunk: opts.logChunk,
509
586
  prompt,
510
587
  response: text,
511
588
  usage: result.usage,
@@ -517,16 +594,20 @@ var GeminiClient = class {
517
594
  lastError = err instanceof Error ? err.message : String(err);
518
595
  if (config.thinkingConfig && isThinkingConfigError(lastError)) {
519
596
  delete config.thinkingConfig;
520
- logger.warn(`[gemini] model ${model} rejected thinking config \u2014 retrying without it`);
597
+ logger.warn(
598
+ `[gemini] model ${model} rejected thinking config \u2014 retrying without it`
599
+ );
521
600
  continue;
522
601
  }
523
- logger.warn(`[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`);
602
+ logger.warn(
603
+ `[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`
604
+ );
524
605
  logLlmCall({
525
606
  ts: new Date(t0).toISOString(),
526
607
  provider: "gemini",
527
608
  model,
528
- kind: opts2.logKind,
529
- chunk: opts2.logChunk,
609
+ kind: opts.logKind,
610
+ chunk: opts.logChunk,
530
611
  prompt,
531
612
  response: "",
532
613
  durationMs: Date.now() - t0,
@@ -536,15 +617,19 @@ var GeminiClient = class {
536
617
  if (attempt < maxRetries - 1) await sleep(retryDelayMs * (attempt + 1));
537
618
  }
538
619
  }
539
- return { text: "", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, error: lastError };
620
+ return {
621
+ text: "",
622
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
623
+ error: lastError
624
+ };
540
625
  } finally {
541
626
  await this.cleanup(uploaded);
542
627
  }
543
628
  }
544
629
  /** Generate and parse JSON (requires responseSchema in opts). */
545
- async generateJson(model, prompt, files, responseSchema, opts2 = {}) {
630
+ async generateJson(model, prompt, files, responseSchema, opts = {}) {
546
631
  const result = await this.generate(model, prompt, files, {
547
- ...opts2,
632
+ ...opts,
548
633
  responseSchema
549
634
  });
550
635
  if (result.error || !result.text) {
@@ -589,11 +674,11 @@ async function fileHash(path) {
589
674
  var AssemblyAIProvider = class {
590
675
  client;
591
676
  cacheDir;
592
- constructor(opts2) {
593
- this.client = new AssemblyAI({ apiKey: opts2.apiKey });
594
- this.cacheDir = opts2.cacheDir;
595
- this.speechModel = opts2.speechModel ?? "universal";
596
- this.speakersExpected = opts2.speakersExpected;
677
+ constructor(opts) {
678
+ this.client = new AssemblyAI({ apiKey: opts.apiKey });
679
+ this.cacheDir = opts.cacheDir;
680
+ this.speechModel = opts.speechModel ?? "universal";
681
+ this.speakersExpected = opts.speakersExpected;
597
682
  }
598
683
  speechModel;
599
684
  speakersExpected;
@@ -606,7 +691,10 @@ var AssemblyAIProvider = class {
606
691
  return JSON.parse(await readFile(cachePath, "utf-8"));
607
692
  }
608
693
  logger.info(`[assemblyai] uploading ${filePath}...`);
609
- const uploadUrl = await this.client.files.upload(filePath);
694
+ const uploadUrl = await withRetry(
695
+ "assemblyai upload",
696
+ () => this.client.files.upload(filePath)
697
+ );
610
698
  logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
611
699
  const params = {
612
700
  audio: uploadUrl,
@@ -614,7 +702,10 @@ var AssemblyAIProvider = class {
614
702
  speech_model: this.speechModel
615
703
  };
616
704
  if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
617
- const transcript = await this.client.transcripts.transcribe(params);
705
+ const transcript = await withRetry(
706
+ "assemblyai transcribe",
707
+ () => this.client.transcripts.transcribe(params)
708
+ );
618
709
  if (transcript.status === "error") {
619
710
  throw new Error(`AssemblyAI error: ${transcript.error}`);
620
711
  }
@@ -718,9 +809,315 @@ var WhisperGroqClient = class {
718
809
  }
719
810
  };
720
811
 
812
+ // src/providers/elevenlabs.ts
813
+ var MAX_UTTERANCE_GAP_SEC = 1.5;
814
+ var ElevenLabsClient = class {
815
+ constructor(apiKey, baseUrl = "https://api.elevenlabs.io/v1") {
816
+ this.apiKey = apiKey;
817
+ this.baseUrl = baseUrl;
818
+ }
819
+ apiKey;
820
+ baseUrl;
821
+ async transcribe(audio, opts = {}) {
822
+ const model = opts.model ?? "scribe_v2";
823
+ const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
824
+ const form = new FormData();
825
+ form.append("file", blob, "audio.mp3");
826
+ form.append("model_id", model);
827
+ form.append("timestamps_granularity", "word");
828
+ form.append("diarize", "true");
829
+ form.append("tag_audio_events", "false");
830
+ if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
831
+ for (const term of opts.keyterms ?? []) form.append("keyterms", term);
832
+ const data = await withRetry("elevenlabs", async () => {
833
+ const res = await fetch(`${this.baseUrl}/speech-to-text`, {
834
+ method: "POST",
835
+ headers: { "xi-api-key": this.apiKey },
836
+ body: form
837
+ });
838
+ if (!res.ok) {
839
+ const txt = await res.text();
840
+ throw new Error(`ElevenLabs Scribe ${res.status}: ${txt.slice(0, 300)}`);
841
+ }
842
+ return await res.json();
843
+ });
844
+ const words = [];
845
+ for (const w of data.words ?? []) {
846
+ if (w.type !== "word") continue;
847
+ if (w.start === void 0 || w.end === void 0) continue;
848
+ words.push({
849
+ text: w.text.trim(),
850
+ start: w.start,
851
+ end: w.end,
852
+ speaker: w.speaker_id ?? "speaker_0"
853
+ });
854
+ }
855
+ const utterances = [];
856
+ let cur = [];
857
+ const flush = () => {
858
+ if (cur.length === 0) return;
859
+ utterances.push({
860
+ speaker: cur[0].speaker,
861
+ start: cur[0].start,
862
+ end: cur[cur.length - 1].end,
863
+ text: cur.map((w) => w.text).join(" "),
864
+ words: cur.map(({ text, start, end }) => ({ text, start, end }))
865
+ });
866
+ cur = [];
867
+ };
868
+ for (const w of words) {
869
+ const prev = cur[cur.length - 1];
870
+ if (prev && (w.speaker !== prev.speaker || w.start - prev.end > MAX_UTTERANCE_GAP_SEC)) {
871
+ flush();
872
+ }
873
+ cur.push(w);
874
+ }
875
+ flush();
876
+ const speakers = [...new Set(words.map((w) => w.speaker))];
877
+ return {
878
+ utterances,
879
+ words: words.map(({ text, start, end }) => ({ text, start, end })),
880
+ durationSec: data.audio_duration_secs ?? (words.length ? words[words.length - 1].end : 0),
881
+ speakers,
882
+ hasDiarization: true,
883
+ transcriptId: data.transcription_id ?? `elevenlabs-${model}`
884
+ };
885
+ }
886
+ };
887
+
888
+ // src/core/pricing.ts
889
+ var PRICES_AS_OF = "2026-07";
890
+ var MODEL_PRICES = {
891
+ // Gemini (ai.google.dev/gemini-api/docs/pricing, standard tier, <=200k prompts)
892
+ "gemini-3.1-pro-preview": { textIn: 2, out: 12 },
893
+ "gemini-3-pro-preview": { textIn: 2, out: 12 },
894
+ "gemini-3.5-flash": { textIn: 1.5, out: 9 },
895
+ "gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
896
+ "gemini-2.5-pro": { textIn: 1.25, out: 10 },
897
+ "gemini-2.5-flash": { textIn: 0.3, audioIn: 1, out: 2.5 },
898
+ "gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
899
+ // Moving aliases — priced as their current targets.
900
+ "gemini-pro-latest": { textIn: 2, out: 12 },
901
+ "gemini-flash-latest": { textIn: 1.5, out: 9 },
902
+ "gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
903
+ // Text reasoners
904
+ "deepseek-chat": { textIn: 0.28, out: 0.42 },
905
+ "deepseek-reasoner": { textIn: 0.28, out: 0.42 },
906
+ "gpt-4o-mini": { textIn: 0.15, out: 0.6 },
907
+ "glm-4.7": { textIn: 0.6, out: 2.2 }
908
+ };
909
+ var ASR_HOURLY = {
910
+ assemblyai: 0.15,
911
+ // universal-2, diarization included
912
+ elevenlabs: 0.4,
913
+ // scribe v2 (standard tier; business tier is lower)
914
+ "whisper-groq": 0.04,
915
+ // whisper-large-v3-turbo
916
+ none: 0
917
+ };
918
+ var AUDIO_TOKENS_PER_SEC = 32;
919
+ function priceFor(model) {
920
+ if (MODEL_PRICES[model]) return MODEL_PRICES[model];
921
+ const hit = Object.keys(MODEL_PRICES).find((k) => model.startsWith(k));
922
+ return hit ? MODEL_PRICES[hit] : null;
923
+ }
924
+ function asrCost(provider, durationSec) {
925
+ const hourly = ASR_HOURLY[provider];
926
+ if (hourly === void 0) return null;
927
+ return durationSec / 3600 * hourly;
928
+ }
929
+ function estimateRunCost(opts) {
930
+ const lines = [];
931
+ let total = 0;
932
+ let incomplete = false;
933
+ const p = priceFor(opts.model);
934
+ const chunks = Math.max(
935
+ 1,
936
+ Math.ceil((opts.durationSec - opts.overlapSec) / (opts.chunkSec - opts.overlapSec))
937
+ );
938
+ const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
939
+ if (p) {
940
+ const audioTok = billedAudioSec * AUDIO_TOKENS_PER_SEC;
941
+ const promptTok = chunks * 1500;
942
+ const outTok = opts.durationSec / 60 * 150 + 1500;
943
+ const inRate = p.audioIn ?? p.textIn;
944
+ const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
945
+ total += llmUsd;
946
+ lines.push(
947
+ `${opts.model}: ${chunks} chunk${chunks > 1 ? "s" : ""} + describe \u2248 $${llmUsd.toFixed(2)}`
948
+ );
949
+ } else {
950
+ incomplete = true;
951
+ lines.push(`${opts.model}: unpriced`);
952
+ }
953
+ const asr = asrCost(opts.tsProvider, opts.durationSec);
954
+ if (asr !== null && opts.tsProvider !== "none") {
955
+ total += asr;
956
+ lines.push(
957
+ `${opts.tsProvider}: ${(opts.durationSec / 60).toFixed(0)}min \u2248 $${asr.toFixed(2)}`
958
+ );
959
+ }
960
+ if (opts.identify && opts.reasoner) {
961
+ const rp = priceFor(opts.reasoner);
962
+ if (rp) {
963
+ const idUsd = (8e3 * rp.textIn + 1e3 * rp.out) / 1e6;
964
+ total += idUsd;
965
+ lines.push(`${opts.reasoner} (identify) \u2248 $${idUsd.toFixed(3)}`);
966
+ }
967
+ }
968
+ return { totalUsd: total, lines, incomplete };
969
+ }
970
+ function computeReceipt(usage, tsProvider, durationSec) {
971
+ let llmUsd = 0;
972
+ let incomplete = false;
973
+ const lines = [];
974
+ const perModel = {};
975
+ const totals = { calls: 0, inputTokens: 0, outputTokens: 0 };
976
+ const byModel = /* @__PURE__ */ new Map();
977
+ for (const r of usage) {
978
+ totals.calls += r.calls;
979
+ totals.inputTokens += r.inputTokens;
980
+ totals.outputTokens += r.outputTokens;
981
+ const m = byModel.get(r.model) ?? { in: 0, out: 0, calls: 0 };
982
+ m.in += r.inputTokens;
983
+ m.out += r.outputTokens;
984
+ m.calls += r.calls;
985
+ byModel.set(r.model, m);
986
+ }
987
+ for (const [model, m] of byModel) {
988
+ const p = priceFor(model);
989
+ if (!p) {
990
+ incomplete = true;
991
+ lines.push(
992
+ `${model}: ${m.calls} calls \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 unpriced`
993
+ );
994
+ continue;
995
+ }
996
+ const usd = (m.in * (p.audioIn ?? p.textIn) + m.out * p.out) / 1e6;
997
+ llmUsd += usd;
998
+ perModel[model] = usd;
999
+ lines.push(
1000
+ `${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
1001
+ );
1002
+ }
1003
+ const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
1004
+ if (asrUsd !== null && tsProvider !== "none") {
1005
+ perModel[tsProvider] = asrUsd;
1006
+ lines.push(
1007
+ `${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 $${asrUsd.toFixed(2)}`
1008
+ );
1009
+ }
1010
+ return {
1011
+ totalUsd: llmUsd + (asrUsd ?? 0),
1012
+ llmUsd,
1013
+ asrUsd,
1014
+ lines,
1015
+ totals,
1016
+ perModel,
1017
+ incomplete
1018
+ };
1019
+ }
1020
+ function fmtTok(n) {
1021
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
1022
+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
1023
+ return String(n);
1024
+ }
1025
+
1026
+ // src/core/stats.ts
1027
+ import {
1028
+ appendFileSync as appendFileSync2,
1029
+ existsSync as existsSync2,
1030
+ mkdirSync,
1031
+ readFileSync,
1032
+ rmdirSync,
1033
+ writeFileSync
1034
+ } from "fs";
1035
+ import { homedir } from "os";
1036
+ import { join } from "path";
1037
+ function statsDir() {
1038
+ return process.env.OFFMUTE_HOME || join(homedir(), ".offmute");
1039
+ }
1040
+ function statsEnabled() {
1041
+ return !process.env.OFFMUTE_NO_STATS;
1042
+ }
1043
+ var EMPTY = {
1044
+ runs: 0,
1045
+ mediaSeconds: 0,
1046
+ characters: 0,
1047
+ llmCalls: 0,
1048
+ inputTokens: 0,
1049
+ outputTokens: 0,
1050
+ costUsd: 0,
1051
+ costByModel: {},
1052
+ runsByModel: {}
1053
+ };
1054
+ function readStats() {
1055
+ try {
1056
+ const p = join(statsDir(), "stats.json");
1057
+ if (!existsSync2(p)) return { ...EMPTY };
1058
+ return { ...EMPTY, ...JSON.parse(readFileSync(p, "utf-8")) };
1059
+ } catch {
1060
+ return { ...EMPTY };
1061
+ }
1062
+ }
1063
+ function withStatsLock(dir, fn) {
1064
+ const lock = join(dir, ".stats.lock");
1065
+ const deadline = Date.now() + 2e3;
1066
+ for (; ; ) {
1067
+ try {
1068
+ mkdirSync(lock);
1069
+ break;
1070
+ } catch {
1071
+ if (Date.now() > deadline) break;
1072
+ const until = Date.now() + 25;
1073
+ while (Date.now() < until) {
1074
+ }
1075
+ }
1076
+ }
1077
+ try {
1078
+ fn();
1079
+ } finally {
1080
+ try {
1081
+ rmdirSync(lock);
1082
+ } catch {
1083
+ }
1084
+ }
1085
+ }
1086
+ function recordRun(rec, perModelCost) {
1087
+ if (!statsEnabled()) return;
1088
+ try {
1089
+ const dir = statsDir();
1090
+ mkdirSync(dir, { recursive: true });
1091
+ appendFileSync2(join(dir, "history.jsonl"), JSON.stringify(rec) + "\n");
1092
+ withStatsLock(dir, () => {
1093
+ foldIntoAggregates(rec, perModelCost, dir);
1094
+ });
1095
+ } catch {
1096
+ }
1097
+ }
1098
+ function foldIntoAggregates(rec, perModelCost, dir) {
1099
+ const s = readStats();
1100
+ s.runs += 1;
1101
+ s.mediaSeconds += rec.durationSec;
1102
+ s.characters += rec.characters;
1103
+ s.llmCalls += rec.llmCalls;
1104
+ s.inputTokens += rec.inputTokens;
1105
+ s.outputTokens += rec.outputTokens;
1106
+ if (rec.costUsd !== null) s.costUsd += rec.costUsd;
1107
+ for (const [model, usd] of Object.entries(perModelCost)) {
1108
+ s.costByModel[model] = (s.costByModel[model] ?? 0) + usd;
1109
+ }
1110
+ const tModel = rec.models.transcribe;
1111
+ if (tModel) s.runsByModel[tModel] = (s.runsByModel[tModel] ?? 0) + 1;
1112
+ s.firstRun ??= rec.ts;
1113
+ s.lastRun = rec.ts;
1114
+ writeFileSync(join(dir, "stats.json"), JSON.stringify(s, null, 2));
1115
+ }
1116
+
721
1117
  // src/transcribe/describe.ts
722
- function descriptionPrompt(fileName, instructions) {
723
- return `You are listening to a recording to prepare a transcription engine. Describe what you hear${instructions ? ` (note: ${instructions})` : ""}.
1118
+ function descriptionPrompt(fileName, instructions, sampleCount = 1) {
1119
+ const sampleNote = sampleCount > 1 ? `You are given ${sampleCount} audio samples from a longer recording \u2014 taken from the beginning, middle, and end \u2014 plus any keyframes. Speakers may appear in only one sample.` : `You are listening to a recording.`;
1120
+ return `${sampleNote} Your job is to prepare context for a transcription engine. Describe what you hear${instructions ? ` (note: ${instructions})` : ""}.
724
1121
 
725
1122
  Respond in TWO sections, clearly separated by a line containing only "---":
726
1123
 
@@ -730,17 +1127,24 @@ A short paragraph: what kind of recording this is, the setting, the main topics,
730
1127
  ROSTER
731
1128
  A bulleted speaker roster. For each distinct speaker you can identify, give:
732
1129
  - A short label to use consistently (a name/role if you can infer it, e.g. "Presenter (Hrishi)", else "Speaker A").
733
- - A one-line description (voice, role, accent if notable).
1130
+ - A one-line description anchored to the VOICE itself (pitch, pace, accent, audio quality/mic distance) plus role if evident.
734
1131
  List the people you can distinguish. Do not invent names you didn't hear. If only one person speaks, say so.
735
1132
 
1133
+ IMPORTANT \u2014 name-to-voice binding: knowing WHO is present is not the same as knowing WHICH voice is whose. If the voices are similar (same accent, same register) or you are not certain which voice a name belongs to, say so explicitly in the roster (e.g. "one of the two voices \u2014 binding uncertain") instead of asserting it. Never describe a speaker by conversational role alone (e.g. "the primary speaker who drives the conversation") \u2014 that changes call to call and misleads downstream labeling; anchor to the voice.
1134
+
736
1135
  File: ${fileName}`;
737
1136
  }
738
- async function describeMeeting(client, model, files, fileName, instructions) {
739
- const res = await client.generate(model, descriptionPrompt(fileName, instructions), files, {
740
- temperature: 0.2,
741
- maxRetries: 3,
742
- logKind: "describe"
743
- });
1137
+ async function describeMeeting(client, model, files, fileName, instructions, audioSampleCount = 1) {
1138
+ const res = await client.generate(
1139
+ model,
1140
+ descriptionPrompt(fileName, instructions, audioSampleCount),
1141
+ files,
1142
+ {
1143
+ temperature: 0.2,
1144
+ maxRetries: 3,
1145
+ logKind: "describe"
1146
+ }
1147
+ );
744
1148
  const text = res.text || "";
745
1149
  const parts = text.split(/\n---\n|\n\s*---\s*\n/);
746
1150
  const description = parts[0]?.trim() || text.trim();
@@ -757,14 +1161,23 @@ var TRANSCRIPT_SCHEMA = {
757
1161
  items: {
758
1162
  type: "OBJECT",
759
1163
  properties: {
760
- speaker: { type: "STRING", description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc." },
761
- start: { type: "STRING", description: "Relative start time as mm:ss (00:00 = start of this audio chunk)" },
1164
+ speaker: {
1165
+ type: "STRING",
1166
+ description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc."
1167
+ },
1168
+ start: {
1169
+ type: "STRING",
1170
+ description: "Relative start time as mm:ss (00:00 = start of this audio chunk)"
1171
+ },
762
1172
  end: { type: "STRING", description: "Relative end time as mm:ss" },
763
- text: { type: "STRING", description: "Verbatim transcribed words, including fillers and false starts" },
1173
+ text: {
1174
+ type: "STRING",
1175
+ description: "Verbatim transcribed words, including fillers and false starts"
1176
+ },
764
1177
  tone: {
765
1178
  type: "ARRAY",
766
1179
  items: { type: "STRING" },
767
- description: "Tone/behavior tags e.g. hesitant, laughing, contemplating, urgent, sarcastic. Empty array if neutral."
1180
+ description: "Tone tags ONLY when something clearly stands out (laughing, sarcastic, agitated, whispering). Empty array for normal speech \u2014 most segments."
768
1181
  }
769
1182
  },
770
1183
  required: ["speaker", "start", "end", "text"]
@@ -779,19 +1192,40 @@ function transcriptionPrompt(ctx) {
779
1192
  `You are an expert speech transcription engine. Below is audio chunk ${ctx.index} of ${ctx.total} from a recording. Transcribe ALL speech verbatim and diarize it.`
780
1193
  );
781
1194
  parts.push("");
782
- parts.push("Output one segment per speaker turn (a new segment whenever the speaker changes, or after a long pause, or at an interruption).");
1195
+ parts.push(
1196
+ `Start a NEW segment on EVERY voice change \u2014 this is the single most important rule. That includes one-word interjections, backchannels ("yeah", "right", "oh my god"), and replies inside someone else's story. If a different voice says even a single word, it gets its own segment with its own speaker label. Never fold another person's words into the current speaker's segment. Also break on long pauses and interruptions.`
1197
+ );
783
1198
  parts.push("");
784
1199
  parts.push("For each segment provide:");
785
- parts.push("- speaker: a label. Use an identified name/role from the roster if you are confident who is speaking; otherwise use 'Speaker A', 'Speaker B', etc. Keep labels CONSISTENT across the chunk.");
786
- parts.push("- start, end: relative timestamps as mm:ss, where 00:00 is the START of this audio chunk. They must be monotonic and span the full chunk.");
787
- parts.push("- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase.");
788
- parts.push("- tone: array of behavior/emotion tags. Tag most segments \u2014 e.g. confident, hesitant, laughing, sarcastic, urgent, contemplative, whispering, emphatic, questioning, joking, frustrated. Use an empty array ONLY when nothing stands out.");
1200
+ parts.push(
1201
+ "- speaker: a label. Use an identified name/role from the roster if you are confident who is speaking; otherwise use 'Speaker A', 'Speaker B', etc. Keep labels CONSISTENT across the chunk."
1202
+ );
1203
+ parts.push(
1204
+ "- start, end: relative timestamps as mm:ss, where 00:00 is the START of this audio chunk. They must be monotonic and span the full chunk."
1205
+ );
1206
+ parts.push(
1207
+ "- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase."
1208
+ );
1209
+ parts.push(
1210
+ '- tone: tags ONLY when the delivery clearly stands out \u2014 laughing, sarcastic, agitated, whispering, mock-serious, exasperated. Normal conversational speech (even confident/casual/curious speech) gets an EMPTY array. Most segments should have no tone tags; a tag should mean "a reader would want to know this".'
1211
+ );
789
1212
  parts.push("");
790
1213
  parts.push("Rules:");
791
- parts.push("- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing.");
792
- parts.push("- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap.");
793
- parts.push("- Do not invent content not present in the audio. If inaudible, write [inaudible].");
794
- parts.push("- Keep speaker labels consistent within this chunk; the same voice = same label.");
1214
+ parts.push(
1215
+ "- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing."
1216
+ );
1217
+ parts.push(
1218
+ "- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap."
1219
+ );
1220
+ parts.push(
1221
+ "- Listen for voice characteristics (pitch, accent, mic distance), not just content. Two people agreeing with each other are still two segments."
1222
+ );
1223
+ parts.push(
1224
+ "- Do not invent content not present in the audio. If inaudible, write [inaudible]."
1225
+ );
1226
+ parts.push(
1227
+ "- Keep speaker labels consistent within this chunk; the same voice = same label."
1228
+ );
795
1229
  if (ctx.description) {
796
1230
  parts.push("");
797
1231
  parts.push("MEETING CONTEXT:");
@@ -799,12 +1233,20 @@ function transcriptionPrompt(ctx) {
799
1233
  }
800
1234
  if (ctx.roster) {
801
1235
  parts.push("");
802
- parts.push("SPEAKER ROSTER (prefer these labels/names when you can identify the voice):");
1236
+ parts.push(
1237
+ "SPEAKER ROSTER (context about who is present \u2014 but its name-to-voice binding may be wrong):"
1238
+ );
803
1239
  parts.push(ctx.roster);
1240
+ parts.push("");
1241
+ parts.push(
1242
+ "Use a roster name ONLY when the voice itself tells you it's that person (they self-identify, are addressed by name, or the voice description clearly matches). If two speakers sound similar and you are not sure which name belongs to which voice, use 'Speaker A' / 'Speaker B' instead \u2014 a WRONG name is much worse than a generic label; a later pass verifies names."
1243
+ );
804
1244
  }
805
1245
  if (ctx.previousTail) {
806
1246
  parts.push("");
807
- parts.push("TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):");
1247
+ parts.push(
1248
+ "TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
1249
+ );
808
1250
  parts.push(ctx.previousTail);
809
1251
  }
810
1252
  if (ctx.instructions) {
@@ -813,7 +1255,9 @@ function transcriptionPrompt(ctx) {
813
1255
  parts.push(ctx.instructions);
814
1256
  }
815
1257
  parts.push("");
816
- parts.push("Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }");
1258
+ parts.push(
1259
+ "Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }"
1260
+ );
817
1261
  return parts.join("\n");
818
1262
  }
819
1263
 
@@ -838,6 +1282,16 @@ function parseMmSs(timeStr) {
838
1282
  if (seconds < 0 || seconds >= 60) return null;
839
1283
  return minutes * 60 + seconds;
840
1284
  }
1285
+ function formatDuration(seconds) {
1286
+ const hours = Math.floor(seconds / 3600);
1287
+ const minutes = Math.floor(seconds % 3600 / 60);
1288
+ const remaining = Math.floor(seconds % 60);
1289
+ const parts = [];
1290
+ if (hours > 0) parts.push(`${hours}h`);
1291
+ if (minutes > 0) parts.push(`${minutes}m`);
1292
+ parts.push(`${remaining}s`);
1293
+ return parts.join(" ");
1294
+ }
841
1295
 
842
1296
  // src/transcribe/llm-transcribe.ts
843
1297
  var MIN_SEGMENTS = 3;
@@ -861,7 +1315,9 @@ function parseLlmSegments(data, chunkOffsetSec) {
861
1315
  const end = toAbsolute(seg.end, chunkOffsetSec);
862
1316
  if (start === null || end === null || end < start) {
863
1317
  dropped++;
864
- logger.debug(`[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`);
1318
+ logger.debug(
1319
+ `[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`
1320
+ );
865
1321
  continue;
866
1322
  }
867
1323
  out.push({
@@ -878,19 +1334,34 @@ function parseLlmSegments(data, chunkOffsetSec) {
878
1334
  }
879
1335
  function validate(segments, chunkDuration) {
880
1336
  if (segments.length < MIN_SEGMENTS) {
881
- return { isValid: false, spanSec: 0, segmentCount: segments.length, message: `only ${segments.length} segments (min ${MIN_SEGMENTS})` };
1337
+ return {
1338
+ isValid: false,
1339
+ spanSec: 0,
1340
+ segmentCount: segments.length,
1341
+ message: `only ${segments.length} segments (min ${MIN_SEGMENTS})`
1342
+ };
882
1343
  }
883
1344
  const first = segments[0].startSec;
884
1345
  const last = segments[segments.length - 1].endSec;
885
1346
  const span = last - first;
886
1347
  const minSpan = chunkDuration * MIN_SPAN_RATIO;
887
1348
  if (span < minSpan) {
888
- return { isValid: false, spanSec: span, segmentCount: segments.length, message: `span ${span.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)` };
1349
+ return {
1350
+ isValid: false,
1351
+ spanSec: span,
1352
+ segmentCount: segments.length,
1353
+ message: `span ${span.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)`
1354
+ };
889
1355
  }
890
- return { isValid: true, spanSec: span, segmentCount: segments.length, message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)` };
1356
+ return {
1357
+ isValid: true,
1358
+ spanSec: span,
1359
+ segmentCount: segments.length,
1360
+ message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)`
1361
+ };
891
1362
  }
892
- async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts2) {
893
- const validationRetries = opts2.validationRetries ?? 1;
1363
+ async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
1364
+ const validationRetries = opts.validationRetries ?? 1;
894
1365
  const prompt = transcriptionPrompt(ctx);
895
1366
  let lastResult;
896
1367
  for (let attempt = 0; attempt <= validationRetries; attempt++) {
@@ -900,7 +1371,7 @@ async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opt
900
1371
  [{ path: chunkPath }],
901
1372
  TRANSCRIPT_SCHEMA,
902
1373
  {
903
- temperature: opts2.temperature ?? 0.2,
1374
+ temperature: opts.temperature ?? 0.2,
904
1375
  maxRetries: 3,
905
1376
  logKind: "transcribe",
906
1377
  logChunk: ctx.index - 1
@@ -911,22 +1382,35 @@ async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opt
911
1382
  segments: [],
912
1383
  raw: gen.raw,
913
1384
  usage: gen.usage,
914
- validation: { isValid: false, spanSec: 0, segmentCount: 0, message: gen.error || "no data" },
1385
+ validation: {
1386
+ isValid: false,
1387
+ spanSec: 0,
1388
+ segmentCount: 0,
1389
+ message: gen.error || "no data"
1390
+ },
915
1391
  error: gen.error
916
1392
  };
917
- logger.warn(`[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`);
1393
+ logger.warn(
1394
+ `[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
1395
+ );
918
1396
  continue;
919
1397
  }
920
1398
  const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
921
- const v = validate(segments, opts2.chunkDurationSec);
1399
+ const v = validate(segments, opts.chunkDurationSec);
922
1400
  lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
923
1401
  if (v.isValid) {
924
- logger.info(`[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`);
1402
+ logger.info(
1403
+ `[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
1404
+ );
925
1405
  return lastResult;
926
1406
  }
927
- logger.warn(`[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`);
1407
+ logger.warn(
1408
+ `[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
1409
+ );
928
1410
  }
929
- logger.error(`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`);
1411
+ logger.error(
1412
+ `[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
1413
+ );
930
1414
  return lastResult;
931
1415
  }
932
1416
 
@@ -938,8 +1422,8 @@ function tokenize(text) {
938
1422
  const out = [];
939
1423
  for (const raw of text.split(/\s+/)) {
940
1424
  if (!raw) continue;
941
- const norm = normalize(raw);
942
- if (norm) out.push({ original: raw, norm });
1425
+ const norm2 = normalize(raw);
1426
+ if (norm2) out.push({ original: raw, norm: norm2 });
943
1427
  }
944
1428
  return out;
945
1429
  }
@@ -1063,7 +1547,11 @@ function transferTiming(llm, asr, ops) {
1063
1547
  for (const op of ops) {
1064
1548
  if (op.type === "match" || op.type === "substitute") {
1065
1549
  const a = asr[op.asr];
1066
- times[op.llm] = { start: a.start, end: a.end, matched: op.type === "match" && !op.fuzzy };
1550
+ times[op.llm] = {
1551
+ start: a.start,
1552
+ end: a.end,
1553
+ matched: op.type === "match" && !op.fuzzy
1554
+ };
1067
1555
  }
1068
1556
  }
1069
1557
  for (let k = 0; k < times.length; k++) {
@@ -1101,9 +1589,9 @@ function transferTiming(llm, asr, ops) {
1101
1589
  }
1102
1590
  return times;
1103
1591
  }
1104
- function alignSegments(llmSegments, asrWords, opts2 = {}) {
1105
- const confThreshold = opts2.confidenceThreshold ?? 0.5;
1106
- const margin = opts2.timeMarginSec ?? 0;
1592
+ function alignSegments(llmSegments, asrWords, opts = {}) {
1593
+ const confThreshold = opts.confidenceThreshold ?? 0.5;
1594
+ const margin = opts.timeMarginSec ?? 0;
1107
1595
  const sorted = [...llmSegments].map((s, i) => ({ s, i })).sort((a, b) => a.s.startSec - b.s.startSec);
1108
1596
  const flat = [];
1109
1597
  const segRanges = [];
@@ -1232,7 +1720,12 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
1232
1720
  tone: [],
1233
1721
  confidence: 0,
1234
1722
  timingSource: "timestamped",
1235
- words: words.map((w) => ({ text: w.text, start: w.start, end: w.end, matched: true })),
1723
+ words: words.map((w) => ({
1724
+ text: w.text,
1725
+ start: w.start,
1726
+ end: w.end,
1727
+ matched: true
1728
+ })),
1236
1729
  sourceIndex: -1
1237
1730
  });
1238
1731
  }
@@ -1245,10 +1738,21 @@ function overlap(s1, e1, s2, e2) {
1245
1738
  return Math.max(0, Math.min(e1, e2) - Math.max(s1, s2));
1246
1739
  }
1247
1740
  function isGenericLabel(label) {
1248
- return /^(speaker\s+[a-z0-9]+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(label.trim());
1741
+ return /^(speaker\s+[a-z0-9]+|voice\s+\S+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(
1742
+ label.trim()
1743
+ );
1744
+ }
1745
+ function countTurnTransitions(utterances, a, b) {
1746
+ const seq = [...utterances].sort((x, y) => x.start - y.start).map((u) => u.speaker).filter((s) => s === a || s === b);
1747
+ let transitions = 0;
1748
+ for (let i = 1; i < seq.length; i++) {
1749
+ if (seq[i] !== seq[i - 1]) transitions++;
1750
+ }
1751
+ return transitions;
1249
1752
  }
1250
- function assignGlobalSpeakers(segments, asrUtterances, opts2 = {}) {
1251
- const hasDiarization = opts2.hasDiarization ?? true;
1753
+ var MAX_MERGE_TRANSITIONS = 3;
1754
+ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
1755
+ const hasDiarization = opts.hasDiarization ?? true;
1252
1756
  const out = segments.map((seg) => ({ seg, asrSpeaker: "" }));
1253
1757
  const labelVotes = {};
1254
1758
  const asrDuration = {};
@@ -1298,7 +1802,18 @@ function assignGlobalSpeakers(segments, asrUtterances, opts2 = {}) {
1298
1802
  const label = dominantLabel[asrSp] ?? asrSp;
1299
1803
  let groupId;
1300
1804
  if (!isGenericLabel(label)) {
1301
- groupId = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
1805
+ const candidate = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
1806
+ if (candidate && hasDiarization) {
1807
+ const partners = groupAsrVoices[candidate] ?? [];
1808
+ const maxTransitions = Math.max(
1809
+ ...partners.map((p) => countTurnTransitions(asrUtterances, p, asrSp))
1810
+ );
1811
+ if (maxTransitions <= MAX_MERGE_TRANSITIONS) {
1812
+ groupId = candidate;
1813
+ }
1814
+ } else if (candidate) {
1815
+ groupId = candidate;
1816
+ }
1302
1817
  }
1303
1818
  if (!groupId) {
1304
1819
  groupId = asrSp;
@@ -1308,15 +1823,24 @@ function assignGlobalSpeakers(segments, asrUtterances, opts2 = {}) {
1308
1823
  groupTalk[groupId] = (groupTalk[groupId] ?? 0) + (asrDuration[asrSp] ?? 0);
1309
1824
  (groupAsrVoices[groupId] ??= []).push(asrSp);
1310
1825
  }
1311
- const groupsByTalk = Object.keys(groupTalk).sort((a, b) => groupTalk[b] - groupTalk[a]);
1826
+ const groupsByTalk = Object.keys(groupTalk).sort(
1827
+ (a, b) => groupTalk[b] - groupTalk[a]
1828
+ );
1312
1829
  const groupToGlobal = {};
1313
1830
  groupsByTalk.forEach((g, i) => {
1314
1831
  groupToGlobal[g] = `Speaker ${String.fromCharCode(65 + i)}`;
1315
1832
  });
1833
+ const labelGroupCount = {};
1834
+ for (const g of groupsByTalk) {
1835
+ const label = groupLabel[g];
1836
+ if (!isGenericLabel(label))
1837
+ labelGroupCount[label] = (labelGroupCount[label] ?? 0) + 1;
1838
+ }
1316
1839
  const displayNames = {};
1317
1840
  for (const g of groupsByTalk) {
1318
1841
  const label = groupLabel[g];
1319
- displayNames[groupToGlobal[g]] = isGenericLabel(label) ? groupToGlobal[g] : label;
1842
+ const contested = (labelGroupCount[label] ?? 0) > 1;
1843
+ displayNames[groupToGlobal[g]] = isGenericLabel(label) || contested ? groupToGlobal[g] : label;
1320
1844
  }
1321
1845
  const llmLabelToAsr = {};
1322
1846
  for (const o of out) {
@@ -1350,6 +1874,111 @@ function assignGlobalSpeakers(segments, asrUtterances, opts2 = {}) {
1350
1874
  return { segments: updated, speakers, displayNames, llmLabelToAsr };
1351
1875
  }
1352
1876
 
1877
+ // src/diarize/split-mixed.ts
1878
+ var MIN_RUN_WORDS = 5;
1879
+ var MIN_RUN_SEC = 2;
1880
+ function clusterAt(utterances, t) {
1881
+ let best = "";
1882
+ let bestDist = Infinity;
1883
+ for (const u of utterances) {
1884
+ if (t >= u.start && t <= u.end) return u.speaker;
1885
+ const d = t < u.start ? u.start - t : t - u.end;
1886
+ if (d < bestDist) {
1887
+ bestDist = d;
1888
+ best = u.speaker;
1889
+ }
1890
+ }
1891
+ return best;
1892
+ }
1893
+ function buildRuns(words, utterances) {
1894
+ const clusters = words.map(
1895
+ (w) => w.matched ? clusterAt(utterances, (w.start + w.end) / 2) : null
1896
+ );
1897
+ for (let i = 1; i < clusters.length; i++) {
1898
+ if (clusters[i] === null) clusters[i] = clusters[i - 1] ?? null;
1899
+ }
1900
+ for (let i = clusters.length - 2; i >= 0; i--) {
1901
+ if (clusters[i] === null) clusters[i] = clusters[i + 1] ?? null;
1902
+ }
1903
+ const runs = [];
1904
+ for (let i = 0; i < clusters.length; i++) {
1905
+ const c = clusters[i] ?? "";
1906
+ const last = runs[runs.length - 1];
1907
+ if (last && last.cluster === c) last.endIdx = i + 1;
1908
+ else runs.push({ cluster: c, startIdx: i, endIdx: i + 1 });
1909
+ }
1910
+ return runs;
1911
+ }
1912
+ function runSec(run2, words) {
1913
+ return words[run2.endIdx - 1].end - words[run2.startIdx].start;
1914
+ }
1915
+ function foldShortRuns(runs, words) {
1916
+ let out = runs;
1917
+ let changed = true;
1918
+ while (changed && out.length > 1) {
1919
+ changed = false;
1920
+ for (let i = 0; i < out.length; i++) {
1921
+ const r = out[i];
1922
+ const nWords = r.endIdx - r.startIdx;
1923
+ if (nWords >= MIN_RUN_WORDS || runSec(r, words) >= MIN_RUN_SEC) continue;
1924
+ const prev = out[i - 1];
1925
+ const next = out[i + 1];
1926
+ const target = prev && next ? prev.endIdx - prev.startIdx >= next.endIdx - next.startIdx ? prev : next : prev ?? next;
1927
+ if (!target) continue;
1928
+ if (target === prev) prev.endIdx = r.endIdx;
1929
+ else next.startIdx = r.startIdx;
1930
+ out = out.filter((_, j) => j !== i);
1931
+ changed = true;
1932
+ break;
1933
+ }
1934
+ const merged = [];
1935
+ for (const r of out) {
1936
+ const last = merged[merged.length - 1];
1937
+ if (last && last.cluster === r.cluster) last.endIdx = r.endIdx;
1938
+ else merged.push({ ...r });
1939
+ }
1940
+ out = merged;
1941
+ }
1942
+ return out;
1943
+ }
1944
+ function splitMixedVoiceSegments(segments, utterances) {
1945
+ if (utterances.length === 0) return segments;
1946
+ const out = [];
1947
+ let splits = 0;
1948
+ for (const seg of segments) {
1949
+ const matched = seg.words.filter((w) => w.matched).length;
1950
+ if (seg.words.length < MIN_RUN_WORDS * 2 || matched < seg.words.length * 0.4) {
1951
+ out.push(seg);
1952
+ continue;
1953
+ }
1954
+ const runs = foldShortRuns(buildRuns(seg.words, utterances), seg.words);
1955
+ if (runs.length <= 1) {
1956
+ out.push(seg);
1957
+ continue;
1958
+ }
1959
+ splits += runs.length - 1;
1960
+ const lens = runs.map((r) => r.endIdx - r.startIdx);
1961
+ const dominantIdx = lens.indexOf(Math.max(...lens));
1962
+ runs.forEach((run2, ri) => {
1963
+ const words = seg.words.slice(run2.startIdx, run2.endIdx);
1964
+ out.push({
1965
+ ...seg,
1966
+ start: words[0].start,
1967
+ end: words[words.length - 1].end,
1968
+ text: words.map((w) => w.text).join(" "),
1969
+ words,
1970
+ speaker: ri === dominantIdx ? seg.speaker : `Voice ${run2.cluster}`
1971
+ });
1972
+ });
1973
+ }
1974
+ if (splits > 0) {
1975
+ logger.info(
1976
+ `split ${splits} mixed-voice boundary(ies) across ${segments.length} segments`
1977
+ );
1978
+ }
1979
+ return out.sort((a, b) => a.start - b.start);
1980
+ }
1981
+
1353
1982
  // src/providers/openai-compat.ts
1354
1983
  var PROVIDER_BASE = {
1355
1984
  deepseek: "https://api.deepseek.com/v1",
@@ -1371,18 +2000,21 @@ var OpenAICompatClient = class _OpenAICompatClient {
1371
2000
  const base = PROVIDER_BASE[provider] ?? provider;
1372
2001
  return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
1373
2002
  }
1374
- async chat(model, messages, opts2 = {}) {
2003
+ async chat(model, messages, opts = {}) {
1375
2004
  const m = model ?? this.defaultModel;
1376
- const maxRetries = opts2.maxRetries ?? 2;
2005
+ const maxRetries = opts.maxRetries ?? 5;
1377
2006
  const body = {
1378
2007
  model: m,
1379
2008
  messages,
1380
- temperature: opts2.temperature ?? 0.2
2009
+ temperature: opts.temperature ?? 0.2
1381
2010
  };
1382
- if (opts2.maxTokens) body.max_tokens = opts2.maxTokens;
1383
- if (opts2.responseJson) {
2011
+ if (opts.maxTokens) body.max_tokens = opts.maxTokens;
2012
+ if (opts.responseJson) {
1384
2013
  body.response_format = { type: "json_object" };
1385
2014
  }
2015
+ if (this.providerName === "gemini") {
2016
+ body.reasoning_effort = "low";
2017
+ }
1386
2018
  let lastError;
1387
2019
  const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
1388
2020
  for (let attempt = 0; attempt < maxRetries; attempt++) {
@@ -1410,7 +2042,7 @@ var OpenAICompatClient = class _OpenAICompatClient {
1410
2042
  ts: new Date(t0).toISOString(),
1411
2043
  provider: this.providerName,
1412
2044
  model: m,
1413
- kind: opts2.logKind,
2045
+ kind: opts.logKind,
1414
2046
  prompt: promptStr,
1415
2047
  response: text,
1416
2048
  usage,
@@ -1420,72 +2052,128 @@ var OpenAICompatClient = class _OpenAICompatClient {
1420
2052
  return { text, usage };
1421
2053
  } catch (err) {
1422
2054
  lastError = err instanceof Error ? err.message : String(err);
2055
+ if (body.response_format && /response_format/i.test(lastError)) {
2056
+ delete body.response_format;
2057
+ continue;
2058
+ }
2059
+ if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
2060
+ delete body.reasoning_effort;
2061
+ continue;
2062
+ }
1423
2063
  logLlmCall({
1424
2064
  ts: new Date(t0).toISOString(),
1425
2065
  provider: this.providerName,
1426
2066
  model: m,
1427
- kind: opts2.logKind,
2067
+ kind: opts.logKind,
1428
2068
  prompt: promptStr,
1429
2069
  response: "",
1430
2070
  durationMs: Date.now() - t0,
1431
2071
  attempt: attempt + 1,
1432
2072
  error: lastError
1433
2073
  });
1434
- if (attempt < maxRetries - 1) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
2074
+ if (attempt < maxRetries - 1)
2075
+ await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
1435
2076
  }
1436
2077
  }
1437
2078
  return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
1438
2079
  }
1439
- async chatJson(model, messages, opts2 = {}) {
1440
- const res = await this.chat(model, messages, { ...opts2, responseJson: true });
1441
- if (res.error || !res.text) return { data: null, raw: res.text, error: res.error };
1442
- try {
1443
- let txt = res.text.trim();
1444
- const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
1445
- if (fence && fence[1]) txt = fence[1];
1446
- return { data: JSON.parse(txt), raw: res.text };
1447
- } catch (err) {
1448
- return { data: null, raw: res.text, error: `JSON parse: ${err instanceof Error ? err.message : String(err)}` };
2080
+ async chatJson(model, messages, opts = {}) {
2081
+ let lastRaw = "";
2082
+ let lastError;
2083
+ for (let attempt = 0; attempt < 2; attempt++) {
2084
+ const res = await this.chat(model, messages, { ...opts, responseJson: true });
2085
+ lastRaw = res.text;
2086
+ lastError = res.error;
2087
+ if (res.error || !res.text) continue;
2088
+ try {
2089
+ let txt = res.text.trim();
2090
+ const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
2091
+ if (fence && fence[1]) txt = fence[1];
2092
+ return { data: JSON.parse(txt), raw: res.text };
2093
+ } catch (err) {
2094
+ lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
2095
+ }
1449
2096
  }
2097
+ return { data: null, raw: lastRaw, error: lastError };
1450
2098
  }
1451
2099
  };
1452
2100
 
1453
2101
  // src/diarize/identify.ts
2102
+ var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
1454
2103
  function buildTranscriptExcerpt(segments, speakers) {
2104
+ const speakerHeader = (sp) => {
2105
+ const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
2106
+ return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
2107
+ };
2108
+ const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
2109
+ if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
2110
+ const parts2 = [
2111
+ "SPEAKERS:",
2112
+ ...speakers.map((sp) => `- ${speakerHeader(sp)}`),
2113
+ "",
2114
+ "FULL TRANSCRIPT (in order):"
2115
+ ];
2116
+ for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
2117
+ return parts2.join("\n");
2118
+ }
1455
2119
  const bySpeaker = {};
1456
2120
  for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
1457
2121
  const parts = [];
1458
2122
  for (const sp of speakers) {
1459
2123
  const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
1460
- const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
1461
- parts.push(
1462
- `### ${sp.id} (${sp.name || "unknown"}, ${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s${voices})`
1463
- );
2124
+ parts.push(`### ${speakerHeader(sp)}`);
1464
2125
  for (const s of segs) parts.push(` ${s.text}`);
1465
2126
  }
1466
2127
  return parts.join("\n");
1467
2128
  }
1468
- function identifyPrompt(transcriptExcerpt, roster, knownSpeakers) {
1469
- return `You are identifying speakers in a transcribed recording. Below are the most substantial quotes from each speaker (labeled exactly as shown in the headers, e.g. "Speaker A"), plus a roster description.
2129
+ function identifyPrompt(transcriptExcerpt, roster, knownSpeakers, nameHints, sourceFileName) {
2130
+ const hintBlock = nameHints && Object.keys(nameHints).length ? `
2131
+ TENTATIVE LABELS (from the transcription model \u2014 UNVERIFIED and possibly SWAPPED between speakers; treat as weak hints to confirm or refute, never as ground truth):
2132
+ ${Object.entries(
2133
+ nameHints
2134
+ ).map(([id, n]) => ` ${id} was tentatively called "${n}"`).join("\n")}
2135
+ ` : "";
2136
+ return `You are identifying speakers in a transcribed recording. Below is the diarized transcript (speaker ids like "Speaker A" are stable voice clusters), plus a roster description.
1470
2137
 
1471
2138
  Identify each speaker by name and/or role using content cues: self-introductions ("my name is X"), references to themselves, their role, or context. If you cannot confidently identify a speaker, leave the name empty ("").
1472
2139
 
2140
+ CRITICAL \u2014 direction of address: when a speaker says a name, work out whether they are talking ABOUT themselves or TO someone else. "Thanks, Rishi" or "I'm stealing your update, Rishi" is spoken TO Rishi \u2014 so that speaker is NOT Rishi, and Rishi is one of the OTHER speakers. Only first-person statements ("I'm Rishi", "my name is...") identify the speaker themselves. Misreading address direction is the most common error in this task.
2141
+
2142
+ BEWARE the roster and tentative labels: they describe who is PRESENT, but their name-to-voice binding may be wrong or swapped (this happens when speakers sound similar). Verify every name against first-person evidence in the transcript itself. If the transcript contradicts a tentative label, trust the transcript. If you cannot verify which of two speakers a name belongs to, leave both names empty rather than guess.
2143
+
2144
+ Prefer real human names over screen handles/usernames when both are available for the same person (e.g. a recording named after "Jay" whose call UI shows a handle \u2014 the person is Jay).
2145
+
1473
2146
  ${knownSpeakers && knownSpeakers.length ? `Known possible speakers: ${knownSpeakers.join(", ")}
2147
+ ` : ""}${sourceFileName ? `RECORDING FILENAME (often names participants): ${sourceFileName}
1474
2148
  ` : ""}ROSTER:
1475
2149
  ${roster}
1476
-
1477
- TRANSCRIPT EXCERPTS BY SPEAKER:
2150
+ ${hintBlock}
2151
+ TRANSCRIPT:
1478
2152
  ${transcriptExcerpt}
1479
2153
 
1480
- Respond as JSON: { "speakers": [ { "id": "<exact speaker id from the headers>", "name": "Full Name or Role", "confidence": "high|medium|low", "evidence": "short quote/reason" } ], "reasoning": "one-paragraph summary" }
1481
- Use the EXACT speaker id strings from the headers above (e.g. "Speaker A").`;
2154
+ Respond as JSON: { "speakers": [ { "id": "<exact speaker id from the headers>", "name": "Full Name or Role", "confidence": "high|medium|low", "evidence": "a short quote copied VERBATIM from the transcript above that supports the name" } ], "reasoning": "one-paragraph summary" }
2155
+ Use the EXACT speaker id strings (e.g. "Speaker A"). The evidence field must be an exact quote from the TRANSCRIPT \u2014 never the filename, roster, or your own words; an unverifiable evidence quote disqualifies the name.`;
1482
2156
  }
1483
- async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers) {
2157
+ async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers, nameHints, sourceFileName) {
1484
2158
  const excerpt = buildTranscriptExcerpt(segments, speakers);
1485
2159
  const { data, error } = await client.chatJson(
1486
2160
  model,
1487
- [{ role: "user", content: identifyPrompt(excerpt, roster, knownSpeakers) }],
1488
- { temperature: 0.1, maxTokens: 2e3, logKind: "identify" }
2161
+ [
2162
+ {
2163
+ role: "user",
2164
+ content: identifyPrompt(
2165
+ excerpt,
2166
+ roster,
2167
+ knownSpeakers,
2168
+ nameHints,
2169
+ sourceFileName
2170
+ )
2171
+ }
2172
+ ],
2173
+ // 8000 tokens: verbose models quote long verbatim evidence, and Gemini's compat
2174
+ // endpoint spends part of the budget on thinking — tighter caps truncated
2175
+ // mid-JSON and silently emptied whole identify passes (observed live, twice).
2176
+ { temperature: 0.1, maxTokens: 8e3, logKind: "identify" }
1489
2177
  );
1490
2178
  if (error || !data) {
1491
2179
  return { nameMap: {}, speakers: [], reasoning: error || "no response" };
@@ -1497,40 +2185,491 @@ async function identifySpeakers(client, model, segments, speakers, roster, known
1497
2185
  return { nameMap, speakers: data.speakers || [], reasoning: data.reasoning || "" };
1498
2186
  }
1499
2187
 
1500
- // src/finalize/finalize.ts
1501
- var MIN_DUR = 0.5;
1502
- var MAX_DUR = 7;
1503
- var OVERLAP_GAP = 0.05;
1504
- function textSimilarity(a, b) {
1505
- const ta = new Set(tokenize(a).map((t) => t.norm));
1506
- const tb = new Set(tokenize(b).map((t) => t.norm));
1507
- if (ta.size === 0 && tb.size === 0) return 1;
1508
- if (ta.size === 0 || tb.size === 0) return 0;
1509
- let inter = 0;
1510
- for (const t of ta) if (tb.has(t)) inter++;
1511
- return inter / (ta.size + tb.size - inter);
2188
+ // src/diarize/identify2.ts
2189
+ var norm = (s) => s.toLowerCase().replace(/['’]/g, "").replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
2190
+ function withinOneEdit(a, b) {
2191
+ if (a === b) return true;
2192
+ if (Math.abs(a.length - b.length) > 1) return false;
2193
+ const [s, l] = a.length <= b.length ? [a, b] : [b, a];
2194
+ let i = 0;
2195
+ let j = 0;
2196
+ let edits = 0;
2197
+ while (i < s.length && j < l.length) {
2198
+ if (s[i] === l[j]) {
2199
+ i++;
2200
+ j++;
2201
+ continue;
2202
+ }
2203
+ if (++edits > 1) return false;
2204
+ if (s.length === l.length) i++;
2205
+ j++;
2206
+ }
2207
+ return edits + (l.length - j) <= 1;
1512
2208
  }
1513
- function timeOverlapFrac(a, b) {
1514
- const ov = Math.max(0, Math.min(a.end, b.end) - Math.max(a.start, b.start));
1515
- const shorter = Math.min(a.end - a.start, b.end - b.start);
1516
- return shorter > 0 ? ov / shorter : 0;
2209
+ function tokensMatch(a, b) {
2210
+ if (a === b) return true;
2211
+ return a.length >= 5 && b.length >= 5 && withinOneEdit(a, b);
1517
2212
  }
1518
- function dedupSegments(segments) {
1519
- const sorted = [...segments].sort((a, b) => a.start - b.start);
1520
- const kept = [];
1521
- for (const seg of sorted) {
1522
- const dup = kept.find(
1523
- (k) => k.speaker === seg.speaker && textSimilarity(k.text, seg.text) > 0.7 && timeOverlapFrac(k, seg) > 0.2
1524
- );
1525
- if (dup) {
1526
- if (seg.confidence > dup.confidence) {
1527
- Object.assign(dup, seg);
1528
- }
1529
- continue;
2213
+ function namesMatch(a, b) {
2214
+ const na = norm(a);
2215
+ const nb = norm(b);
2216
+ if (!na || !nb) return false;
2217
+ if (na === nb) return true;
2218
+ const ta = na.split(" ");
2219
+ const tb = nb.split(" ");
2220
+ const [small, big] = ta.length <= tb.length ? [ta, tb] : [tb, ta];
2221
+ return small.every((t) => big.some((u) => tokensMatch(t, u)));
2222
+ }
2223
+ function evidenceInTranscript(evidence, transcript) {
2224
+ if (!evidence) return false;
2225
+ const ne = norm(evidence);
2226
+ if (ne.length < 8) return false;
2227
+ return transcript.includes(ne);
2228
+ }
2229
+ var INTRO_RE = /\b(?:[Mm]y name is|I am|I'm)[,\s]+([A-Z][\p{L}'’-]+(?:\s+[A-Z][\p{L}'’-]+)?)/gu;
2230
+ var INTRO_STOPWORDS = /* @__PURE__ */ new Set([
2231
+ "i",
2232
+ "im",
2233
+ "ive",
2234
+ "id",
2235
+ "ill",
2236
+ "you",
2237
+ "we",
2238
+ "they",
2239
+ "he",
2240
+ "she",
2241
+ "it",
2242
+ "so",
2243
+ "not",
2244
+ "just",
2245
+ "here",
2246
+ "there",
2247
+ "going",
2248
+ "gonna",
2249
+ "really",
2250
+ "very",
2251
+ "also",
2252
+ "still",
2253
+ "sure",
2254
+ "sorry",
2255
+ "happy",
2256
+ "glad",
2257
+ "excited",
2258
+ "curious",
2259
+ "the",
2260
+ "a",
2261
+ "an",
2262
+ "okay",
2263
+ "ok",
2264
+ "now",
2265
+ "like",
2266
+ "actually",
2267
+ "basically",
2268
+ "kind",
2269
+ "sort",
2270
+ "definitely"
2271
+ ]);
2272
+ function findSelfIntroductions(segments) {
2273
+ const out = [];
2274
+ for (const seg of segments) {
2275
+ for (const m of seg.text.matchAll(INTRO_RE)) {
2276
+ const name = m[1].trim();
2277
+ const tokens = name.split(/\s+/).map((t) => t.toLowerCase().replace(/['’]/g, ""));
2278
+ if (tokens.some((t) => INTRO_STOPWORDS.has(t))) continue;
2279
+ if (name.replace(/[^\p{L}]/gu, "").length < 3) continue;
2280
+ out.push({
2281
+ speakerId: seg.speaker,
2282
+ introducedName: name,
2283
+ segmentText: seg.text.slice(0, 160)
2284
+ });
1530
2285
  }
1531
- kept.push(seg);
1532
2286
  }
1533
- return kept;
2287
+ return out;
2288
+ }
2289
+ function pickCompleteName(a, b) {
2290
+ if (!a) return b ?? "";
2291
+ if (!b) return a;
2292
+ return b.trim().split(/\s+/).length > a.trim().split(/\s+/).length ? b.trim() : a.trim();
2293
+ }
2294
+ function adjudicate(speakerId, a, b, transcriptNorm, intro, introCorroborated = false) {
2295
+ const base = {
2296
+ speakerId,
2297
+ nameA: a.name,
2298
+ nameB: b?.name,
2299
+ outcome: "kept-generic"
2300
+ };
2301
+ const aName = a.name?.trim() || void 0;
2302
+ const bName = b?.name?.trim() || void 0;
2303
+ if (b === void 0) {
2304
+ if (!aName) return base;
2305
+ return { ...base, outcome: "a-only", finalName: aName };
2306
+ }
2307
+ if (aName && bName && namesMatch(aName, bName)) {
2308
+ return { ...base, outcome: "agreed", finalName: pickCompleteName(aName, bName) };
2309
+ }
2310
+ if (intro) {
2311
+ if (aName && namesMatch(aName, intro))
2312
+ return { ...base, outcome: "tripwire", finalName: aName, note: `intro "${intro}"` };
2313
+ if (bName && namesMatch(bName, intro))
2314
+ return { ...base, outcome: "tripwire", finalName: bName, note: `intro "${intro}"` };
2315
+ if (introCorroborated) {
2316
+ return {
2317
+ ...base,
2318
+ outcome: "tripwire",
2319
+ finalName: intro,
2320
+ note: `intro "${intro}" corroborated by roster/known speakers`
2321
+ };
2322
+ }
2323
+ }
2324
+ if (aName && !bName) return { ...base, outcome: "a-only", finalName: aName };
2325
+ if (bName && !aName) return { ...base, outcome: "b-only", finalName: bName };
2326
+ const aOk = evidenceInTranscript(a.evidence, transcriptNorm);
2327
+ const bOk = evidenceInTranscript(b.evidence, transcriptNorm);
2328
+ if (aOk && !bOk)
2329
+ return {
2330
+ ...base,
2331
+ outcome: "evidence-break",
2332
+ finalName: aName,
2333
+ note: "B evidence not in transcript"
2334
+ };
2335
+ if (bOk && !aOk)
2336
+ return {
2337
+ ...base,
2338
+ outcome: "evidence-break",
2339
+ finalName: bName,
2340
+ note: "A evidence not in transcript"
2341
+ };
2342
+ return {
2343
+ ...base,
2344
+ outcome: "kept-generic",
2345
+ note: "disagreement unresolved \u2014 not inventing a name"
2346
+ };
2347
+ }
2348
+ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts) {
2349
+ const mode = opts.mode ?? "dual";
2350
+ const runPass = (r) => identifySpeakers(
2351
+ r.client,
2352
+ r.model,
2353
+ segments,
2354
+ speakers,
2355
+ opts.roster,
2356
+ opts.knownSpeakers,
2357
+ opts.nameHints,
2358
+ opts.sourceFileName
2359
+ );
2360
+ const wantB = mode === "dual" && reasonerB !== null;
2361
+ const [resA, resB] = await Promise.all([
2362
+ runPass(reasonerA),
2363
+ wantB ? runPass(reasonerB) : Promise.resolve(void 0)
2364
+ ]);
2365
+ const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
2366
+ if (passFailed(resA) && (!wantB || passFailed(resB))) {
2367
+ logger.warn(
2368
+ `identify: ALL passes failed (${resA.reasoning.slice(0, 80)}) \u2014 speakers left as generic labels. Re-run to retry naming cheaply (everything else is cached).`
2369
+ );
2370
+ }
2371
+ const transcriptNorm = norm(segments.map((s) => s.text).join(" "));
2372
+ const tripwires = findSelfIntroductions(segments);
2373
+ const introBySpeaker = /* @__PURE__ */ new Map();
2374
+ const conflicted = /* @__PURE__ */ new Set();
2375
+ for (const t of tripwires) {
2376
+ const prev = introBySpeaker.get(t.speakerId);
2377
+ if (prev && !namesMatch(prev, t.introducedName)) conflicted.add(t.speakerId);
2378
+ else introBySpeaker.set(t.speakerId, t.introducedName);
2379
+ }
2380
+ for (const id of conflicted) introBySpeaker.delete(id);
2381
+ const byIdA = new Map(resA.speakers.map((s) => [s.id, s]));
2382
+ const byIdB = resB ? new Map(resB.speakers.map((s) => [s.id, s])) : void 0;
2383
+ const decisions = [];
2384
+ const corroborationText = norm(
2385
+ `${opts.roster ?? ""} ${(opts.knownSpeakers ?? []).join(" ")}`
2386
+ );
2387
+ const isCorroborated = (name) => {
2388
+ if (!name) return false;
2389
+ const n = norm(name);
2390
+ return n.length >= 3 && corroborationText.includes(n);
2391
+ };
2392
+ const nameMap = {};
2393
+ for (const sp of speakers) {
2394
+ const a = byIdA.get(sp.id) ?? { name: resA.nameMap[sp.id] };
2395
+ const b = byIdB ? byIdB.get(sp.id) ?? { name: resB.nameMap[sp.id] } : void 0;
2396
+ const intro = introBySpeaker.get(sp.id);
2397
+ const d = adjudicate(
2398
+ sp.id,
2399
+ a ?? {},
2400
+ wantB ? b ?? {} : void 0,
2401
+ transcriptNorm,
2402
+ intro,
2403
+ isCorroborated(intro)
2404
+ );
2405
+ decisions.push(d);
2406
+ if (d.finalName) nameMap[sp.id] = d.finalName;
2407
+ }
2408
+ const STRENGTH = {
2409
+ agreed: 4,
2410
+ tripwire: 3,
2411
+ "evidence-break": 2,
2412
+ "a-only": 1,
2413
+ "b-only": 1,
2414
+ elimination: 1,
2415
+ "conflict-fallback": 0,
2416
+ "kept-generic": 0
2417
+ };
2418
+ const named = decisions.filter((d) => d.finalName);
2419
+ for (let i = 0; i < named.length; i++) {
2420
+ for (let j = i + 1; j < named.length; j++) {
2421
+ const di = named[i];
2422
+ const dj = named[j];
2423
+ if (!di.finalName || !dj.finalName) continue;
2424
+ if (!namesMatch(di.finalName, dj.finalName)) continue;
2425
+ const si = STRENGTH[di.outcome];
2426
+ const sj = STRENGTH[dj.outcome];
2427
+ const losers = si === sj ? [di, dj] : si < sj ? [di] : [dj];
2428
+ for (const loser of losers) {
2429
+ loser.note = `demoted: "${loser.finalName}" also claimed by another speaker with ${si === sj ? "equal" : "stronger"} evidence`;
2430
+ loser.finalName = void 0;
2431
+ loser.outcome = "conflict-fallback";
2432
+ delete nameMap[loser.speakerId];
2433
+ }
2434
+ }
2435
+ }
2436
+ if (opts.knownSpeakers?.length) {
2437
+ const unusedNames = opts.knownSpeakers.filter(
2438
+ (n) => !decisions.some((d) => d.finalName && namesMatch(d.finalName, n))
2439
+ );
2440
+ const unnamed = decisions.filter((d) => !d.finalName);
2441
+ if (unusedNames.length === 1 && unnamed.length === 1) {
2442
+ const d = unnamed[0];
2443
+ d.finalName = unusedNames[0];
2444
+ d.outcome = "elimination";
2445
+ d.note = `only remaining known speaker`;
2446
+ nameMap[d.speakerId] = d.finalName;
2447
+ logger.info(
2448
+ `identify: "${d.speakerId}" \u2192 ${d.finalName} (by elimination from --speakers)`
2449
+ );
2450
+ }
2451
+ }
2452
+ for (const d of decisions) {
2453
+ if (d.outcome === "conflict-fallback") {
2454
+ logger.info(`identify: "${d.speakerId}" kept generic \u2014 ${d.note}`);
2455
+ }
2456
+ if (d.outcome === "kept-generic" && (d.nameA || d.nameB)) {
2457
+ logger.info(
2458
+ `identify: kept "${d.speakerId}" generic \u2014 passes disagreed (${d.nameA ?? "\u2014"} vs ${d.nameB ?? "\u2014"})`
2459
+ );
2460
+ } else if (d.outcome === "tripwire") {
2461
+ logger.info(
2462
+ `identify: "${d.speakerId}" \u2192 ${d.finalName} (self-introduction tripwire)`
2463
+ );
2464
+ }
2465
+ }
2466
+ return {
2467
+ nameMap,
2468
+ decisions,
2469
+ tripwires,
2470
+ passA: { ...resA, model: reasonerA.model },
2471
+ passB: resB ? { ...resB, model: reasonerB.model } : void 0
2472
+ };
2473
+ }
2474
+
2475
+ // src/providers/reasoner.ts
2476
+ var PROVIDERS = {
2477
+ deepseek: { baseUrl: "https://api.deepseek.com/v1", keyName: "deepseek" },
2478
+ openai: { baseUrl: "https://api.openai.com/v1", keyName: "openai" },
2479
+ groq: { baseUrl: "https://api.groq.com/openai/v1", keyName: "groq" },
2480
+ gemini: {
2481
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
2482
+ keyName: "gemini"
2483
+ },
2484
+ zai: { baseUrl: "https://api.z.ai/api/paas/v4", keyName: "zai" },
2485
+ kimi: { baseUrl: "https://api.moonshot.ai/v1", keyName: "kimi" },
2486
+ anthropic: { baseUrl: "https://api.anthropic.com/v1", keyName: "anthropic" }
2487
+ };
2488
+ function inferProvider(model) {
2489
+ const m = model.toLowerCase();
2490
+ if (m.startsWith("deepseek")) return "deepseek";
2491
+ if (m.startsWith("gemini") || m.startsWith("gemma")) return "gemini";
2492
+ if (m.startsWith("glm")) return "zai";
2493
+ if (m.startsWith("kimi") || m.startsWith("moonshot")) return "kimi";
2494
+ if (m.startsWith("claude")) return "anthropic";
2495
+ if (m.startsWith("gpt") || m.startsWith("o1") || m.startsWith("o3") || m.startsWith("o4"))
2496
+ return "openai";
2497
+ if (m.includes("llama") || m.includes("mixtral")) return "groq";
2498
+ return "openai";
2499
+ }
2500
+ function resolveReasonerInfo(spec) {
2501
+ let provider;
2502
+ let model;
2503
+ const colon = spec.indexOf(":");
2504
+ if (colon > 0 && PROVIDERS[spec.slice(0, colon)]) {
2505
+ provider = spec.slice(0, colon);
2506
+ model = spec.slice(colon + 1);
2507
+ } else {
2508
+ model = spec;
2509
+ provider = inferProvider(spec);
2510
+ }
2511
+ const p = PROVIDERS[provider] ?? PROVIDERS.openai;
2512
+ return { provider, model, keyName: p.keyName, baseUrl: p.baseUrl };
2513
+ }
2514
+ function reasonerKey(info, keys) {
2515
+ if (info.keyName === "gemini") return keys.gemini || keys.google;
2516
+ return keys[info.keyName];
2517
+ }
2518
+ function resolveReasoner(spec, keys) {
2519
+ const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
2520
+ (s) => !!s
2521
+ );
2522
+ for (const c of candidates) {
2523
+ const info = resolveReasonerInfo(c);
2524
+ const key = reasonerKey(info, keys);
2525
+ if (key) {
2526
+ return {
2527
+ client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2528
+ info
2529
+ };
2530
+ }
2531
+ }
2532
+ return null;
2533
+ }
2534
+ function resolveSecondReasoner(first, keys) {
2535
+ const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
2536
+ for (const c of candidates) {
2537
+ const info = resolveReasonerInfo(c);
2538
+ if (info.provider === first.provider) continue;
2539
+ const key = reasonerKey(info, keys);
2540
+ if (key) {
2541
+ return {
2542
+ client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2543
+ info
2544
+ };
2545
+ }
2546
+ }
2547
+ return null;
2548
+ }
2549
+ var REASONER_PRESETS = [
2550
+ { model: "deepseek-chat", note: "default \u2014 cheap, strong text reasoner" },
2551
+ { model: "gemini-flash-latest", note: "fallback \u2014 uses the same key as transcription" },
2552
+ { model: "glm-4.7", note: "z.ai" },
2553
+ { model: "kimi-k2-turbo-preview", note: "Moonshot" },
2554
+ { model: "gpt-4o-mini", note: "OpenAI" },
2555
+ { model: "claude-sonnet-4-5", note: "Anthropic (OpenAI-compat endpoint)" }
2556
+ ];
2557
+
2558
+ // src/finalize/finalize.ts
2559
+ var MIN_DUR = 0.5;
2560
+ var MAX_DUR = 7;
2561
+ var OVERLAP_GAP = 0.05;
2562
+ function textSimilarity(a, b) {
2563
+ const ta = new Set(tokenize(a).map((t) => t.norm));
2564
+ const tb = new Set(tokenize(b).map((t) => t.norm));
2565
+ if (ta.size === 0 && tb.size === 0) return 1;
2566
+ if (ta.size === 0 || tb.size === 0) return 0;
2567
+ let inter = 0;
2568
+ for (const t of ta) if (tb.has(t)) inter++;
2569
+ return inter / (ta.size + tb.size - inter);
2570
+ }
2571
+ function timeOverlapFrac(a, b) {
2572
+ const ov = Math.max(0, Math.min(a.end, b.end) - Math.max(a.start, b.start));
2573
+ const shorter = Math.min(a.end - a.start, b.end - b.start);
2574
+ return shorter > 0 ? ov / shorter : 0;
2575
+ }
2576
+ var SEAM_WINDOW = 250;
2577
+ var SEAM_MIN_TOKENS = 6;
2578
+ var SEAM_MIN_SCORE_RATIO = 0.5;
2579
+ function suffixPrefixOverlap(a, b) {
2580
+ const n = a.length;
2581
+ const m = b.length;
2582
+ if (n === 0 || m === 0) return null;
2583
+ const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
2584
+ const origin = Array.from(
2585
+ { length: n + 1 },
2586
+ () => new Array(m + 1).fill(0)
2587
+ );
2588
+ for (let i = 0; i <= n; i++) {
2589
+ dp[i][0] = 0;
2590
+ origin[i][0] = i;
2591
+ }
2592
+ for (let j = 1; j <= m; j++) {
2593
+ dp[0][j] = -j;
2594
+ origin[0][j] = 0;
2595
+ }
2596
+ for (let i = 1; i <= n; i++) {
2597
+ for (let j = 1; j <= m; j++) {
2598
+ const diag = dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 1 : -1);
2599
+ const up = dp[i - 1][j] - 1;
2600
+ const left = dp[i][j - 1] - 1;
2601
+ if (diag >= up && diag >= left) {
2602
+ dp[i][j] = diag;
2603
+ origin[i][j] = origin[i - 1][j - 1];
2604
+ } else if (up >= left) {
2605
+ dp[i][j] = up;
2606
+ origin[i][j] = origin[i - 1][j];
2607
+ } else {
2608
+ dp[i][j] = left;
2609
+ origin[i][j] = origin[i][j - 1];
2610
+ }
2611
+ }
2612
+ }
2613
+ let bestJ = 0;
2614
+ let bestScore = -Infinity;
2615
+ for (let j = 1; j <= m; j++) {
2616
+ if (dp[n][j] > bestScore) {
2617
+ bestScore = dp[n][j];
2618
+ bestJ = j;
2619
+ }
2620
+ }
2621
+ if (bestJ < SEAM_MIN_TOKENS) return null;
2622
+ if (bestScore < bestJ * SEAM_MIN_SCORE_RATIO) return null;
2623
+ return { aStart: origin[n][bestJ], bLen: bestJ };
2624
+ }
2625
+ function trimSeamOverlaps(segments) {
2626
+ const sorted = [...segments].sort((a, b) => a.start - b.start);
2627
+ const lastIdxBySpeaker = /* @__PURE__ */ new Map();
2628
+ const out = [];
2629
+ for (const seg of sorted) {
2630
+ const prevIdx = lastIdxBySpeaker.get(seg.speaker);
2631
+ const prev = prevIdx !== void 0 ? out[prevIdx] : void 0;
2632
+ if (prev && prev.words?.length && seg.words?.length) {
2633
+ const prevWin = Math.min(SEAM_WINDOW, prev.words.length);
2634
+ const prevToks = prev.words.slice(-prevWin).map((w) => tokenize(w.text)[0]?.norm ?? "");
2635
+ const segToks = seg.words.slice(0, SEAM_WINDOW).map((w) => tokenize(w.text)[0]?.norm ?? "");
2636
+ const hit = suffixPrefixOverlap(prevToks, segToks);
2637
+ if (hit) {
2638
+ const trimFrom = prev.words.length - prevWin + hit.aStart;
2639
+ const kept = prev.words.slice(0, trimFrom);
2640
+ if (kept.length === 0) {
2641
+ out[prevIdx] = null;
2642
+ } else {
2643
+ out[prevIdx] = {
2644
+ ...prev,
2645
+ words: kept,
2646
+ end: kept[kept.length - 1].end,
2647
+ text: kept.map((w) => w.text).join(" ")
2648
+ };
2649
+ }
2650
+ }
2651
+ }
2652
+ out.push(seg);
2653
+ lastIdxBySpeaker.set(seg.speaker, out.length - 1);
2654
+ }
2655
+ return out.filter((s) => s !== null);
2656
+ }
2657
+ function dedupSegments(segments) {
2658
+ const sorted = [...segments].sort((a, b) => a.start - b.start);
2659
+ const kept = [];
2660
+ for (const seg of sorted) {
2661
+ const dup = kept.find(
2662
+ (k) => k.speaker === seg.speaker && textSimilarity(k.text, seg.text) > 0.7 && timeOverlapFrac(k, seg) > 0.2
2663
+ );
2664
+ if (dup) {
2665
+ if (seg.confidence > dup.confidence) {
2666
+ Object.assign(dup, seg);
2667
+ }
2668
+ continue;
2669
+ }
2670
+ kept.push(seg);
2671
+ }
2672
+ return kept;
1534
2673
  }
1535
2674
  function fixOverlaps(segments) {
1536
2675
  if (segments.length === 0) return segments;
@@ -1568,9 +2707,9 @@ function clampAndFix(segments) {
1568
2707
  }
1569
2708
  return fixOverlaps(segments);
1570
2709
  }
1571
- function finalizeSegments(segments, opts2 = {}) {
1572
- const minSeg = opts2.minSegmentSec ?? 0.2;
1573
- let deduped = dedupSegments(segments);
2710
+ function finalizeSegments(segments, opts = {}) {
2711
+ const minSeg = opts.minSegmentSec ?? 0.2;
2712
+ let deduped = dedupSegments(trimSeamOverlaps(segments));
1574
2713
  deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
1575
2714
  const out = deduped.map((s, i) => ({
1576
2715
  id: i + 1,
@@ -1592,11 +2731,17 @@ function finalizeSegments(segments, opts2 = {}) {
1592
2731
  // src/finalize/format.ts
1593
2732
  var MAX_CHARS = 84;
1594
2733
  var MAX_BLOCK_SEC = 7;
1595
- function splitIntoBlocks(seg) {
1596
- const words = seg.words && seg.words.length > 0 ? seg.words : null;
1597
- if (!words) {
1598
- return [{ start: seg.start, end: seg.end, text: seg.text }];
1599
- }
2734
+ function compactTime(sec) {
2735
+ const s = Math.max(0, Math.floor(sec));
2736
+ const h = Math.floor(s / 3600);
2737
+ const m = Math.floor(s % 3600 / 60);
2738
+ const r = s % 60;
2739
+ const mm = m.toString().padStart(2, "0");
2740
+ const rr = r.toString().padStart(2, "0");
2741
+ return h > 0 ? `${h}:${mm}:${rr}` : `${mm}:${rr}`;
2742
+ }
2743
+ function splitByWords(seg) {
2744
+ const words = seg.words;
1600
2745
  const blocks = [];
1601
2746
  let curWords = [];
1602
2747
  let curLen = 0;
@@ -1623,64 +2768,287 @@ function splitIntoBlocks(seg) {
1623
2768
  curLen += addLen;
1624
2769
  }
1625
2770
  flush();
2771
+ return blocks;
2772
+ }
2773
+ function splitByChars(seg) {
2774
+ const text = seg.text.trim();
2775
+ if (text.length <= MAX_CHARS) return [{ start: seg.start, end: seg.end, text }];
2776
+ const words = text.split(/\s+/);
2777
+ const lines = [];
2778
+ let cur = "";
2779
+ for (const w of words) {
2780
+ if (cur && cur.length + 1 + w.length > MAX_CHARS) {
2781
+ lines.push(cur);
2782
+ cur = w;
2783
+ } else {
2784
+ cur = cur ? `${cur} ${w}` : w;
2785
+ }
2786
+ }
2787
+ if (cur) lines.push(cur);
2788
+ const total = lines.reduce((n, l) => n + l.length, 0) || 1;
2789
+ const dur = Math.max(0, seg.end - seg.start);
2790
+ const blocks = [];
2791
+ let t = seg.start;
2792
+ for (const line of lines) {
2793
+ const span = line.length / total * dur;
2794
+ blocks.push({ start: t, end: Math.min(seg.end, t + span), text: line });
2795
+ t += span;
2796
+ }
2797
+ return blocks;
2798
+ }
2799
+ function splitIntoBlocks(seg) {
2800
+ const blocks = seg.words && seg.words.length > 0 ? splitByWords(seg) : splitByChars(seg);
1626
2801
  return blocks.length ? blocks : [{ start: seg.start, end: seg.end, text: seg.text }];
1627
2802
  }
1628
- function formatSrt(result, opts2 = {}) {
1629
- const labelSpeakers = opts2.labelSpeakers ?? true;
1630
- const showTone = opts2.showTone ?? true;
2803
+ function formatSrt(result, opts = {}) {
2804
+ const labelSpeakers = opts.labelSpeakers ?? true;
2805
+ const showTone = opts.showTone ?? true;
1631
2806
  let idx = 1;
1632
2807
  const blocks = [];
1633
2808
  for (const seg of result.segments) {
1634
2809
  const tone = showTone && seg.tone && seg.tone.length ? ` (${seg.tone.join(", ")})` : "";
1635
2810
  const speaker = labelSpeakers ? `${seg.speakerName || seg.speaker}: ` : "";
1636
- for (const b of splitIntoBlocks(seg)) {
1637
- blocks.push(`${idx}
2811
+ const segBlocks = splitIntoBlocks(seg);
2812
+ for (let i = 0; i < segBlocks.length; i++) {
2813
+ const b = segBlocks[i];
2814
+ const t = i === 0 ? tone : "";
2815
+ blocks.push(
2816
+ `${idx}
1638
2817
  ${formatSrtTiming(b.start, b.end)}
1639
- ${speaker}${b.text}${tone}
1640
- `);
2818
+ ${speaker}${b.text}${t}
2819
+ `
2820
+ );
1641
2821
  idx++;
1642
2822
  }
1643
2823
  }
1644
2824
  return blocks.join("\n");
1645
2825
  }
1646
- function formatMarkdown(result, opts2 = {}) {
2826
+ function groupBySpeaker(segments) {
2827
+ const groups = [];
2828
+ for (const seg of segments) {
2829
+ const last = groups[groups.length - 1];
2830
+ const key = (s) => s.speakerName || s.speaker;
2831
+ if (last && key(last[0]) === key(seg)) last.push(seg);
2832
+ else groups.push([seg]);
2833
+ }
2834
+ return groups;
2835
+ }
2836
+ function groupText(group, showTone) {
1647
2837
  const parts = [];
1648
- parts.push(`# ${opts2.title || "Transcript"}
1649
- `);
1650
- parts.push(`*Duration: ${Math.round(result.metadata.duration)}s \xB7 Speakers: ${result.speakers.length}*
2838
+ let lastTone = "";
2839
+ for (const s of group) {
2840
+ const toneStr = s.tone && s.tone.length ? s.tone.join(", ") : "";
2841
+ if (showTone && toneStr && toneStr !== lastTone) {
2842
+ parts.push(`*(${toneStr})* ${s.text}`);
2843
+ } else {
2844
+ parts.push(s.text);
2845
+ }
2846
+ lastTone = toneStr;
2847
+ }
2848
+ return parts.join(" ");
2849
+ }
2850
+ function mdHeader(result, opts) {
2851
+ const parts = [];
2852
+ parts.push(`# ${opts.title || "Transcript"}
1651
2853
  `);
2854
+ parts.push(
2855
+ `*Duration: ${formatDuration(result.metadata.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns*
2856
+ `
2857
+ );
1652
2858
  parts.push("\n## Speakers\n");
1653
2859
  for (const s of result.speakers) {
1654
- const talk = s.talkTime ? ` (${Math.round(s.talkTime)}s)` : "";
1655
- parts.push(`- **${s.name || s.id}**${talk}`);
2860
+ const talk = s.talkTime ? ` \u2014 ${formatDuration(Math.round(s.talkTime))}` : "";
2861
+ const desc = s.description ? ` \xB7 ${s.description}` : "";
2862
+ parts.push(`- **${s.name || s.id}**${talk}${desc}`);
1656
2863
  }
1657
2864
  parts.push("\n## Transcript\n");
1658
- for (const seg of result.segments) {
1659
- const mm = Math.floor(seg.start / 60).toString().padStart(2, "0");
1660
- const ss = Math.floor(seg.start % 60).toString().padStart(2, "0");
1661
- const tone = seg.tone && seg.tone.length ? ` *(${seg.tone.join(", ")})*` : "";
1662
- parts.push(`[${mm}:${ss}] **${seg.speakerName || seg.speaker}**${tone}: ${seg.text}
2865
+ return parts;
2866
+ }
2867
+ function formatMarkdown(result, opts = {}) {
2868
+ const showTone = opts.showTone ?? true;
2869
+ const timestamps = opts.timestamps ?? true;
2870
+ const style = opts.mdStyle ?? "merged";
2871
+ const parts = mdHeader(result, opts);
2872
+ const groups = style === "merged" ? groupBySpeaker(result.segments) : result.segments.map((s) => [s]);
2873
+ for (const group of groups) {
2874
+ const first = group[0];
2875
+ const ts2 = timestamps ? `\`[${compactTime(first.start)}]\` ` : "";
2876
+ const name = first.speakerName || first.speaker;
2877
+ parts.push(`${ts2}**${name}:** ${groupText(group, showTone)}
1663
2878
  `);
1664
2879
  }
1665
2880
  return parts.join("\n");
1666
2881
  }
2882
+ function formatText(result, opts = {}) {
2883
+ const timestamps = opts.timestamps ?? true;
2884
+ const showTone = opts.showTone ?? false;
2885
+ const lines = [];
2886
+ for (const group of groupBySpeaker(result.segments)) {
2887
+ const first = group[0];
2888
+ const ts2 = timestamps ? `[${compactTime(first.start)}] ` : "";
2889
+ const name = first.speakerName || first.speaker;
2890
+ const text = group.map(
2891
+ (s) => showTone && s.tone?.length ? `(${s.tone.join(", ")}) ${s.text}` : s.text
2892
+ ).join(" ");
2893
+ lines.push(`${ts2}${name}: ${text}`);
2894
+ }
2895
+ return lines.join("\n\n") + "\n";
2896
+ }
1667
2897
  function formatJson(result) {
1668
2898
  return JSON.stringify(result, null, 2);
1669
2899
  }
1670
2900
 
2901
+ // src/finalize/html.ts
2902
+ var PALETTE = [
2903
+ "#2563eb",
2904
+ "#059669",
2905
+ "#d97706",
2906
+ "#dc2626",
2907
+ "#7c3aed",
2908
+ "#0891b2",
2909
+ "#be185d",
2910
+ "#4d7c0f",
2911
+ "#b45309",
2912
+ "#6d28d9"
2913
+ ];
2914
+ var esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2915
+ function groupBySpeaker2(segments) {
2916
+ const groups = [];
2917
+ for (const seg of segments) {
2918
+ const last = groups[groups.length - 1];
2919
+ const key = (s) => s.speakerName || s.speaker;
2920
+ if (last && key(last[0]) === key(seg)) last.push(seg);
2921
+ else groups.push([seg]);
2922
+ }
2923
+ return groups;
2924
+ }
2925
+ function formatHtml(result, opts = {}) {
2926
+ const title = opts.title || "Transcript";
2927
+ const colorOf = /* @__PURE__ */ new Map();
2928
+ result.speakers.forEach((sp, i) => {
2929
+ colorOf.set(sp.name || sp.id, PALETTE[i % PALETTE.length]);
2930
+ });
2931
+ const color = (name) => colorOf.get(name) ?? "#64748b";
2932
+ const legend = result.speakers.map((sp) => {
2933
+ const name = sp.name || sp.id;
2934
+ const talk = sp.talkTime ? ` \xB7 ${formatDuration(Math.round(sp.talkTime))}` : "";
2935
+ return `<span class="who"><i style="background:${color(name)}"></i>${esc(name)}<small>${talk}</small></span>`;
2936
+ }).join("");
2937
+ const paragraphs = groupBySpeaker2(result.segments).map((group) => {
2938
+ const first = group[0];
2939
+ const name = first.speakerName || first.speaker;
2940
+ let lastTone = "";
2941
+ const body = group.map((s) => {
2942
+ const toneStr = s.tone?.length ? s.tone.join(", ") : "";
2943
+ const badge = toneStr && toneStr !== lastTone ? `<em class="tone">${esc(toneStr)}</em> ` : "";
2944
+ lastTone = toneStr;
2945
+ return `${badge}${esc(s.text)}`;
2946
+ }).join(" ");
2947
+ return `<div class="turn" style="border-color:${color(name)}">
2948
+ <div class="meta"><b style="color:${color(name)}">${esc(name)}</b><time data-t="${compactTime(first.start)}" title="click to copy">${compactTime(first.start)}</time></div>
2949
+ <p>${body}</p>
2950
+ </div>`;
2951
+ }).join("\n");
2952
+ const m = result.metadata;
2953
+ const cost = m.cost ? ` \xB7 ~$${m.cost.actualUsd.toFixed(2)}` : "";
2954
+ const footer = `${esc(m.models.transcribe ?? "")} + ${esc(m.models.timestamped ?? "")}${cost} \xB7 ${new Date(m.processedAt).toLocaleDateString()}`;
2955
+ return `<!doctype html>
2956
+ <html lang="en">
2957
+ <meta charset="utf-8">
2958
+ <meta name="viewport" content="width=device-width,initial-scale=1">
2959
+ <title>${esc(title)}</title>
2960
+ <style>
2961
+ :root{--bg:#ffffff;--fg:#1e293b;--muted:#64748b;--line:#e2e8f0;--chip:#f1f5f9}
2962
+ @media(prefers-color-scheme:dark){:root{--bg:#0f172a;--fg:#e2e8f0;--muted:#94a3b8;--line:#1e293b;--chip:#1e293b}}
2963
+ *{box-sizing:border-box}
2964
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
2965
+ main{max-width:760px;margin:0 auto;padding:2rem 1.25rem 4rem}
2966
+ h1{font-size:1.5rem;margin:0 0 .25rem}
2967
+ .sub{color:var(--muted);font-size:.9rem;margin-bottom:1rem}
2968
+ header.legend{position:sticky;top:0;background:var(--bg);padding:.6rem 0;border-bottom:1px solid var(--line);display:flex;flex-wrap:wrap;gap:.4rem .9rem;z-index:1}
2969
+ .who{display:inline-flex;align-items:center;gap:.4rem;font-size:.85rem}
2970
+ .who i{width:.65rem;height:.65rem;border-radius:50%;display:inline-block}
2971
+ .who small{color:var(--muted)}
2972
+ .turn{border-left:3px solid;padding:.15rem 0 .15rem 1rem;margin:1.1rem 0}
2973
+ .turn .meta{display:flex;align-items:baseline;gap:.6rem;font-size:.85rem}
2974
+ .turn time{color:var(--muted);font-family:ui-monospace,Menlo,monospace;font-size:.78rem;cursor:pointer}
2975
+ .turn time:hover{text-decoration:underline}
2976
+ .turn p{margin:.25rem 0 0}
2977
+ .tone{background:var(--chip);color:var(--muted);border-radius:.5rem;padding:0 .45rem;font-size:.75rem;font-style:italic;white-space:nowrap}
2978
+ footer{margin-top:3rem;color:var(--muted);font-size:.8rem;border-top:1px solid var(--line);padding-top:1rem}
2979
+ </style>
2980
+ <main>
2981
+ <h1>${esc(title)}</h1>
2982
+ <div class="sub">${formatDuration(m.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns</div>
2983
+ <header class="legend">${legend}</header>
2984
+ ${paragraphs}
2985
+ <footer>${footer}</footer>
2986
+ </main>
2987
+ <script>
2988
+ document.querySelectorAll("time").forEach(t=>t.addEventListener("click",()=>{
2989
+ navigator.clipboard&&navigator.clipboard.writeText(t.dataset.t);
2990
+ const o=t.textContent;t.textContent="copied";setTimeout(()=>t.textContent=o,700);
2991
+ }));
2992
+ </script>
2993
+ </html>
2994
+ `;
2995
+ }
2996
+
2997
+ // src/finalize/summary.ts
2998
+ function summaryPrompt(result, instructions) {
2999
+ const lines = result.segments.map((s) => {
3000
+ const name = s.speakerName || s.speaker;
3001
+ return `[${compactTime(s.start)}] ${name}: ${s.text}`;
3002
+ });
3003
+ return `Below is a diarized meeting transcript. Write a summary in clean markdown with these sections (omit a section entirely if there is nothing for it):
3004
+
3005
+ ## TL;DR
3006
+ 2-4 sentences. What was this, what mattered.
3007
+
3008
+ ## Decisions
3009
+ Bullet list of decisions actually made (not topics discussed). Attribute who decided when clear.
3010
+
3011
+ ## Action items
3012
+ Bullet list, "**Owner** \u2014 action" format. Only real commitments, with the timestamp in [mm:ss].
3013
+
3014
+ ## By speaker
3015
+ One short paragraph per speaker: their main points and positions.
3016
+
3017
+ ## Open questions
3018
+ Things raised but not resolved.
3019
+
3020
+ Be specific and quote sparingly. Do not invent content.${instructions ? `
3021
+
3022
+ Additional instructions: ${instructions}` : ""}
3023
+
3024
+ TRANSCRIPT:
3025
+ ${lines.join("\n")}`;
3026
+ }
3027
+ async function summarizeTranscript(client, model, result, instructions) {
3028
+ const res = await client.chat(
3029
+ model,
3030
+ [{ role: "user", content: summaryPrompt(result, instructions) }],
3031
+ { temperature: 0.3, maxTokens: 4e3, logKind: "summary" }
3032
+ );
3033
+ if (res.error || !res.text) {
3034
+ throw new Error(`summary failed: ${res.error || "empty response"}`);
3035
+ }
3036
+ return res.text.trim() + "\n";
3037
+ }
3038
+
1671
3039
  // src/core/pipeline.ts
1672
3040
  import { basename as basename3, resolve as resolve2 } from "path";
1673
3041
  var JSON_OPTS = { encoding: "utf-8" };
1674
3042
  function readJson(p) {
1675
- if (!existsSync2(p)) return null;
3043
+ if (!existsSync3(p)) return null;
1676
3044
  try {
1677
- return JSON.parse(readFileSync(p, JSON_OPTS));
3045
+ return JSON.parse(readFileSync2(p, JSON_OPTS));
1678
3046
  } catch {
1679
3047
  return null;
1680
3048
  }
1681
3049
  }
1682
3050
  function writeJson(p, data) {
1683
- writeFileSync(p, JSON.stringify(data, null, 2), JSON_OPTS);
3051
+ writeFileSync2(p, JSON.stringify(data, null, 2), JSON_OPTS);
1684
3052
  }
1685
3053
  async function mapPool(items, limit, fn) {
1686
3054
  const results = new Array(items.length);
@@ -1695,30 +3063,41 @@ async function mapPool(items, limit, fn) {
1695
3063
  await Promise.all(workers);
1696
3064
  return results;
1697
3065
  }
1698
- function has(passes2, p) {
1699
- return passes2.includes(p);
3066
+ function has(passes, p) {
3067
+ return passes.includes(p);
1700
3068
  }
1701
- async function transcribe(opts2) {
1702
- if (!opts2 || typeof opts2.input !== "string" || opts2.input.length === 0) {
3069
+ function stageTag(name) {
3070
+ return (err) => {
3071
+ const msg = err instanceof Error ? err.message : String(err);
3072
+ if (msg.startsWith(`[${name}]`)) throw err;
3073
+ const e = new Error(`[${name}] ${msg}`);
3074
+ if (err instanceof Error && err.stack) e.stack = err.stack;
3075
+ throw e;
3076
+ };
3077
+ }
3078
+ async function transcribe(opts) {
3079
+ if (!opts || typeof opts.input !== "string" || opts.input.length === 0) {
1703
3080
  throw new Error(
1704
3081
  "transcribe(options): 'input' (path to the audio/video file) is required"
1705
3082
  );
1706
3083
  }
1707
- const options = resolveOptions(opts2);
3084
+ const options = resolveOptions(opts);
1708
3085
  const keys = resolveKeys(options.apiKeys);
1709
3086
  logger.setLevel(options.logLevel);
1710
- if (!existsSync2(options.input)) {
3087
+ if (!existsSync3(options.input)) {
1711
3088
  throw new Error(`Input file not found: ${options.input}`);
1712
3089
  }
1713
- mkdirSync(options.intermediatesDir, { recursive: true });
1714
- mkdirSync(options.outputDir, { recursive: true });
3090
+ mkdirSync2(options.intermediatesDir, { recursive: true });
3091
+ mkdirSync2(options.outputDir, { recursive: true });
1715
3092
  logger.info(
1716
3093
  `intermediates: ${resolve2(options.intermediatesDir)} (file://${resolve2(options.intermediatesDir)})`
1717
3094
  );
1718
3095
  setLlmLogPath(options.llmLog ? `${options.intermediatesDir}/llm-calls.jsonl` : null);
3096
+ resetLlmUsage();
3097
+ const runStartedAt = Date.now();
1719
3098
  const sourcePath = `${options.intermediatesDir}/source.json`;
1720
3099
  const sig = inputSignature(options.input);
1721
- const cfgSig = configSignature(opts2);
3100
+ const cfgSig = configSignature(opts);
1722
3101
  const prevSig = readJson(
1723
3102
  sourcePath
1724
3103
  );
@@ -1740,45 +3119,60 @@ async function transcribe(opts2) {
1740
3119
  config: cfgSig,
1741
3120
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1742
3121
  });
1743
- const passes2 = options.passes;
3122
+ const passes = options.passes;
1744
3123
  const models = {
1745
3124
  transcribe: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
1746
3125
  reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL
1747
3126
  };
3127
+ const checkAbort = () => {
3128
+ options.signal?.throwIfAborted();
3129
+ };
1748
3130
  if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
1749
3131
  if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
1750
3132
  const tsProvider = options.timestampedProvider ?? "assemblyai";
1751
- const willTimestamp = has(passes2, "timestamped") || has(passes2, "align");
3133
+ const willTimestamp = has(passes, "timestamped") || has(passes, "align");
1752
3134
  if (willTimestamp) {
1753
3135
  if (tsProvider === "assemblyai" && !keys.assemblyai) {
1754
3136
  throw new Error(
1755
- "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
3137
+ "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
1756
3138
  );
1757
3139
  }
1758
3140
  if (tsProvider === "whisper-groq" && !keys.groq) {
1759
3141
  throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
1760
3142
  }
3143
+ if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
3144
+ throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3145
+ }
1761
3146
  }
1762
3147
  let probeInfo = null;
1763
3148
  const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
1764
3149
  const audioPath = `${options.intermediatesDir}/audio.mp3`;
1765
3150
  const probePath = `${options.intermediatesDir}/probe.json`;
1766
- if (has(passes2, "preprocess")) {
3151
+ if (has(passes, "preprocess")) {
3152
+ checkAbort();
1767
3153
  logger.info("=== preprocess ===");
1768
3154
  probeInfo = forceAll ? null : readJson(probePath);
1769
3155
  if (!probeInfo) {
1770
- probeInfo = await probe(options.input);
3156
+ probeInfo = await probe(options.input).catch(stageTag("preprocess"));
1771
3157
  writeJson(probePath, probeInfo);
1772
3158
  }
1773
- if (!existsSync2(audioPath) || forceAll) {
3159
+ if (!existsSync3(audioPath) || forceAll) {
1774
3160
  logger.info("extracting audio (mono 16kHz mp3)...");
1775
- await extractAudio(options.input, audioPath, AUDIO_OPTS);
3161
+ await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
3162
+ stageTag("preprocess")
3163
+ );
1776
3164
  }
1777
3165
  if (probeInfo.hasVideo) {
1778
3166
  const kfDir = `${options.intermediatesDir}/keyframes`;
1779
- if (!existsSync2(kfDir) || forceAll) {
3167
+ if (!existsSync3(kfDir) || forceAll) {
1780
3168
  logger.info("extracting keyframes...");
1781
- await extractKeyframes(options.input, kfDir, options.screenshotCount);
3169
+ await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
3170
+ (err) => {
3171
+ logger.warn(
3172
+ `keyframe extraction failed (continuing audio-only): ${err instanceof Error ? err.message : err}`
3173
+ );
3174
+ }
3175
+ );
1782
3176
  }
1783
3177
  }
1784
3178
  } else {
@@ -1786,23 +3180,46 @@ async function transcribe(opts2) {
1786
3180
  }
1787
3181
  if (!probeInfo) throw new Error("probe info missing (run preprocess)");
1788
3182
  const duration = probeInfo.duration;
3183
+ const estimate = estimateRunCost({
3184
+ durationSec: duration,
3185
+ model: models.transcribe,
3186
+ reasoner: models.reasoner,
3187
+ tsProvider,
3188
+ chunkSec: options.chunkDurationSec,
3189
+ overlapSec: options.chunkOverlapSec,
3190
+ identify: options.diarizationLevel >= 3 && has(passes, "identify")
3191
+ });
3192
+ logger.info(
3193
+ `estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
3194
+ );
1789
3195
  let description = null;
1790
- if (has(passes2, "describe")) {
3196
+ if (has(passes, "describe")) {
1791
3197
  const descPath = `${options.intermediatesDir}/description.json`;
1792
3198
  description = forceAll ? null : readJson(descPath);
1793
3199
  if (!description) {
3200
+ checkAbort();
1794
3201
  logger.info("=== describe ===");
1795
3202
  const client = new GeminiClient(keys.gemini);
1796
- const samplePath = `${options.intermediatesDir}/sample.mp3`;
1797
- if (!existsSync2(samplePath) || forceAll) {
1798
- await extractChunk(audioPath, samplePath, 0, Math.min(300, duration), AUDIO_OPTS);
3203
+ const sampleSpans = duration <= 360 ? [[0, duration]] : [
3204
+ [0, 150],
3205
+ [Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
3206
+ [Math.max(0, duration - 120), duration]
3207
+ ];
3208
+ const files = [];
3209
+ for (let i = 0; i < sampleSpans.length; i++) {
3210
+ const [s, e] = sampleSpans[i];
3211
+ const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
3212
+ if (!existsSync3(samplePath) || forceAll) {
3213
+ await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
3214
+ }
3215
+ files.push({ path: samplePath });
1799
3216
  }
1800
- const files = [{ path: samplePath }];
3217
+ const audioSampleCount = files.length;
1801
3218
  const kfDir = `${options.intermediatesDir}/keyframes`;
1802
- if (existsSync2(kfDir)) {
3219
+ if (existsSync3(kfDir)) {
1803
3220
  for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
1804
3221
  const p = `${kfDir}/${f}`;
1805
- if (existsSync2(p)) files.push({ path: p });
3222
+ if (existsSync3(p)) files.push({ path: p });
1806
3223
  }
1807
3224
  }
1808
3225
  description = await describeMeeting(
@@ -1810,15 +3227,16 @@ async function transcribe(opts2) {
1810
3227
  models.transcribe,
1811
3228
  files,
1812
3229
  basename3(options.input),
1813
- options.instructions
1814
- );
3230
+ options.instructions,
3231
+ audioSampleCount
3232
+ ).catch(stageTag("describe"));
1815
3233
  writeJson(descPath, description);
1816
3234
  logger.info(`description: ${description.description.slice(0, 120)}...`);
1817
3235
  }
1818
3236
  } else {
1819
3237
  description = forceAll ? null : readJson(`${options.intermediatesDir}/description.json`);
1820
3238
  }
1821
- const needChunks = has(passes2, "llm-transcribe") || has(passes2, "align") || has(passes2, "consistency");
3239
+ const needChunks = has(passes, "llm-transcribe") || has(passes, "align") || has(passes, "consistency");
1822
3240
  let chunks = [];
1823
3241
  if (needChunks) {
1824
3242
  let silences = [];
@@ -1849,7 +3267,7 @@ async function transcribe(opts2) {
1849
3267
  }))
1850
3268
  });
1851
3269
  let llmChunkResults = [];
1852
- if (has(passes2, "llm-transcribe")) {
3270
+ if (has(passes, "llm-transcribe")) {
1853
3271
  logger.info("=== llm-transcribe ===");
1854
3272
  let runChunks = chunks;
1855
3273
  if (options.onlyChunk !== void 0)
@@ -1859,16 +3277,39 @@ async function transcribe(opts2) {
1859
3277
  );
1860
3278
  const client = new GeminiClient(keys.gemini);
1861
3279
  const llmDir = `${options.intermediatesDir}/llm`;
1862
- mkdirSync(llmDir, { recursive: true });
3280
+ mkdirSync2(llmDir, { recursive: true });
3281
+ const partialPath = `${options.outputDir}/${basename3(options.input, ext(options.input))}.partial.md`;
3282
+ const completed = [];
3283
+ const writePartial = () => {
3284
+ try {
3285
+ const segs = completed.flatMap((r) => r.segments).sort((a, b) => a.startSec - b.startSec);
3286
+ if (segs.length === 0) return;
3287
+ const lines = segs.map((s) => {
3288
+ const mm = Math.floor(s.startSec / 60).toString().padStart(2, "0");
3289
+ const ss = Math.floor(s.startSec % 60).toString().padStart(2, "0");
3290
+ return `[${mm}:${ss}] **${s.speaker}**: ${s.text}`;
3291
+ });
3292
+ writeFileSync2(
3293
+ partialPath,
3294
+ `> Partial transcript (run in progress \u2014 coarse LLM timings, speakers not yet unified)
3295
+
3296
+ ${lines.join("\n\n")}
3297
+ `
3298
+ );
3299
+ } catch {
3300
+ }
3301
+ };
1863
3302
  llmChunkResults = await mapPool(runChunks, options.concurrency, async (chunk) => {
3303
+ checkAbort();
1864
3304
  const parsedPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_parsed.json`;
1865
3305
  const cached = forceAll ? null : readJson(parsedPath);
1866
3306
  if (cached && cached.segments.length > 0) {
1867
3307
  logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
3308
+ completed.push(cached);
1868
3309
  return tagWith(cached, chunk);
1869
3310
  }
1870
3311
  const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
1871
- if (!existsSync2(chunkPath) || forceAll) {
3312
+ if (!existsSync3(chunkPath) || forceAll) {
1872
3313
  await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
1873
3314
  }
1874
3315
  let previousTail;
@@ -1899,10 +3340,12 @@ async function transcribe(opts2) {
1899
3340
  { chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
1900
3341
  );
1901
3342
  writeJson(parsedPath, result2);
1902
- writeFileSync(
3343
+ writeFileSync2(
1903
3344
  `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
1904
3345
  result2.raw
1905
3346
  );
3347
+ completed.push(result2);
3348
+ writePartial();
1906
3349
  return tagWith(result2, chunk);
1907
3350
  });
1908
3351
  const errored = llmChunkResults.filter((r) => r.error);
@@ -1914,7 +3357,7 @@ async function transcribe(opts2) {
1914
3357
  }
1915
3358
  } else {
1916
3359
  const llmDir = `${options.intermediatesDir}/llm`;
1917
- if (!forceAll && existsSync2(llmDir)) {
3360
+ if (!forceAll && existsSync3(llmDir)) {
1918
3361
  const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
1919
3362
  llmChunkResults = files.map((f, i) => {
1920
3363
  const r = readJson(`${llmDir}/${f}`);
@@ -1932,19 +3375,39 @@ async function transcribe(opts2) {
1932
3375
  }
1933
3376
  logger.info(`total LLM segments: ${allLlmSegments.length}`);
1934
3377
  let asrResult = null;
1935
- if (has(passes2, "timestamped") || has(passes2, "align")) {
3378
+ if (has(passes, "timestamped") || has(passes, "align")) {
3379
+ checkAbort();
1936
3380
  const provider = options.timestampedProvider ?? "assemblyai";
1937
3381
  if (provider === "whisper-groq") {
1938
3382
  logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
1939
3383
  if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
1940
- if (!existsSync2(audioPath) || forceAll) {
3384
+ if (!existsSync3(audioPath) || forceAll) {
1941
3385
  await extractAudio(options.input, audioPath, AUDIO_OPTS);
1942
3386
  }
1943
3387
  const { readFile: readFile2 } = await import("fs/promises");
1944
3388
  const buf = await readFile2(audioPath);
1945
3389
  const groq = new WhisperGroqClient(keys.groq);
1946
- asrResult = await groq.transcribe(buf);
3390
+ asrResult = await groq.transcribe(buf).catch(stageTag("asr"));
1947
3391
  writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3392
+ } else if (provider === "elevenlabs") {
3393
+ logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
3394
+ if (!keys.elevenlabs)
3395
+ throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3396
+ const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs.json`;
3397
+ asrResult = forceAll ? null : readJson(cachePath);
3398
+ if (!asrResult) {
3399
+ const { readFile: readFile2 } = await import("fs/promises");
3400
+ const buf = await readFile2(audioPath);
3401
+ const el = new ElevenLabsClient(keys.elevenlabs);
3402
+ asrResult = await el.transcribe(buf).catch(stageTag("asr"));
3403
+ writeJson(cachePath, asrResult);
3404
+ } else {
3405
+ logger.info("[elevenlabs] cache hit");
3406
+ }
3407
+ writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3408
+ logger.info(
3409
+ `[elevenlabs] ${asrResult.utterances.length} utterances, ${asrResult.words.length} words, ${asrResult.speakers?.length ?? "?"} speakers`
3410
+ );
1948
3411
  } else {
1949
3412
  logger.info("=== timestamped (AssemblyAI) ===");
1950
3413
  if (!keys.assemblyai)
@@ -1955,14 +3418,14 @@ async function transcribe(opts2) {
1955
3418
  apiKey: keys.assemblyai,
1956
3419
  cacheDir: `${options.intermediatesDir}/assemblyai`
1957
3420
  });
1958
- asrResult = await aai.transcribe(audioPath);
3421
+ asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
1959
3422
  writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
1960
3423
  }
1961
3424
  } else {
1962
3425
  asrResult = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
1963
3426
  }
1964
3427
  let aligned = [];
1965
- if (has(passes2, "align") && asrResult) {
3428
+ if (has(passes, "align") && asrResult) {
1966
3429
  logger.info("=== align ===");
1967
3430
  aligned = alignSegments(allLlmSegments, asrResult.words, { timeMarginSec: 30 });
1968
3431
  writeJson(`${options.intermediatesDir}/aligned.json`, aligned);
@@ -1971,15 +3434,18 @@ async function transcribe(opts2) {
1971
3434
  }
1972
3435
  const alignedOk = aligned.filter((a) => a.timingSource !== "coarse").length;
1973
3436
  logger.info(`aligned: ${alignedOk}/${aligned.length} with ASR timing`);
1974
- if (asrResult && (has(passes2, "align") || has(passes2, "consistency"))) {
3437
+ if (asrResult && (has(passes, "align") || has(passes, "consistency"))) {
1975
3438
  const before = aligned.length;
1976
3439
  aligned = fillAsrGaps(aligned, asrResult.words, asrResult.utterances);
1977
3440
  const added = aligned.length - before;
1978
3441
  if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
1979
3442
  }
3443
+ if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
3444
+ aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
3445
+ }
1980
3446
  let segments = aligned;
1981
3447
  let speakers = [];
1982
- if (has(passes2, "consistency") && asrResult) {
3448
+ if (has(passes, "consistency") && asrResult) {
1983
3449
  logger.info("=== consistency ===");
1984
3450
  const cons = assignGlobalSpeakers(aligned, asrResult.utterances, {
1985
3451
  hasDiarization: asrResult.hasDiarization ?? true
@@ -1996,34 +3462,78 @@ async function transcribe(opts2) {
1996
3462
  speakers = c.speakers;
1997
3463
  }
1998
3464
  }
1999
- if (options.diarizationLevel >= 3 && has(passes2, "identify") && keys.deepseek && description) {
2000
- logger.info("=== identify (DeepSeek) ===");
2001
- const dsClient = OpenAICompatClient.fromProvider(
2002
- "deepseek",
2003
- keys.deepseek,
2004
- models.reasoner
2005
- );
2006
- const id = await identifySpeakers(
2007
- dsClient,
2008
- models.reasoner,
2009
- segments.map((s) => ({ speaker: s.speaker, text: s.text })),
2010
- speakers,
2011
- description.roster,
2012
- options.knownSpeakers
2013
- );
2014
- logger.info(
2015
- `identified ${Object.keys(id.nameMap).length} speakers: ${JSON.stringify(id.nameMap)}`
2016
- );
2017
- writeJson(`${options.intermediatesDir}/identified.json`, id);
2018
- segments = segments.map(
2019
- (s) => id.nameMap[s.speaker] ? { ...s, speakerName: id.nameMap[s.speaker] } : s
2020
- );
2021
- speakers = speakers.map(
2022
- (sp) => id.nameMap[sp.id] ? { ...sp, name: id.nameMap[sp.id] } : sp
2023
- );
3465
+ const nameHints = {};
3466
+ for (const sp of speakers) {
3467
+ if (sp.name && sp.name !== sp.id) nameHints[sp.id] = sp.name;
3468
+ }
3469
+ segments = segments.map(
3470
+ (s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
3471
+ );
3472
+ speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
3473
+ if (options.diarizationLevel >= 3 && has(passes, "identify")) {
3474
+ const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
3475
+ if (!reasonerA) {
3476
+ logger.warn(
3477
+ "identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
3478
+ );
3479
+ } else {
3480
+ const mode = options.identifyMode;
3481
+ const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
3482
+ const idConfig = {
3483
+ mode,
3484
+ reasonerA: reasonerA.info.model,
3485
+ reasonerB: reasonerB?.info.model ?? null
3486
+ };
3487
+ const idCachePath = `${options.intermediatesDir}/identified.json`;
3488
+ const cachedId = forceAll ? null : readJson(
3489
+ idCachePath
3490
+ );
3491
+ const idConfigMatches = cachedId?.config && JSON.stringify(cachedId.config) === JSON.stringify(idConfig);
3492
+ let nameMap = null;
3493
+ if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
3494
+ logger.info("=== identify (cached) ===");
3495
+ nameMap = cachedId.nameMap;
3496
+ } else {
3497
+ logger.info(
3498
+ `=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
3499
+ );
3500
+ checkAbort();
3501
+ const id = await identifySpeakersV2(
3502
+ {
3503
+ client: reasonerA.client,
3504
+ model: reasonerA.info.model,
3505
+ provider: reasonerA.info.provider
3506
+ },
3507
+ reasonerB ? {
3508
+ client: reasonerB.client,
3509
+ model: reasonerB.info.model,
3510
+ provider: reasonerB.info.provider
3511
+ } : null,
3512
+ segments.map((s) => ({ speaker: s.speaker, text: s.text })),
3513
+ speakers,
3514
+ {
3515
+ roster: description?.roster ?? "(no roster available \u2014 infer from the transcript alone)",
3516
+ knownSpeakers: options.knownSpeakers,
3517
+ mode,
3518
+ nameHints,
3519
+ sourceFileName: basename3(options.input)
3520
+ }
3521
+ ).catch(stageTag("identify"));
3522
+ writeJson(idCachePath, { ...id, config: idConfig });
3523
+ nameMap = id.nameMap;
3524
+ }
3525
+ logger.info(
3526
+ `identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
3527
+ );
3528
+ const nm = nameMap;
3529
+ segments = segments.map(
3530
+ (s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
3531
+ );
3532
+ speakers = speakers.map((sp) => nm[sp.id] ? { ...sp, name: nm[sp.id] } : sp);
3533
+ }
2024
3534
  }
2025
3535
  let finalSegments = [];
2026
- if (has(passes2, "finalize")) {
3536
+ if (has(passes, "finalize")) {
2027
3537
  logger.info("=== finalize ===");
2028
3538
  finalSegments = finalizeSegments(segments);
2029
3539
  writeJson(`${options.intermediatesDir}/final.json`, finalSegments);
@@ -2031,33 +3541,106 @@ async function transcribe(opts2) {
2031
3541
  finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
2032
3542
  }
2033
3543
  logger.info(`final segments: ${finalSegments.length}`);
3544
+ const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
3545
+ const wallMs = Date.now() - runStartedAt;
2034
3546
  const metadata = {
2035
3547
  sourceFile: options.input,
2036
3548
  duration,
2037
3549
  processedAt: (/* @__PURE__ */ new Date()).toISOString(),
2038
3550
  models: {
2039
3551
  transcribe: models.transcribe,
2040
- timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
3552
+ timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "elevenlabs" ? "scribe-v2 (elevenlabs)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
2041
3553
  },
2042
- passes: passes2
3554
+ passes,
3555
+ wallMs,
3556
+ cost: {
3557
+ estimatedUsd: estimate.totalUsd,
3558
+ actualUsd: receipt.totalUsd,
3559
+ pricesAsOf: PRICES_AS_OF,
3560
+ lines: receipt.lines,
3561
+ llmCalls: receipt.totals.calls,
3562
+ inputTokens: receipt.totals.inputTokens,
3563
+ outputTokens: receipt.totals.outputTokens
3564
+ }
2043
3565
  };
2044
3566
  const result = { segments: finalSegments, speakers, metadata };
3567
+ writeJson(`${options.intermediatesDir}/result.json`, result);
2045
3568
  for (const fmt of options.formats) {
2046
3569
  const base = basename3(options.input, ext(options.input));
2047
3570
  if (fmt === "srt")
2048
- writeFileSync(
3571
+ writeFileSync2(
2049
3572
  `${options.outputDir}/${base}.srt`,
2050
3573
  formatSrt(result, { title: base })
2051
3574
  );
2052
3575
  if (fmt === "md")
2053
- writeFileSync(
3576
+ writeFileSync2(
2054
3577
  `${options.outputDir}/${base}.md`,
2055
- formatMarkdown(result, { title: base })
3578
+ formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
3579
+ );
3580
+ if (fmt === "txt")
3581
+ writeFileSync2(
3582
+ `${options.outputDir}/${base}.txt`,
3583
+ formatText(result, { title: base })
3584
+ );
3585
+ if (fmt === "html")
3586
+ writeFileSync2(
3587
+ `${options.outputDir}/${base}.html`,
3588
+ formatHtml(result, { title: base })
2056
3589
  );
2057
3590
  if (fmt === "json")
2058
- writeFileSync(`${options.outputDir}/${base}.json`, formatJson(result));
3591
+ writeFileSync2(`${options.outputDir}/${base}.json`, formatJson(result));
3592
+ }
3593
+ if (options.summary && finalSegments.length > 0) {
3594
+ const reasoner = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
3595
+ if (!reasoner) {
3596
+ logger.warn("summary: no reasoner-capable key \u2014 skipping");
3597
+ } else {
3598
+ logger.info(`=== summary (${reasoner.info.model}) ===`);
3599
+ try {
3600
+ const summary = await summarizeTranscript(
3601
+ reasoner.client,
3602
+ reasoner.info.model,
3603
+ result,
3604
+ options.instructions
3605
+ );
3606
+ const base = basename3(options.input, ext(options.input));
3607
+ writeFileSync2(`${options.outputDir}/${base}.summary.md`, summary);
3608
+ logger.info(`summary written to ${base}.summary.md`);
3609
+ } catch (err) {
3610
+ logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
3611
+ }
3612
+ }
3613
+ }
3614
+ try {
3615
+ const base = basename3(options.input, ext(options.input));
3616
+ const partial = `${options.outputDir}/${base}.partial.md`;
3617
+ if (existsSync3(partial)) (await import("fs/promises")).unlink(partial);
3618
+ } catch {
2059
3619
  }
2060
3620
  logger.info(`outputs written to ${options.outputDir}`);
3621
+ const mins = Math.floor(wallMs / 6e4);
3622
+ const secs = Math.round(wallMs % 6e4 / 1e3);
3623
+ logger.info(
3624
+ `receipt: ${receipt.totals.calls} LLM calls \xB7 ${(receipt.totals.inputTokens / 1e3).toFixed(0)}k in / ${(receipt.totals.outputTokens / 1e3).toFixed(0)}k out \xB7 ~$${receipt.totalUsd.toFixed(2)}${receipt.incomplete ? " (+unpriced)" : ""} \xB7 ${mins ? `${mins}m` : ""}${secs}s`
3625
+ );
3626
+ for (const line of receipt.lines) logger.info(` ${line}`);
3627
+ recordRun(
3628
+ {
3629
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
3630
+ input: basename3(options.input),
3631
+ durationSec: duration,
3632
+ wallMs,
3633
+ models: metadata.models,
3634
+ segments: finalSegments.length,
3635
+ characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
3636
+ speakers: speakers.length,
3637
+ llmCalls: receipt.totals.calls,
3638
+ inputTokens: receipt.totals.inputTokens,
3639
+ outputTokens: receipt.totals.outputTokens,
3640
+ costUsd: receipt.totalUsd
3641
+ },
3642
+ receipt.perModel
3643
+ );
2061
3644
  return result;
2062
3645
  }
2063
3646
  function ext(p) {
@@ -2065,61 +3648,1101 @@ function ext(p) {
2065
3648
  return i >= 0 ? p.slice(i) : "";
2066
3649
  }
2067
3650
 
3651
+ // src/commands/models.ts
3652
+ var TRANSCRIBE_PRESETS = [
3653
+ { model: "gemini-3.1-pro-preview", note: "default \u2014 best diarization/tone" },
3654
+ { model: "gemini-3.5-flash", note: "fast/cheap \u2014 great daily driver" },
3655
+ { model: "gemini-flash-latest", note: "moving alias, stays current" },
3656
+ { model: "gemini-3-pro-preview", note: "" },
3657
+ { model: "gemini-2.5-pro", note: "" },
3658
+ { model: "gemini-2.5-flash", note: "" }
3659
+ ];
3660
+ var TIMESTAMPED_PRESETS = [
3661
+ {
3662
+ id: "assemblyai",
3663
+ keyName: "assemblyai",
3664
+ note: "default \u2014 word timing + diarization"
3665
+ },
3666
+ {
3667
+ id: "elevenlabs",
3668
+ keyName: "elevenlabs",
3669
+ note: "Scribe v2 \u2014 strongest diarization labels"
3670
+ },
3671
+ {
3672
+ id: "whisper-groq",
3673
+ keyName: "groq",
3674
+ note: "free/fast \u2014 word timing, NO diarization"
3675
+ },
3676
+ { id: "none", keyName: null, note: "LLM-only (coarse timestamps)" }
3677
+ ];
3678
+ var ok = (b) => b ? "\u2713" : "\u2717 (no key)";
3679
+ async function runModels() {
3680
+ const keys = resolveKeys();
3681
+ const lines = [];
3682
+ lines.push("");
3683
+ lines.push("TRANSCRIBE (multimodal \u2014 hears the audio) --model");
3684
+ for (const p of TRANSCRIBE_PRESETS) {
3685
+ const mark = ok(!!keys.gemini);
3686
+ const def = p.model === DEFAULT_TRANSCRIBE_MODEL ? " \u2190 default" : "";
3687
+ lines.push(` ${mark} ${p.model.padEnd(28)} ${p.note}${def}`);
3688
+ }
3689
+ lines.push("");
3690
+ lines.push("TIMESTAMPED (owns the clock) --timestamped");
3691
+ for (const p of TIMESTAMPED_PRESETS) {
3692
+ const has2 = p.keyName === null ? true : !!keys[p.keyName];
3693
+ const def = p.id === "assemblyai" ? " \u2190 default" : "";
3694
+ lines.push(` ${ok(has2)} ${p.id.padEnd(28)} ${p.note}${def}`);
3695
+ }
3696
+ lines.push("");
3697
+ lines.push("REASONER (text passes: identify, summary) --reasoner");
3698
+ for (const p of REASONER_PRESETS) {
3699
+ const info = resolveReasonerInfo(p.model);
3700
+ const has2 = !!reasonerKey(info, keys);
3701
+ const def = p.model === DEFAULT_REASONER_MODEL ? " \u2190 default" : "";
3702
+ lines.push(` ${ok(has2)} ${p.model.padEnd(28)} ${p.note}${def}`);
3703
+ }
3704
+ lines.push("");
3705
+ lines.push("Any Gemini model id works for --model; any provider-prefixed model");
3706
+ lines.push('(e.g. "zai:glm-4.7") works for --reasoner. Keys come from the environment');
3707
+ lines.push("or can be injected via the library API.");
3708
+ lines.push("");
3709
+ console.log(lines.join("\n"));
3710
+ }
3711
+
3712
+ // src/commands/doctor.ts
3713
+ async function ping(url, headers) {
3714
+ const controller = new AbortController();
3715
+ const timer2 = setTimeout(() => controller.abort(), 8e3);
3716
+ try {
3717
+ const res = await fetch(url, { headers, signal: controller.signal });
3718
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
3719
+ } finally {
3720
+ clearTimeout(timer2);
3721
+ }
3722
+ }
3723
+ function providerChecks(keys) {
3724
+ const checks = [];
3725
+ const add = (name, key, fn) => {
3726
+ checks.push({
3727
+ name,
3728
+ run: async () => {
3729
+ if (!key) throw new Error("no key in environment");
3730
+ await fn(key);
3731
+ return "key valid, API reachable";
3732
+ }
3733
+ });
3734
+ };
3735
+ add(
3736
+ "gemini (transcribe)",
3737
+ keys.gemini,
3738
+ (k) => ping(
3739
+ `https://generativelanguage.googleapis.com/v1beta/models?pageSize=1&key=${k}`,
3740
+ {}
3741
+ )
3742
+ );
3743
+ add(
3744
+ "assemblyai (timestamped)",
3745
+ keys.assemblyai,
3746
+ (k) => ping("https://api.assemblyai.com/v2/transcript?limit=1", { authorization: k })
3747
+ );
3748
+ checks.push({
3749
+ name: "elevenlabs (timestamped)",
3750
+ run: async () => {
3751
+ if (!keys.elevenlabs) throw new Error("no key in environment");
3752
+ const res = await fetch("https://api.elevenlabs.io/v1/speech-to-text", {
3753
+ method: "POST",
3754
+ headers: { "xi-api-key": keys.elevenlabs }
3755
+ });
3756
+ if (res.status === 401) throw new Error("HTTP 401 (bad key)");
3757
+ return "key valid, API reachable";
3758
+ }
3759
+ });
3760
+ add(
3761
+ "groq (timestamped fallback)",
3762
+ keys.groq,
3763
+ (k) => ping("https://api.groq.com/openai/v1/models", { Authorization: `Bearer ${k}` })
3764
+ );
3765
+ add(
3766
+ "deepseek (reasoner)",
3767
+ keys.deepseek,
3768
+ (k) => ping("https://api.deepseek.com/v1/models", { Authorization: `Bearer ${k}` })
3769
+ );
3770
+ add(
3771
+ "openai (reasoner)",
3772
+ keys.openai,
3773
+ (k) => ping("https://api.openai.com/v1/models", { Authorization: `Bearer ${k}` })
3774
+ );
3775
+ add(
3776
+ "zai / GLM (reasoner)",
3777
+ keys.zai,
3778
+ (k) => ping("https://api.z.ai/api/paas/v4/models", { Authorization: `Bearer ${k}` })
3779
+ );
3780
+ add(
3781
+ "kimi / Moonshot (reasoner)",
3782
+ keys.kimi,
3783
+ (k) => ping("https://api.moonshot.ai/v1/models", { Authorization: `Bearer ${k}` })
3784
+ );
3785
+ return checks;
3786
+ }
3787
+ async function runDoctor() {
3788
+ const keys = resolveKeys();
3789
+ console.log("\noffmute-v2 doctor\n");
3790
+ const ff = await checkFfmpeg();
3791
+ console.log(
3792
+ ` ${ff ? "\u2713" : "\u2717"} ffmpeg/ffprobe ${ff ? "found in PATH" : "NOT FOUND \u2014 install ffmpeg"}`
3793
+ );
3794
+ const checks = providerChecks(keys);
3795
+ const results = await Promise.allSettled(checks.map((c) => c.run()));
3796
+ let usable = 0;
3797
+ results.forEach((r, i) => {
3798
+ const name = checks[i].name;
3799
+ if (r.status === "fulfilled") {
3800
+ usable++;
3801
+ console.log(` \u2713 ${name.padEnd(28)} ${r.value}`);
3802
+ } else {
3803
+ const msg = r.reason instanceof Error ? r.reason.message : String(r.reason);
3804
+ const mark = msg === "no key in environment" ? "\u2013" : "\u2717";
3805
+ console.log(` ${mark} ${name.padEnd(28)} ${msg}`);
3806
+ }
3807
+ });
3808
+ console.log("");
3809
+ const okByName = (needle) => checks.some(
3810
+ (c, i) => c.name.startsWith(needle) && results[i]?.status === "fulfilled"
3811
+ );
3812
+ const geminiOk = okByName("gemini");
3813
+ const assemblyOk = okByName("assemblyai");
3814
+ const elevenOk = okByName("elevenlabs");
3815
+ const groqOk = okByName("groq");
3816
+ if (ff && geminiOk && assemblyOk) {
3817
+ console.log(" Ready: transcription will work with the current setup.\n");
3818
+ } else if (ff && geminiOk && (elevenOk || groqOk)) {
3819
+ const alt = elevenOk ? "--timestamped elevenlabs" : "--timestamped whisper-groq";
3820
+ console.log(
3821
+ ` Ready with ${alt}: the default clock (AssemblyAI) is missing, so plain runs will fail \u2014`
3822
+ );
3823
+ console.log(` add ASSEMBLYAI_API_KEY or pass ${alt}.
3824
+ `);
3825
+ } else {
3826
+ if (!ff) console.log(" Blocked: install ffmpeg (e.g. `brew install ffmpeg`).");
3827
+ if (!geminiOk)
3828
+ console.log(
3829
+ " Blocked: set GEMINI_API_KEY (or GOOGLE_API_KEY) \u2014 required for transcription."
3830
+ );
3831
+ if (!assemblyOk && !elevenOk && !groqOk)
3832
+ console.log(
3833
+ " Degraded: no timestamped provider (ASSEMBLYAI/ELEVENLABS/GROQ key) \u2014 timestamps will be coarse."
3834
+ );
3835
+ console.log("");
3836
+ }
3837
+ void usable;
3838
+ }
3839
+
3840
+ // src/commands/stats.ts
3841
+ function runStats() {
3842
+ const s = readStats();
3843
+ if (s.runs === 0) {
3844
+ console.log(`
3845
+ No runs recorded yet (stats live in ${statsDir()}).
3846
+ `);
3847
+ return;
3848
+ }
3849
+ const lines = [];
3850
+ lines.push("");
3851
+ lines.push(`offmute-v2 lifetime stats (${statsDir()})`);
3852
+ lines.push("");
3853
+ lines.push(` runs ${s.runs}`);
3854
+ lines.push(
3855
+ ` media processed ${formatDuration(Math.round(s.mediaSeconds))} (${(s.mediaSeconds / 3600).toFixed(1)}h)`
3856
+ );
3857
+ lines.push(` characters out ${s.characters.toLocaleString()}`);
3858
+ lines.push(
3859
+ ` LLM calls ${s.llmCalls.toLocaleString()} (${(s.inputTokens / 1e6).toFixed(1)}M in / ${(s.outputTokens / 1e6).toFixed(1)}M out)`
3860
+ );
3861
+ lines.push(` total cost ~$${s.costUsd.toFixed(2)}`);
3862
+ if (s.firstRun) lines.push(` since ${s.firstRun.slice(0, 10)}`);
3863
+ const models = Object.entries(s.costByModel).sort((a, b) => b[1] - a[1]);
3864
+ if (models.length) {
3865
+ lines.push("");
3866
+ lines.push(" cost by model");
3867
+ for (const [model, usd] of models) {
3868
+ const runs = s.runsByModel[model] ? ` \xB7 ${s.runsByModel[model]} runs` : "";
3869
+ lines.push(` ${model.padEnd(28)} ~$${usd.toFixed(2)}${runs}`);
3870
+ }
3871
+ }
3872
+ lines.push("");
3873
+ console.log(lines.join("\n"));
3874
+ }
3875
+
3876
+ // src/commands/rename.ts
3877
+ import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
3878
+ import { basename as basename4, dirname as dirname4, join as join2, resolve as resolve3 } from "path";
3879
+ function loadSource(path, opts) {
3880
+ if (path.endsWith(".json")) {
3881
+ return {
3882
+ result: JSON.parse(readFileSync3(path, "utf-8")),
3883
+ outDir: opts.output ?? dirname4(resolve3(path)),
3884
+ base: basename4(path, ".json"),
3885
+ jsonPath: path
3886
+ };
3887
+ }
3888
+ const cacheDir = opts.intermediates ?? deriveIntermediatesDir(path);
3889
+ const resultPath = join2(cacheDir, "result.json");
3890
+ const sourcePath = join2(cacheDir, "source.json");
3891
+ if (!existsSync4(resultPath)) {
3892
+ console.error(`\u2717 no cached transcript found for ${basename4(path)}`);
3893
+ console.error(
3894
+ ` the cache lives in the OS temp dir and may have been cleaned up.
3895
+ re-run first: offmute-v2 "${path}" (then rename again \u2014 naming is cached)`
3896
+ );
3897
+ process.exit(1);
3898
+ }
3899
+ try {
3900
+ const src = JSON.parse(readFileSync3(sourcePath, "utf-8"));
3901
+ if (src.signature && src.signature !== inputSignature(path)) {
3902
+ console.error(
3903
+ `\u2717 the cached transcript is from an older version of ${basename4(path)}`
3904
+ );
3905
+ console.error(` re-run first: offmute-v2 "${path}"`);
3906
+ process.exit(1);
3907
+ }
3908
+ } catch {
3909
+ }
3910
+ const ext2 = path.slice(path.lastIndexOf("."));
3911
+ return {
3912
+ result: JSON.parse(readFileSync3(resultPath, "utf-8")),
3913
+ outDir: opts.output ?? dirname4(resolve3(path)),
3914
+ base: basename4(path, ext2),
3915
+ jsonPath: resultPath
3916
+ };
3917
+ }
3918
+ function runRename(path, mappings, opts) {
3919
+ const { result, outDir, base, jsonPath } = loadSource(path, opts);
3920
+ const map = /* @__PURE__ */ new Map();
3921
+ for (const m of mappings) {
3922
+ const eq = m.indexOf("=");
3923
+ if (eq <= 0) {
3924
+ console.error(`\u2717 bad mapping "${m}" \u2014 expected "Old Name=New Name"`);
3925
+ process.exit(1);
3926
+ }
3927
+ map.set(m.slice(0, eq).trim(), m.slice(eq + 1).trim());
3928
+ }
3929
+ const applied = /* @__PURE__ */ new Set();
3930
+ const renameOf = (s) => {
3931
+ for (const key of [
3932
+ s.speakerName,
3933
+ s.name,
3934
+ s.speaker,
3935
+ typeof s.id === "string" ? s.id : void 0
3936
+ ]) {
3937
+ if (key && map.has(key)) {
3938
+ applied.add(key);
3939
+ return map.get(key);
3940
+ }
3941
+ }
3942
+ return null;
3943
+ };
3944
+ for (const seg of result.segments) {
3945
+ const to = renameOf(seg);
3946
+ if (to) seg.speakerName = to;
3947
+ }
3948
+ for (const sp of result.speakers) {
3949
+ const to = renameOf(sp);
3950
+ if (to) sp.name = to;
3951
+ }
3952
+ const missed = [...map.keys()].filter((k) => !applied.has(k));
3953
+ if (missed.length) {
3954
+ const known = [
3955
+ ...new Set(result.speakers.flatMap((s) => [s.id, s.name]).filter(Boolean))
3956
+ ].join(", ");
3957
+ console.error(
3958
+ `\u2717 no speaker matched: ${missed.join(", ")}
3959
+ known speakers: ${known}`
3960
+ );
3961
+ process.exit(1);
3962
+ }
3963
+ writeFileSync3(jsonPath, JSON.stringify(result, null, 2));
3964
+ const idPath = join2(dirname4(jsonPath), "identified.json");
3965
+ if (basename4(jsonPath) === "result.json" && existsSync4(idPath)) {
3966
+ try {
3967
+ const id = JSON.parse(readFileSync3(idPath, "utf-8"));
3968
+ id.nameMap ??= {};
3969
+ for (const sp of result.speakers) {
3970
+ if (sp.name && sp.name !== sp.id) id.nameMap[sp.id] = sp.name;
3971
+ }
3972
+ writeFileSync3(idPath, JSON.stringify(id, null, 2));
3973
+ } catch {
3974
+ }
3975
+ }
3976
+ const formats = opts.formats.split(",").map((f) => f.trim());
3977
+ const written = [];
3978
+ const write = (name, contents) => {
3979
+ const p = join2(outDir, name);
3980
+ writeFileSync3(p, contents);
3981
+ written.push(p);
3982
+ };
3983
+ if (formats.includes("md"))
3984
+ write(`${base}.md`, formatMarkdown(result, { title: base, mdStyle: opts.mdStyle }));
3985
+ if (formats.includes("srt")) write(`${base}.srt`, formatSrt(result, { title: base }));
3986
+ if (formats.includes("txt")) write(`${base}.txt`, formatText(result, { title: base }));
3987
+ if (formats.includes("html"))
3988
+ write(`${base}.html`, formatHtml(result, { title: base }));
3989
+ if (formats.includes("json") && jsonPath !== join2(outDir, `${base}.json`)) {
3990
+ write(`${base}.json`, JSON.stringify(result, null, 2));
3991
+ }
3992
+ console.log(`Renamed ${applied.size} speaker(s).`);
3993
+ for (const p of written) console.log(` \u2192 ${p}`);
3994
+ }
3995
+
3996
+ // src/commands/watch.ts
3997
+ import {
3998
+ existsSync as existsSync5,
3999
+ mkdirSync as mkdirSync3,
4000
+ readFileSync as readFileSync4,
4001
+ writeFileSync as writeFileSync4,
4002
+ appendFileSync as appendFileSync3,
4003
+ watch as fsWatch,
4004
+ statSync as statSync2,
4005
+ readdirSync
4006
+ } from "fs";
4007
+ import { join as join3, extname, basename as basename5 } from "path";
4008
+
4009
+ // src/utils/notify.ts
4010
+ import { execFile } from "child_process";
4011
+ function notify(title, message) {
4012
+ try {
4013
+ const esc2 = (s) => s.replace(/["\\]/g, "");
4014
+ if (process.platform === "darwin") {
4015
+ execFile(
4016
+ "osascript",
4017
+ [
4018
+ "-e",
4019
+ `display notification "${esc2(message)}" with title "${esc2(title)}" sound name "Glass"`
4020
+ ],
4021
+ () => {
4022
+ }
4023
+ );
4024
+ } else if (process.platform === "linux") {
4025
+ execFile("notify-send", [title, message], () => {
4026
+ });
4027
+ }
4028
+ } catch {
4029
+ }
4030
+ }
4031
+
4032
+ // src/commands/watch.ts
4033
+ var MEDIA_EXTS = /* @__PURE__ */ new Set([
4034
+ ".mp4",
4035
+ ".mov",
4036
+ ".mkv",
4037
+ ".webm",
4038
+ ".avi",
4039
+ ".m4a",
4040
+ ".mp3",
4041
+ ".wav",
4042
+ ".aac",
4043
+ ".flac",
4044
+ ".ogg",
4045
+ ".opus",
4046
+ ".wma"
4047
+ ]);
4048
+ var POLL_MS = 5e3;
4049
+ function ts() {
4050
+ return (/* @__PURE__ */ new Date()).toTimeString().slice(0, 8);
4051
+ }
4052
+ async function runWatch(dir, opts) {
4053
+ if (!existsSync5(dir) || !statSync2(dir).isDirectory()) {
4054
+ console.error(`\u2717 not a directory: ${dir}`);
4055
+ process.exit(1);
4056
+ }
4057
+ const stateDir = join3(dir, ".offmute");
4058
+ mkdirSync3(stateDir, { recursive: true });
4059
+ const statePath = join3(stateDir, "state.json");
4060
+ const logPath2 = join3(stateDir, "daemon.log");
4061
+ let state = { done: {} };
4062
+ if (existsSync5(statePath)) {
4063
+ try {
4064
+ const parsed = JSON.parse(readFileSync4(statePath, "utf-8"));
4065
+ state = { done: parsed.done ?? {} };
4066
+ } catch {
4067
+ }
4068
+ }
4069
+ const saveState = () => writeFileSync4(statePath, JSON.stringify(state, null, 2));
4070
+ const log2 = (line) => {
4071
+ console.log(`[${ts()}] ${line}`);
4072
+ try {
4073
+ appendFileSync3(logPath2, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
4074
+ `);
4075
+ } catch {
4076
+ }
4077
+ };
4078
+ const matchExts = opts.match ? new Set(
4079
+ opts.match.split(",").map((e) => (e.startsWith(".") ? e : `.${e}`).toLowerCase())
4080
+ ) : MEDIA_EXTS;
4081
+ const seenSizes = /* @__PURE__ */ new Map();
4082
+ const queued = /* @__PURE__ */ new Set();
4083
+ const queue = [];
4084
+ let processed = 0;
4085
+ const listCandidates = () => {
4086
+ try {
4087
+ return readdirSync(dir).filter((f) => !f.startsWith(".")).filter((f) => matchExts.has(extname(f).toLowerCase())).map((f) => join3(dir, f));
4088
+ } catch {
4089
+ return [];
4090
+ }
4091
+ };
4092
+ const failedThisSession = /* @__PURE__ */ new Set();
4093
+ const scan = (isFirst = false) => {
4094
+ for (const file of listCandidates()) {
4095
+ if (queued.has(file) || failedThisSession.has(file)) continue;
4096
+ let st;
4097
+ try {
4098
+ st = statSync2(file);
4099
+ } catch {
4100
+ continue;
4101
+ }
4102
+ if (st.size === 0) continue;
4103
+ const sig = inputSignature(file);
4104
+ let record = state.done[sig];
4105
+ if (isFirst && !opts.backlog) {
4106
+ if (!record || record.error) {
4107
+ state.done[sig] = {
4108
+ file: basename5(file),
4109
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
4110
+ skipped: true
4111
+ };
4112
+ }
4113
+ continue;
4114
+ }
4115
+ if (isFirst && record?.error) {
4116
+ delete state.done[sig];
4117
+ record = void 0;
4118
+ log2(`retrying ${basename5(file)} (failed last session)`);
4119
+ }
4120
+ if (record) continue;
4121
+ const prev = seenSizes.get(file);
4122
+ if (prev && prev.size === st.size && prev.mtimeMs === st.mtimeMs) {
4123
+ queued.add(file);
4124
+ queue.push(file);
4125
+ log2(
4126
+ `queued ${basename5(file)} (${(st.size / 1e6).toFixed(0)}MB, queue: ${queue.length})`
4127
+ );
4128
+ } else {
4129
+ seenSizes.set(file, { size: st.size, mtimeMs: st.mtimeMs });
4130
+ }
4131
+ }
4132
+ if (isFirst && !opts.backlog) saveState();
4133
+ };
4134
+ let stopping = false;
4135
+ const activeControllers = /* @__PURE__ */ new Set();
4136
+ const jobs = Math.max(1, parseInt(opts.jobs, 10) || 1);
4137
+ let active2 = 0;
4138
+ const pump = async () => {
4139
+ while (!stopping && active2 < jobs && queue.length > 0) {
4140
+ const file = queue.shift();
4141
+ active2++;
4142
+ void runJob(file).finally(() => {
4143
+ active2--;
4144
+ void pump();
4145
+ });
4146
+ }
4147
+ };
4148
+ const runJob = async (file) => {
4149
+ const name = basename5(file);
4150
+ const abort = new AbortController();
4151
+ activeControllers.add(abort);
4152
+ log2(`start ${name}`);
4153
+ const t0 = Date.now();
4154
+ try {
4155
+ const result = await transcribe({
4156
+ ...opts.pipeline,
4157
+ input: file,
4158
+ outputDir: opts.output,
4159
+ signal: abort.signal,
4160
+ showProgress: false
4161
+ });
4162
+ const mins = ((Date.now() - t0) / 6e4).toFixed(1);
4163
+ const cost = result.metadata.cost ? ` \xB7 ~$${result.metadata.cost.actualUsd.toFixed(2)}` : "";
4164
+ state.done[inputSignature(file)] = {
4165
+ file: name,
4166
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
4167
+ segments: result.segments.length
4168
+ };
4169
+ saveState();
4170
+ processed++;
4171
+ log2(
4172
+ `done ${name} \xB7 ${result.segments.length} segments \xB7 ${result.speakers.length} speakers${cost} \xB7 ${mins}m`
4173
+ );
4174
+ notify(
4175
+ "offmute-v2 watch",
4176
+ `${name} transcribed \u2014 ${result.segments.length} segments${cost}`
4177
+ );
4178
+ } catch (err) {
4179
+ const msg = err instanceof Error ? err.message : String(err);
4180
+ if (abort.signal.aborted) {
4181
+ log2(`stopped ${name} (will resume on next start)`);
4182
+ return;
4183
+ }
4184
+ state.done[inputSignature(file)] = {
4185
+ file: name,
4186
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
4187
+ error: msg
4188
+ };
4189
+ failedThisSession.add(file);
4190
+ saveState();
4191
+ log2(`FAILED ${name} \u2014 ${msg} (will retry on next daemon start)`);
4192
+ notify("offmute-v2 watch", `${name} FAILED \u2014 ${msg.slice(0, 80)}`);
4193
+ } finally {
4194
+ queued.delete(file);
4195
+ activeControllers.delete(abort);
4196
+ }
4197
+ };
4198
+ process.on("SIGINT", () => {
4199
+ if (stopping) {
4200
+ console.log("\nforce exit.");
4201
+ process.exit(1);
4202
+ }
4203
+ stopping = true;
4204
+ log2(
4205
+ `stopping \u2014 ${activeControllers.size ? `aborting ${activeControllers.size} running job(s) at the next stage boundary, ` : ""}state saved. (Ctrl-C again to force)`
4206
+ );
4207
+ for (const c of activeControllers) c.abort();
4208
+ const wait = setInterval(() => {
4209
+ if (active2 === 0) {
4210
+ clearInterval(wait);
4211
+ log2(`daemon stopped \xB7 ${processed} file(s) processed this session`);
4212
+ process.exit(0);
4213
+ }
4214
+ }, 200);
4215
+ });
4216
+ log2(
4217
+ `watching ${dir} (exts: ${[...matchExts].join(" ")}, jobs: ${jobs}${opts.backlog ? "" : ", backlog skipped"})`
4218
+ );
4219
+ scan(true);
4220
+ void pump();
4221
+ try {
4222
+ fsWatch(dir, () => {
4223
+ if (!stopping) {
4224
+ scan();
4225
+ void pump();
4226
+ }
4227
+ });
4228
+ } catch {
4229
+ }
4230
+ setInterval(() => {
4231
+ if (!stopping) {
4232
+ scan();
4233
+ void pump();
4234
+ }
4235
+ }, POLL_MS);
4236
+ await new Promise(() => {
4237
+ });
4238
+ }
4239
+
4240
+ // src/utils/ui.ts
4241
+ import chalk from "chalk";
4242
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
4243
+ var TICK = chalk.green("\u2713");
4244
+ var WARN = chalk.yellow("\u25B2");
4245
+ var FAIL = chalk.red("\u2717");
4246
+ var SHIMMER_SPEED_CELLS_PER_S = 25;
4247
+ var SHIMMER_PADDING = 8;
4248
+ var SHIMMER_HALF_WIDTH = 5;
4249
+ function shimmer(text, now) {
4250
+ const chars = [...text];
4251
+ const period = chars.length + SHIMMER_PADDING * 2;
4252
+ const pos = now / 1e3 * SHIMMER_SPEED_CELLS_PER_S % period;
4253
+ let out = "";
4254
+ let runTier = -1;
4255
+ let run2 = "";
4256
+ const flush = () => {
4257
+ if (!run2) return;
4258
+ out += runTier === 2 ? chalk.bold.whiteBright(run2) : runTier === 1 ? chalk.white(run2) : chalk.dim(run2);
4259
+ run2 = "";
4260
+ };
4261
+ for (let i = 0; i < chars.length; i++) {
4262
+ const dist = Math.abs(i + SHIMMER_PADDING - pos);
4263
+ const intensity = dist >= SHIMMER_HALF_WIDTH ? 0 : 0.5 * (1 + Math.cos(Math.PI * dist / SHIMMER_HALF_WIDTH));
4264
+ const tier = intensity >= 0.65 ? 2 : intensity >= 0.2 ? 1 : 0;
4265
+ if (tier !== runTier) {
4266
+ flush();
4267
+ runTier = tier;
4268
+ }
4269
+ run2 += chars[i];
4270
+ }
4271
+ flush();
4272
+ return out;
4273
+ }
4274
+ var STAGE_LABELS = {
4275
+ preprocess: "preparing media",
4276
+ describe: "listening for context",
4277
+ "llm-transcribe": "transcribing",
4278
+ align: "aligning timestamps",
4279
+ consistency: "resolving speakers",
4280
+ finalize: "finalizing",
4281
+ summary: "summarizing"
4282
+ };
4283
+ function stageLabel(raw) {
4284
+ if (raw.startsWith("timestamped")) return raw.replace("timestamped", "timestamps");
4285
+ if (raw.startsWith("identify")) return raw.replace("identify", "naming speakers");
4286
+ return STAGE_LABELS[raw] ?? raw;
4287
+ }
4288
+ var active = false;
4289
+ var timer = null;
4290
+ var frame = 0;
4291
+ var stage = null;
4292
+ var lineDirty = false;
4293
+ function fmtElapsed(ms) {
4294
+ const s = Math.floor(ms / 1e3);
4295
+ return s >= 60 ? `${Math.floor(s / 60)}m${(s % 60).toString().padStart(2, "0")}s` : `${s}s`;
4296
+ }
4297
+ function clearLine() {
4298
+ if (lineDirty) {
4299
+ process.stdout.write("\r\x1B[2K");
4300
+ lineDirty = false;
4301
+ }
4302
+ }
4303
+ function drawSpinner() {
4304
+ if (!stage) return;
4305
+ const now = Date.now();
4306
+ const f = chalk.cyan(FRAMES[frame % FRAMES.length]);
4307
+ frame++;
4308
+ const elapsed = chalk.dim(fmtElapsed(now - stage.startedAt));
4309
+ const chunks = stage.chunksTotal !== void 0 ? chalk.dim(` ${stage.chunksDone ?? 0}/${stage.chunksTotal} chunks`) : "";
4310
+ const detail = stage.detail ? chalk.dim(` \xB7 ${stage.detail}`) : "";
4311
+ const line = `${f} ${shimmer(stage.label, now)}${chunks}${detail} ${elapsed}`;
4312
+ process.stdout.write(`\r\x1B[2K${line}`);
4313
+ lineDirty = true;
4314
+ }
4315
+ function println(text = "") {
4316
+ clearLine();
4317
+ process.stdout.write(text + "\n");
4318
+ if (active && stage) drawSpinner();
4319
+ }
4320
+ function completeStage() {
4321
+ if (!stage) return;
4322
+ const dur = fmtElapsed(Date.now() - stage.startedAt);
4323
+ const chunks = stage.chunksTotal !== void 0 ? chalk.dim(` \xB7 ${stage.chunksTotal} chunk${stage.chunksTotal === 1 ? "" : "s"}`) : "";
4324
+ const detail = stage.detail ? chalk.dim(` \xB7 ${stage.detail}`) : "";
4325
+ clearLine();
4326
+ process.stdout.write(`${TICK} ${stage.label}${chunks}${detail} ${chalk.dim(dur)}
4327
+ `);
4328
+ stage = null;
4329
+ }
4330
+ function startStage(rawName) {
4331
+ completeStage();
4332
+ stage = { label: stageLabel(rawName), startedAt: Date.now(), detail: "" };
4333
+ drawSpinner();
4334
+ }
4335
+ function handleLine(level, msg) {
4336
+ if (level === "warn") {
4337
+ println(`${WARN} ${chalk.yellow(msg)}`);
4338
+ return;
4339
+ }
4340
+ if (level === "error") {
4341
+ println(`${FAIL} ${chalk.red(msg)}`);
4342
+ return;
4343
+ }
4344
+ const stageMatch = msg.match(/^=== (.+) ===$/);
4345
+ if (stageMatch) {
4346
+ startStage(stageMatch[1]);
4347
+ return;
4348
+ }
4349
+ const totalMatch = msg.match(/^(\d+) chunks \(/);
4350
+ if (totalMatch && stage) {
4351
+ stage.chunksTotal = parseInt(totalMatch[1], 10);
4352
+ stage.chunksDone = 0;
4353
+ return;
4354
+ }
4355
+ if (/^\[llm\] chunk \d+ ok|^chunk \d+: cached/.test(msg) && stage?.chunksTotal !== void 0) {
4356
+ stage.chunksDone = (stage.chunksDone ?? 0) + 1;
4357
+ drawSpinner();
4358
+ return;
4359
+ }
4360
+ if (msg.startsWith("estimated cost")) {
4361
+ const pretty = msg.replace(
4362
+ /^estimated cost (~\$[\d.]+)(.*)$/,
4363
+ (_, amt, rest) => `${chalk.bold("estimate")} ${chalk.yellow(amt)}${chalk.dim(rest)}`
4364
+ );
4365
+ println(` ${pretty}`);
4366
+ return;
4367
+ }
4368
+ if (msg.startsWith("receipt:")) {
4369
+ completeStage();
4370
+ println(` ${chalk.bold("receipt")} ${chalk.yellow(msg.slice(9))}`);
4371
+ return;
4372
+ }
4373
+ if (msg.startsWith(" ") && /\$\d/.test(msg)) {
4374
+ println(chalk.dim(` ${msg.trim()}`));
4375
+ return;
4376
+ }
4377
+ if (msg.startsWith("identified ") || msg.startsWith("identify:")) {
4378
+ println(` ${chalk.magenta("\u25C6")} ${msg}`);
4379
+ return;
4380
+ }
4381
+ if (msg.startsWith("description:")) {
4382
+ const text = msg.slice(12).trim().replace(/\s+/g, " ");
4383
+ println(
4384
+ chalk.dim(` ${text.slice(0, Math.max(40, (process.stdout.columns || 100) - 4))}`)
4385
+ );
4386
+ return;
4387
+ }
4388
+ if (msg.startsWith("intermediates:")) {
4389
+ const p = msg.slice(14).trim().split(" (file://")[0];
4390
+ println(chalk.dim(` cache ${p}`));
4391
+ return;
4392
+ }
4393
+ if (msg.startsWith("outputs written")) {
4394
+ return;
4395
+ }
4396
+ if (stage) {
4397
+ stage.detail = msg.replace(/^\[[a-z-]+\]\s*/i, "").replace(/^cache hit \S+$/, "cached").replace(/\.{3}$/, "").slice(0, 60);
4398
+ drawSpinner();
4399
+ }
4400
+ }
4401
+ function configureUi(opts) {
4402
+ active = opts.enabled;
4403
+ if (!active) return;
4404
+ logger.setSink((level, msg) => {
4405
+ handleLine(level, msg);
4406
+ return true;
4407
+ });
4408
+ timer = setInterval(() => {
4409
+ if (stage) drawSpinner();
4410
+ }, 66);
4411
+ timer.unref();
4412
+ }
4413
+ function uiActive() {
4414
+ return active;
4415
+ }
4416
+ function finishUi() {
4417
+ if (!active) return;
4418
+ completeStage();
4419
+ clearLine();
4420
+ if (timer) clearInterval(timer);
4421
+ timer = null;
4422
+ active = false;
4423
+ logger.setSink(null);
4424
+ }
4425
+ function banner(version, inputName) {
4426
+ if (!active) return;
4427
+ process.stdout.write(
4428
+ `
4429
+ ${chalk.bold.cyan("offmute")}${chalk.dim("-v2")} ${chalk.dim(version)} ${chalk.bold(inputName)}
4430
+
4431
+ `
4432
+ );
4433
+ }
4434
+ function outputsBlock(files, summaryLine) {
4435
+ clearLine();
4436
+ process.stdout.write("\n");
4437
+ for (const f of files) {
4438
+ process.stdout.write(` ${chalk.green("\u2192")} ${f}
4439
+ `);
4440
+ }
4441
+ process.stdout.write(`
4442
+ ${chalk.bold(summaryLine)}
4443
+ `);
4444
+ }
4445
+ function tipsBlock(tips) {
4446
+ if (tips.length === 0) return;
4447
+ process.stdout.write("\n");
4448
+ for (const t of tips) {
4449
+ process.stdout.write(chalk.dim(` tip: ${t}
4450
+ `));
4451
+ }
4452
+ }
4453
+ function starFooter() {
4454
+ process.stdout.write(
4455
+ chalk.dim(
4456
+ `
4457
+ state-of-the-art open diarization \xB7 if it earned it: ${chalk.reset.dim.underline("github.com/SouthBridgeAI/offmute-v2")} ${chalk.yellow("\u2605")}
4458
+ `
4459
+ )
4460
+ );
4461
+ }
4462
+ function errorBlock(message, hint) {
4463
+ clearLine();
4464
+ if (timer) clearInterval(timer);
4465
+ if (stage) {
4466
+ process.stderr.write(
4467
+ `${FAIL} ${stage.label} ${chalk.dim(fmtElapsed(Date.now() - stage.startedAt))}
4468
+ `
4469
+ );
4470
+ stage = null;
4471
+ }
4472
+ process.stderr.write(`
4473
+ ${FAIL} ${chalk.red(message)}
4474
+ `);
4475
+ if (hint) process.stderr.write(chalk.dim(` ${hint}
4476
+ `));
4477
+ }
4478
+
4479
+ // src/commands/first-run.ts
4480
+ import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "fs";
4481
+ import { join as join4 } from "path";
4482
+ import chalk2 from "chalk";
4483
+ function maybeFirstRunCheck(version) {
4484
+ let last = null;
4485
+ const dir = statsDir();
4486
+ const path = join4(dir, "last-version");
4487
+ try {
4488
+ if (existsSync6(path)) last = readFileSync5(path, "utf-8").trim();
4489
+ } catch {
4490
+ }
4491
+ if (last === version) return false;
4492
+ try {
4493
+ mkdirSync4(dir, { recursive: true });
4494
+ writeFileSync5(path, version);
4495
+ } catch {
4496
+ }
4497
+ const keys = resolveKeys();
4498
+ const have = (k) => k ? chalk2.green("\u2713") : chalk2.dim("\u2013");
4499
+ const lines = [];
4500
+ lines.push(
4501
+ chalk2.dim(
4502
+ `first run of ${chalk2.reset.bold(version)}${chalk2.dim(" \u2014 checking your setup (offline; `offmute-v2 doctor` pings live)")}`
4503
+ )
4504
+ );
4505
+ lines.push(
4506
+ ` ${have(keys.gemini)} GEMINI_API_KEY ${chalk2.dim("transcription \u2014 required")}`
4507
+ );
4508
+ lines.push(
4509
+ ` ${have(keys.assemblyai)} ASSEMBLYAI_API_KEY ${chalk2.dim("word-accurate timestamps (default clock)")}`
4510
+ );
4511
+ lines.push(
4512
+ ` ${have(keys.elevenlabs)} ELEVENLABS_API_KEY ${chalk2.dim("Scribe v2 \u2014 sharpest diarization (--timestamped elevenlabs)")}`
4513
+ );
4514
+ lines.push(
4515
+ ` ${have(keys.deepseek)} DEEPSEEK_API_KEY ${chalk2.dim("cheapest speaker-naming reasoner")}`
4516
+ );
4517
+ lines.push(
4518
+ ` ${have(keys.groq)} GROQ_API_KEY ${chalk2.dim("free/fast whisper timing fallback")}`
4519
+ );
4520
+ const unlocks = [];
4521
+ if (!keys.gemini)
4522
+ unlocks.push(
4523
+ "set GEMINI_API_KEY (or GOOGLE_API_KEY) \u2014 nothing works without ears: https://aistudio.google.com/apikey"
4524
+ );
4525
+ if (!keys.assemblyai && !keys.elevenlabs && !keys.groq)
4526
+ unlocks.push(
4527
+ "add ASSEMBLYAI_API_KEY for word-accurate timestamps (timestamps are coarse without a clock)"
4528
+ );
4529
+ if (keys.assemblyai && !keys.elevenlabs)
4530
+ unlocks.push(
4531
+ "add ELEVENLABS_API_KEY to try Scribe v2 \u2014 the sharpest speaker separation we've tested on conversational audio"
4532
+ );
4533
+ if (!keys.deepseek)
4534
+ unlocks.push("add DEEPSEEK_API_KEY so speaker naming costs ~$0.003 a run");
4535
+ for (const u of unlocks.slice(0, 2)) lines.push(chalk2.dim(` unlock: ${u}`));
4536
+ process.stdout.write(lines.join("\n") + "\n\n");
4537
+ return true;
4538
+ }
4539
+
2068
4540
  // src/cli.ts
2069
4541
  var packageVersion = "0.0.0";
2070
4542
  try {
2071
- const here = dirname4(fileURLToPath(import.meta.url));
2072
- const pkg = JSON.parse(readFileSync2(join(here, "..", "package.json"), "utf-8"));
4543
+ const here = dirname5(fileURLToPath(import.meta.url));
4544
+ const pkg = JSON.parse(readFileSync6(join5(here, "..", "package.json"), "utf-8"));
2073
4545
  packageVersion = pkg.version;
2074
4546
  } catch {
2075
4547
  }
2076
4548
  var program = new Command();
2077
- program.name("offmute-v2").description("Diarized meeting transcription with multimodal LLMs + timestamped alignment.").version(packageVersion).argument("<input>", "input video/audio file").option("-o, --output <dir>", "output directory (default: next to the input file)").option(
2078
- "-i, --intermediates <dir>",
2079
- "intermediates directory (default: auto-derived per input file so caches never collide)"
2080
- ).option("--instructions <text>", "custom instructions for the LLM").option("--passes <list>", "comma-separated passes to run").option("--chunk-seconds <n>", "chunk duration in seconds", "600").option("--overlap-seconds <n>", "chunk overlap in seconds", "60").option("--concurrency <n>", "max concurrent chunk requests", "4").option("--screenshots <n>", "number of keyframes to extract (video)", "6").option("--formats <list>", "output formats: srt,md,json (default: md)").option("--level <1|2|3>", "diarization level (1=separation, 2=consistent, 3=identify)", "2").option("--model <name>", "override transcription model").option("--reasoner <name>", "override text-reasoner model (default deepseek-chat)").option("--timestamped <provider>", "timestamped provider (assemblyai|whisper-groq|none)").option("--force", "force reprocess cached chunk outputs", false).option("--only-chunk <n>", "process only a specific chunk index (debug)").option("--save-intermediates", "save intermediates (default true)", true).option("--no-progress", "hide progress output").option("--no-llm-log", "disable per-call LLM logging to <intermediates>/llm-calls.jsonl").option("--log-level <level>", "debug | info | warn | error", "info");
2081
- program.parse();
2082
- var opts = program.opts();
2083
- var input = program.args[0];
2084
- if (!input) {
2085
- console.error("Error: input file is required.");
2086
- process.exit(1);
2087
- }
2088
- var passes = opts.passes?.split(",");
2089
- var level = parseInt(opts.level, 10);
2090
- transcribe({
2091
- input,
2092
- outputDir: opts.output,
2093
- // undefined → defaults to the input file's directory
2094
- intermediatesDir: opts.intermediates,
2095
- instructions: opts.instructions,
2096
- passes,
2097
- chunkDurationSec: parseInt(opts.chunkSeconds, 10),
2098
- chunkOverlapSec: parseInt(opts.overlapSeconds, 10),
2099
- concurrency: parseInt(opts.concurrency, 10),
2100
- screenshotCount: parseInt(opts.screenshots, 10),
2101
- formats: opts.formats ? opts.formats.split(",") : void 0,
2102
- // undefined → defaults to ["md"]
2103
- diarizationLevel: level,
2104
- model: opts.model,
2105
- reasoner: opts.reasoner,
2106
- timestampedProvider: opts.timestamped,
2107
- force: opts.force,
2108
- onlyChunk: opts.onlyChunk ? parseInt(opts.onlyChunk, 10) : void 0,
2109
- saveIntermediates: opts.saveIntermediates,
2110
- showProgress: opts.progress,
2111
- llmLog: opts.llmLog,
2112
- logLevel: opts.logLevel
2113
- }).then((result) => {
2114
- const segs = result.segments.length;
2115
- console.log(`Done. ${segs} segments.`);
2116
- }).catch((err) => {
2117
- const msg = err instanceof Error ? err.message : String(err);
2118
- console.error(`
4549
+ program.name("offmute-v2").description(
4550
+ "Diarized meeting transcription with multimodal LLMs + timestamped alignment."
4551
+ ).version(packageVersion);
4552
+ function buildTips(result, opts, input) {
4553
+ const tips = [];
4554
+ const genericSpeakers = result.speakers.filter(
4555
+ (sp) => !sp.name || /^Speaker [A-Z]$/.test(sp.name)
4556
+ );
4557
+ if (genericSpeakers.length > 0 && !opts.speakers) {
4558
+ tips.push(
4559
+ `${genericSpeakers.length} speaker(s) stayed generic \u2014 retcon instantly: offmute-v2 rename "${input}" "${genericSpeakers[0].id}=Name", or pass --speakers "Alice,Bob" next time`
4560
+ );
4561
+ }
4562
+ if (!opts.model && result.metadata.duration > 1500) {
4563
+ tips.push(
4564
+ "long file on the pro model \u2014 try --model gemini-3.5-flash for ~4\xD7 cheaper and faster (quality holds up well)"
4565
+ );
4566
+ }
4567
+ if (!opts.formats && !opts.summary) {
4568
+ tips.push("want a shareable page and action items? --formats md,html --summary");
4569
+ }
4570
+ if (!opts.instructions) {
4571
+ tips.push(
4572
+ 'nudge the ear with --instructions, e.g. "the host is Alice; spell it Xiao, not Shao"'
4573
+ );
4574
+ }
4575
+ return tips.slice(0, 2);
4576
+ }
4577
+ function errorHint(msg) {
4578
+ if (/Invalid data found|ffprobe exited/.test(msg))
4579
+ return "that file doesn't look like readable media \u2014 is it actually audio/video?";
4580
+ if (/not found in PATH|ffmpeg\/ffprobe/.test(msg))
4581
+ return "install ffmpeg first: brew install ffmpeg (macOS) or apt install ffmpeg";
4582
+ if (/API_KEY/.test(msg))
4583
+ return "run `offmute-v2 doctor` to see which keys are set and working";
4584
+ if (/fetch failed|ENOTFOUND|ECONNRESET/.test(msg))
4585
+ return "network hiccup \u2014 just re-run; everything finished so far is cached";
4586
+ if (/Input file not found/.test(msg))
4587
+ return "check the path (tab-completion is your friend)";
4588
+ return void 0;
4589
+ }
4590
+ async function runTranscribe(input, opts) {
4591
+ const passes = opts.passes?.split(",");
4592
+ let level = parseInt(opts.level, 10);
4593
+ if (opts.speakers && level < 3) level = 3;
4594
+ const pretty = process.stdout.isTTY === true && opts.progress && opts.logLevel !== "debug";
4595
+ configureUi({ enabled: pretty });
4596
+ banner(packageVersion, basename6(input));
4597
+ if (pretty) maybeFirstRunCheck(packageVersion);
4598
+ const t0 = Date.now();
4599
+ const result = await transcribe({
4600
+ input,
4601
+ outputDir: opts.output,
4602
+ // undefined → defaults to the input file's directory
4603
+ intermediatesDir: opts.intermediates,
4604
+ instructions: opts.instructions,
4605
+ passes,
4606
+ chunkDurationSec: parseInt(opts.chunkSeconds, 10),
4607
+ chunkOverlapSec: parseInt(opts.overlapSeconds, 10),
4608
+ concurrency: parseInt(opts.concurrency, 10),
4609
+ screenshotCount: parseInt(opts.screenshots, 10),
4610
+ formats: opts.formats ? opts.formats.split(",") : void 0,
4611
+ // undefined → defaults to ["md"]
4612
+ mdStyle: opts.mdStyle,
4613
+ summary: opts.summary,
4614
+ knownSpeakers: opts.speakers ? opts.speakers.split(",").map((s) => s.trim()).filter(Boolean) : void 0,
4615
+ diarizationLevel: level,
4616
+ identifyMode: opts.identify,
4617
+ model: opts.model,
4618
+ reasoner: opts.reasoner,
4619
+ timestampedProvider: opts.timestamped,
4620
+ force: opts.force,
4621
+ onlyChunk: opts.onlyChunk ? parseInt(opts.onlyChunk, 10) : void 0,
4622
+ saveIntermediates: opts.saveIntermediates,
4623
+ showProgress: opts.progress,
4624
+ llmLog: opts.llmLog,
4625
+ logLevel: opts.logLevel
4626
+ });
4627
+ if (uiActive()) {
4628
+ finishUi();
4629
+ const base = basename6(input).replace(/\.[^.]+$/, "");
4630
+ const outDir = resolve4(opts.output ?? (dirname5(resolve4(input)) || "."));
4631
+ const formats = opts.formats ? opts.formats.split(",") : ["md"];
4632
+ const files = formats.map((f) => join5(outDir, `${base}.${f.trim()}`));
4633
+ if (opts.summary) files.push(join5(outDir, `${base}.summary.md`));
4634
+ const cost = result.metadata.cost ? ` \xB7 ~$${result.metadata.cost.actualUsd.toFixed(2)}` : "";
4635
+ const wall = result.metadata.wallMs ? ` \xB7 ${formatDuration(Math.round(result.metadata.wallMs / 1e3))}` : "";
4636
+ outputsBlock(
4637
+ files,
4638
+ `${result.segments.length} segments \xB7 ${result.speakers.length} speakers \xB7 ${formatDuration(Math.round(result.metadata.duration))} of audio${cost}${wall}`
4639
+ );
4640
+ tipsBlock(buildTips(result, opts, input));
4641
+ starFooter();
4642
+ process.stdout.write("\n");
4643
+ } else {
4644
+ console.log(`Done. ${result.segments.length} segments.`);
4645
+ }
4646
+ if (opts.notify && Date.now() - t0 > 12e4) {
4647
+ const cost = result.metadata.cost ? ` \xB7 ~$${result.metadata.cost.actualUsd.toFixed(2)}` : "";
4648
+ notify(
4649
+ "offmute-v2",
4650
+ `${basename6(input)} transcribed \u2014 ${result.segments.length} segments${cost}`
4651
+ );
4652
+ }
4653
+ }
4654
+ function addTranscribeOptions(cmd) {
4655
+ return cmd.option("-o, --output <dir>", "output directory (default: next to the input file)").option(
4656
+ "-i, --intermediates <dir>",
4657
+ "intermediates directory (default: auto-derived per input file so caches never collide)"
4658
+ ).option("--instructions <text>", "custom instructions for the LLM").option("--passes <list>", "comma-separated passes to run").option("--chunk-seconds <n>", "chunk duration in seconds", "600").option("--overlap-seconds <n>", "chunk overlap in seconds", "60").option("--concurrency <n>", "max concurrent chunk requests", "4").option("--screenshots <n>", "number of keyframes to extract (video)", "6").option("--formats <list>", "output formats: srt,md,txt,html,json (default: md)").option(
4659
+ "--md-style <style>",
4660
+ "markdown layout: merged (paragraphs) | turns",
4661
+ "merged"
4662
+ ).option(
4663
+ "--summary",
4664
+ "also write <name>.summary.md (TL;DR, decisions, action items)",
4665
+ false
4666
+ ).option(
4667
+ "--speakers <names>",
4668
+ "known speaker names, comma-separated (implies --level 3)"
4669
+ ).option(
4670
+ "--level <1|2|3>",
4671
+ "diarization level (1=separation, 2=anonymous consistent, 3=verified names)",
4672
+ "3"
4673
+ ).option(
4674
+ "--identify <mode>",
4675
+ "speaker naming: dual (two reasoners, default) | single",
4676
+ "dual"
4677
+ ).option("--model <name>", "override transcription model").option("--reasoner <name>", "override text-reasoner model (default deepseek-chat)").option(
4678
+ "--timestamped <provider>",
4679
+ "timestamped provider (assemblyai|elevenlabs|whisper-groq|none)"
4680
+ ).option("--force", "force reprocess cached chunk outputs", false).option("--only-chunk <n>", "process only a specific chunk index (debug)").option("--save-intermediates", "save intermediates (default true)", true).option("--no-progress", "hide progress output").option(
4681
+ "--no-llm-log",
4682
+ "disable per-call LLM logging to <intermediates>/llm-calls.jsonl"
4683
+ ).option("--no-notify", "skip the OS notification after long runs").option("--log-level <level>", "debug | info | warn | error", "info");
4684
+ }
4685
+ addTranscribeOptions(
4686
+ program.command("transcribe <input>", { isDefault: true }).description("transcribe a video/audio file (default command)")
4687
+ ).action(async (input, opts) => {
4688
+ try {
4689
+ await runTranscribe(input, opts);
4690
+ } catch (err) {
4691
+ const msg = err instanceof Error ? err.message : String(err);
4692
+ if (uiActive()) {
4693
+ errorBlock(msg, errorHint(msg));
4694
+ finishUi();
4695
+ } else {
4696
+ console.error(`
2119
4697
  \u2717 ${msg}`);
2120
- if (opts.logLevel === "debug" || process.env.OFFMUTE_DEBUG) {
2121
- console.error(err instanceof Error ? err.stack : err);
4698
+ const hint = errorHint(msg);
4699
+ if (hint) console.error(` ${hint}`);
4700
+ }
4701
+ if (opts.logLevel === "debug" || process.env.OFFMUTE_DEBUG) {
4702
+ console.error(err instanceof Error ? err.stack : err);
4703
+ }
4704
+ process.exit(1);
2122
4705
  }
2123
- process.exit(1);
2124
4706
  });
4707
+ program.command("models").description("list model presets per role and what your keys unlock").action(runModels);
4708
+ program.command("doctor").description("check ffmpeg, API keys, and provider reachability").action(runDoctor);
4709
+ program.command("stats").description("lifetime stats: hours processed, characters, cost by model").action(runStats);
4710
+ program.command("watch <dir>").description("daemon mode: watch a folder, transcribe media files as they appear").option("--match <exts>", "comma-separated extensions to watch (default: common media)").option("--jobs <n>", "max concurrent transcription jobs", "1").option("--no-backlog", "skip files already in the folder at startup").option("-o, --output <dir>", "write transcripts here (default: next to each input)").option("--formats <list>", "output formats: srt,md,txt,html,json (default: md)").option("--md-style <style>", "markdown layout: merged | turns", "merged").option("--summary", "also write a summary per file", false).option("--instructions <text>", "custom instructions for the LLM").option(
4711
+ "--speakers <names>",
4712
+ "known speaker names, comma-separated (implies --level 3)"
4713
+ ).option("--level <1|2|3>", "diarization level", "3").option("--identify <mode>", "speaker naming: dual | single", "dual").option("--model <name>", "override transcription model").option("--reasoner <name>", "override text-reasoner model").option("--timestamped <provider>", "assemblyai|elevenlabs|whisper-groq|none").action(
4714
+ async (dir, opts) => {
4715
+ let level = parseInt(opts.level, 10);
4716
+ if (opts.speakers && level < 3) level = 3;
4717
+ await runWatch(dir, {
4718
+ match: opts.match,
4719
+ jobs: opts.jobs,
4720
+ backlog: opts.backlog,
4721
+ output: opts.output,
4722
+ pipeline: {
4723
+ formats: opts.formats ? opts.formats.split(",") : void 0,
4724
+ mdStyle: opts.mdStyle,
4725
+ summary: opts.summary,
4726
+ instructions: opts.instructions,
4727
+ knownSpeakers: opts.speakers ? opts.speakers.split(",").map((s) => s.trim()).filter(Boolean) : void 0,
4728
+ diarizationLevel: level,
4729
+ identifyMode: opts.identify,
4730
+ model: opts.model,
4731
+ reasoner: opts.reasoner,
4732
+ timestampedProvider: opts.timestamped
4733
+ }
4734
+ });
4735
+ }
4736
+ );
4737
+ program.command("rename <media-or-json> <mappings...>").description(
4738
+ 'retcon speaker names without reprocessing, e.g. rename meeting.mp4 "Speaker B=Ang Li" (uses the run cache)'
4739
+ ).option("--formats <list>", "formats to regenerate", "md").option("--md-style <style>", "markdown layout: merged | turns", "merged").option(
4740
+ "-o, --output <dir>",
4741
+ "where to write regenerated files (default: next to the input)"
4742
+ ).option("-i, --intermediates <dir>", "cache dir override (if the run used -i)").action(
4743
+ (path, mappings, opts) => {
4744
+ runRename(path, mappings, opts);
4745
+ }
4746
+ );
4747
+ program.parse();
2125
4748
  //# sourceMappingURL=cli.js.map