offmute-v2 0.0.4 → 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,16 +2,16 @@
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 dirname3, 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";
14
- import { basename, resolve } from "path";
14
+ import { basename, dirname, resolve } from "path";
15
15
  import { statSync } from "fs";
16
16
  import { tmpdir } from "os";
17
17
  var DEFAULT_PASSES = [
@@ -27,12 +27,14 @@ var MODELS = {
27
27
  gemini25Pro: "gemini-2.5-pro",
28
28
  gemini25Flash: "gemini-2.5-flash",
29
29
  gemini3Pro: "gemini-3-pro-preview",
30
+ gemini31Pro: "gemini-3.1-pro-preview",
31
+ geminiFlashLatest: "gemini-flash-latest",
30
32
  deepseek: "deepseek-chat",
31
33
  deepseekReasoner: "deepseek-reasoner",
32
34
  gpt4o: "gpt-4o",
33
35
  claudeSonnet: "claude-sonnet-4-5"
34
36
  };
35
- var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini25Flash;
37
+ var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini31Pro;
36
38
  var DEFAULT_REASONER_MODEL = MODELS.deepseek;
37
39
  function resolveKeys(injected) {
38
40
  const env = process.env;
@@ -43,19 +45,23 @@ function resolveKeys(injected) {
43
45
  deepseek: injected?.deepseek || env.DEEPSEEK_API_KEY,
44
46
  groq: injected?.groq || env.GROQ_API_KEY,
45
47
  assemblyai: injected?.assemblyai || env.ASSEMBLYAI_API_KEY,
46
- 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
47
52
  };
48
53
  }
49
- function resolveOptions(opts2) {
54
+ function resolveOptions(opts) {
50
55
  return {
51
- input: opts2.input,
52
- outputDir: opts2.outputDir,
53
- intermediatesDir: opts2.intermediatesDir ?? deriveIntermediatesDir(opts2.input),
54
- instructions: opts2.instructions,
55
- knownSpeakers: opts2.knownSpeakers,
56
+ input: opts.input,
57
+ // Default: write next to the input file (e.g. meeting.md beside meeting.mp4) — no ./output folder.
58
+ outputDir: opts.outputDir ?? dirname(resolve(opts.input)),
59
+ intermediatesDir: opts.intermediatesDir ?? deriveIntermediatesDir(opts.input),
60
+ instructions: opts.instructions,
61
+ knownSpeakers: opts.knownSpeakers,
56
62
  passes: (() => {
57
- const p = opts2.passes ?? DEFAULT_PASSES;
58
- if ((opts2.diarizationLevel ?? 2) >= 3 && !p.includes("identify")) {
63
+ const p = opts.passes ?? DEFAULT_PASSES;
64
+ if ((opts.diarizationLevel ?? 3) >= 3 && !p.includes("identify")) {
59
65
  const out = [...p];
60
66
  const fi = out.indexOf("finalize");
61
67
  if (fi >= 0) out.splice(fi, 0, "identify");
@@ -64,44 +70,51 @@ function resolveOptions(opts2) {
64
70
  }
65
71
  return p;
66
72
  })(),
67
- chunkDurationSec: opts2.chunkDurationSec ?? 600,
68
- chunkOverlapSec: opts2.chunkOverlapSec ?? 60,
69
- screenshotCount: opts2.screenshotCount ?? 6,
70
- concurrency: opts2.concurrency ?? 4,
71
- saveIntermediates: opts2.saveIntermediates ?? true,
72
- formats: opts2.formats ?? ["srt", "md", "json"],
73
- diarizationLevel: opts2.diarizationLevel ?? 2,
74
- apiKeys: opts2.apiKeys,
75
- model: opts2.model,
76
- reasoner: opts2.reasoner,
77
- timestampedProvider: opts2.timestampedProvider,
78
- force: opts2.force ?? false,
79
- onlyChunk: opts2.onlyChunk,
80
- showProgress: opts2.showProgress ?? true,
81
- llmLog: opts2.llmLog ?? true,
82
- 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
83
96
  };
84
97
  }
85
- function deriveIntermediatesDir(input2) {
86
- const abs = resolve(input2);
98
+ function deriveIntermediatesDir(input) {
99
+ const abs = resolve(input);
87
100
  const hash = createHash("sha1").update(abs).digest("hex").slice(0, 8);
88
- const base = basename(input2, extOf(input2)) || "input";
101
+ const base = basename(input, extOf(input)) || "input";
89
102
  return `${tmpdir()}/offmute-v2-${base}-${hash}`;
90
103
  }
91
104
  function extOf(p) {
92
105
  const i = p.lastIndexOf(".");
93
106
  return i >= 0 ? p.slice(i) : "";
94
107
  }
95
- function inputSignature(input2) {
108
+ function inputSignature(input) {
96
109
  let size = 0;
97
110
  let mtime = 0;
98
111
  try {
99
- const st = statSync(input2);
112
+ const st = statSync(input);
100
113
  size = st.size;
101
114
  mtime = Math.floor(st.mtimeMs);
102
115
  } catch {
103
116
  }
104
- return createHash("sha1").update(`${resolve(input2)}|${size}|${mtime}`).digest("hex");
117
+ return createHash("sha1").update(`${resolve(input)}|${size}|${mtime}`).digest("hex");
105
118
  }
106
119
  function configSignature(o) {
107
120
  const relevant = {
@@ -112,7 +125,7 @@ function configSignature(o) {
112
125
  chunkDurationSec: o.chunkDurationSec ?? 600,
113
126
  chunkOverlapSec: o.chunkOverlapSec ?? 60,
114
127
  screenshotCount: o.screenshotCount ?? 6,
115
- diarizationLevel: o.diarizationLevel ?? 2,
128
+ diarizationLevel: o.diarizationLevel ?? 3,
116
129
  timestampedProvider: o.timestampedProvider ?? "assemblyai"
117
130
  };
118
131
  return createHash("sha1").update(JSON.stringify(relevant)).digest("hex");
@@ -147,17 +160,19 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
147
160
  // src/utils/logger.ts
148
161
  var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
149
162
  var currentLevel = "info";
150
- function setLogLevel(level2) {
151
- currentLevel = level2;
163
+ var sink = null;
164
+ function setLogLevel(level) {
165
+ currentLevel = level;
152
166
  }
153
- function log(level2, msg, extra) {
154
- if (LEVELS[level2] < LEVELS[currentLevel]) return;
155
- const ts = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
156
- 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)}`;
157
172
  if (extra !== void 0) {
158
- console[level2 === "error" ? "error" : "log"](prefix, msg, extra);
173
+ console[level === "error" ? "error" : "log"](prefix, msg, extra);
159
174
  } else {
160
- console[level2 === "error" ? "error" : "log"](prefix, msg);
175
+ console[level === "error" ? "error" : "log"](prefix, msg);
161
176
  }
162
177
  }
163
178
  var logger = {
@@ -165,15 +180,18 @@ var logger = {
165
180
  info: (msg, extra) => log("info", msg, extra),
166
181
  warn: (msg, extra) => log("warn", msg, extra),
167
182
  error: (msg, extra) => log("error", msg, extra),
168
- setLevel: setLogLevel
183
+ setLevel: setLogLevel,
184
+ setSink: (s) => {
185
+ sink = s;
186
+ }
169
187
  };
170
188
 
171
189
  // src/audio/ffmpeg.ts
172
190
  import { spawn } from "child_process";
173
191
  import { mkdir } from "fs/promises";
174
- import { dirname } from "path";
192
+ import { dirname as dirname2 } from "path";
175
193
  function run(cmd, args, _opts = {}) {
176
- return new Promise((resolve3, reject) => {
194
+ return new Promise((resolve5, reject) => {
177
195
  const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
178
196
  let stdout = "";
179
197
  let stderr = "";
@@ -181,7 +199,7 @@ function run(cmd, args, _opts = {}) {
181
199
  child.stderr.on("data", (d) => stderr += d.toString());
182
200
  child.on("error", reject);
183
201
  child.on("close", (code) => {
184
- if (code === 0) resolve3({ stdout, stderr });
202
+ if (code === 0) resolve5({ stdout, stderr });
185
203
  else {
186
204
  const tail = stderr.slice(-800);
187
205
  reject(new Error(`${cmd} exited ${code}: ${tail}`));
@@ -198,7 +216,7 @@ async function checkFfmpeg() {
198
216
  return false;
199
217
  }
200
218
  }
201
- async function probe(input2) {
219
+ async function probe(input) {
202
220
  const { stdout } = await run("ffprobe", [
203
221
  "-v",
204
222
  "error",
@@ -206,7 +224,7 @@ async function probe(input2) {
206
224
  "-show_streams",
207
225
  "-of",
208
226
  "json",
209
- input2
227
+ input
210
228
  ]);
211
229
  const data = JSON.parse(stdout);
212
230
  const streams = data.streams || [];
@@ -225,48 +243,48 @@ async function probe(input2) {
225
243
  sizeBytes: parseInt(data.format?.size || "0", 10) || void 0
226
244
  };
227
245
  }
228
- function audioArgs(opts2) {
229
- const sampleRate = opts2.sampleRate ?? 16e3;
230
- const channels = opts2.channels ?? 1;
231
- 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";
232
250
  const common = ["-vn", "-ac", String(channels), "-ar", String(sampleRate)];
233
251
  switch (format) {
234
252
  case "flac":
235
253
  return [...common, "-c:a", "flac"];
236
254
  case "mp3":
237
- return [...common, "-c:a", "libmp3lame", "-b:a", opts2.bitrate ?? "64k"];
255
+ return [...common, "-c:a", "libmp3lame", "-b:a", opts.bitrate ?? "64k"];
238
256
  case "opus":
239
- return [...common, "-c:a", "libopus", "-b:a", opts2.bitrate ?? "48k"];
257
+ return [...common, "-c:a", "libopus", "-b:a", opts.bitrate ?? "48k"];
240
258
  case "wav":
241
259
  return [...common, "-c:a", "pcm_s16le"];
242
260
  }
243
261
  }
244
- async function extractAudio(input2, output, opts2 = {}) {
245
- await mkdir(dirname(output), { recursive: true });
246
- const args = ["-y", "-i", input2, ...audioArgs(opts2), output];
262
+ async function extractAudio(input, output, opts = {}) {
263
+ await mkdir(dirname2(output), { recursive: true });
264
+ const args = ["-y", "-i", input, ...audioArgs(opts), output];
247
265
  await run("ffmpeg", args);
248
266
  }
249
- async function extractChunk(input2, output, startSec, endSec, opts2 = {}) {
250
- await mkdir(dirname(output), { recursive: true });
267
+ async function extractChunk(input, output, startSec, endSec, opts = {}) {
268
+ await mkdir(dirname2(output), { recursive: true });
251
269
  const duration = Math.max(0, endSec - startSec);
252
270
  const args = [
253
271
  "-y",
254
272
  "-ss",
255
273
  startSec.toFixed(3),
256
274
  "-i",
257
- input2,
275
+ input,
258
276
  "-t",
259
277
  duration.toFixed(3),
260
- ...audioArgs(opts2),
278
+ ...audioArgs(opts),
261
279
  output
262
280
  ];
263
281
  await run("ffmpeg", args);
264
282
  }
265
- async function getSceneChangeTimes(input2, threshold) {
283
+ async function getSceneChangeTimes(input, threshold) {
266
284
  try {
267
285
  const { stderr } = await run("ffmpeg", [
268
286
  "-i",
269
- input2,
287
+ input,
270
288
  "-vf",
271
289
  `select='gt(scene,${threshold})',showinfo`,
272
290
  "-vsync",
@@ -285,12 +303,12 @@ async function getSceneChangeTimes(input2, threshold) {
285
303
  return [];
286
304
  }
287
305
  }
288
- async function extractKeyframes(input2, outputDir, count, opts2 = {}) {
306
+ async function extractKeyframes(input, outputDir, count, opts = {}) {
289
307
  await mkdir(outputDir, { recursive: true });
290
- const width = opts2.width ?? 1280;
291
- const { duration } = await probe(input2);
308
+ const width = opts.width ?? 1280;
309
+ const { duration } = await probe(input);
292
310
  if (!duration) return [];
293
- const sceneTimes = await getSceneChangeTimes(input2, opts2.sceneThreshold ?? 0.3);
311
+ const sceneTimes = await getSceneChangeTimes(input, opts.sceneThreshold ?? 0.3);
294
312
  const times = [];
295
313
  if (sceneTimes.length >= count) {
296
314
  const step = sceneTimes.length / count;
@@ -317,7 +335,7 @@ async function extractKeyframes(input2, outputDir, count, opts2 = {}) {
317
335
  "-ss",
318
336
  t.toFixed(3),
319
337
  "-i",
320
- input2,
338
+ input,
321
339
  "-frames:v",
322
340
  "1",
323
341
  "-vf",
@@ -330,12 +348,12 @@ async function extractKeyframes(input2, outputDir, count, opts2 = {}) {
330
348
  }
331
349
  return out;
332
350
  }
333
- async function detectSilence(input2, opts2 = {}) {
334
- const noise = opts2.noiseDb ?? -30;
335
- 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;
336
354
  const { stderr } = await run("ffmpeg", [
337
355
  "-i",
338
- input2,
356
+ input,
339
357
  "-af",
340
358
  `silencedetect=noise=${noise}dB:d=${minDur}`,
341
359
  "-f",
@@ -378,10 +396,35 @@ import { basename as basename2 } from "path";
378
396
  // src/providers/llm-log.ts
379
397
  import { appendFileSync } from "fs";
380
398
  var logPath = null;
399
+ var usageRecords = /* @__PURE__ */ new Map();
381
400
  function setLlmLogPath(path) {
382
401
  logPath = path ?? null;
383
402
  }
403
+ function resetLlmUsage() {
404
+ usageRecords = /* @__PURE__ */ new Map();
405
+ }
406
+ function getLlmUsage() {
407
+ return [...usageRecords.values()];
408
+ }
384
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
+ }
385
428
  if (!logPath) return;
386
429
  try {
387
430
  appendFileSync(logPath, JSON.stringify(entry) + "\n", { encoding: "utf-8" });
@@ -389,7 +432,39 @@ function logLlmCall(entry) {
389
432
  }
390
433
  }
391
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
+
392
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
+ };
393
468
  var MIME_BY_EXT = {
394
469
  ".flac": "audio/flac",
395
470
  ".mp3": "audio/mp3",
@@ -431,11 +506,16 @@ var GeminiClient = class {
431
506
  constructor(apiKey) {
432
507
  this.ai = new GoogleGenAI({ apiKey });
433
508
  }
434
- /** 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. */
435
512
  async upload(path, mimeType) {
436
513
  const mt = mimeType || detectMime(path);
437
514
  logger.debug(`[gemini] uploading ${basename2(path)} (${mt})...`);
438
- 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
+ );
439
519
  let tries = 0;
440
520
  while (file.state === "PROCESSING" && tries < 120) {
441
521
  await sleep(2e3);
@@ -449,7 +529,7 @@ var GeminiClient = class {
449
529
  return file;
450
530
  }
451
531
  /** Generate content from a prompt + uploaded files. */
452
- async generate(model, prompt, files, opts2 = {}) {
532
+ async generate(model, prompt, files, opts = {}) {
453
533
  const {
454
534
  maxRetries = 3,
455
535
  retryDelayMs = 2e3,
@@ -457,7 +537,7 @@ var GeminiClient = class {
457
537
  maxOutputTokens = 65536,
458
538
  responseSchema,
459
539
  systemInstruction
460
- } = opts2;
540
+ } = opts;
461
541
  const uploaded = [];
462
542
  try {
463
543
  for (const f of files) {
@@ -501,8 +581,8 @@ var GeminiClient = class {
501
581
  ts: new Date(t0).toISOString(),
502
582
  provider: "gemini",
503
583
  model,
504
- kind: opts2.logKind,
505
- chunk: opts2.logChunk,
584
+ kind: opts.logKind,
585
+ chunk: opts.logChunk,
506
586
  prompt,
507
587
  response: text,
508
588
  usage: result.usage,
@@ -514,16 +594,20 @@ var GeminiClient = class {
514
594
  lastError = err instanceof Error ? err.message : String(err);
515
595
  if (config.thinkingConfig && isThinkingConfigError(lastError)) {
516
596
  delete config.thinkingConfig;
517
- 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
+ );
518
600
  continue;
519
601
  }
520
- logger.warn(`[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`);
602
+ logger.warn(
603
+ `[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`
604
+ );
521
605
  logLlmCall({
522
606
  ts: new Date(t0).toISOString(),
523
607
  provider: "gemini",
524
608
  model,
525
- kind: opts2.logKind,
526
- chunk: opts2.logChunk,
609
+ kind: opts.logKind,
610
+ chunk: opts.logChunk,
527
611
  prompt,
528
612
  response: "",
529
613
  durationMs: Date.now() - t0,
@@ -533,15 +617,19 @@ var GeminiClient = class {
533
617
  if (attempt < maxRetries - 1) await sleep(retryDelayMs * (attempt + 1));
534
618
  }
535
619
  }
536
- 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
+ };
537
625
  } finally {
538
626
  await this.cleanup(uploaded);
539
627
  }
540
628
  }
541
629
  /** Generate and parse JSON (requires responseSchema in opts). */
542
- async generateJson(model, prompt, files, responseSchema, opts2 = {}) {
630
+ async generateJson(model, prompt, files, responseSchema, opts = {}) {
543
631
  const result = await this.generate(model, prompt, files, {
544
- ...opts2,
632
+ ...opts,
545
633
  responseSchema
546
634
  });
547
635
  if (result.error || !result.text) {
@@ -578,7 +666,7 @@ import { AssemblyAI } from "assemblyai";
578
666
  import { createHash as createHash2 } from "crypto";
579
667
  import { readFile, mkdir as mkdir2, writeFile } from "fs/promises";
580
668
  import { existsSync } from "fs";
581
- import { dirname as dirname2 } from "path";
669
+ import { dirname as dirname3 } from "path";
582
670
  async function fileHash(path) {
583
671
  const buf = await readFile(path);
584
672
  return createHash2("sha256").update(buf).digest("hex").slice(0, 24);
@@ -586,11 +674,11 @@ async function fileHash(path) {
586
674
  var AssemblyAIProvider = class {
587
675
  client;
588
676
  cacheDir;
589
- constructor(opts2) {
590
- this.client = new AssemblyAI({ apiKey: opts2.apiKey });
591
- this.cacheDir = opts2.cacheDir;
592
- this.speechModel = opts2.speechModel ?? "universal";
593
- 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;
594
682
  }
595
683
  speechModel;
596
684
  speakersExpected;
@@ -603,7 +691,10 @@ var AssemblyAIProvider = class {
603
691
  return JSON.parse(await readFile(cachePath, "utf-8"));
604
692
  }
605
693
  logger.info(`[assemblyai] uploading ${filePath}...`);
606
- const uploadUrl = await this.client.files.upload(filePath);
694
+ const uploadUrl = await withRetry(
695
+ "assemblyai upload",
696
+ () => this.client.files.upload(filePath)
697
+ );
607
698
  logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
608
699
  const params = {
609
700
  audio: uploadUrl,
@@ -611,13 +702,16 @@ var AssemblyAIProvider = class {
611
702
  speech_model: this.speechModel
612
703
  };
613
704
  if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
614
- const transcript = await this.client.transcripts.transcribe(params);
705
+ const transcript = await withRetry(
706
+ "assemblyai transcribe",
707
+ () => this.client.transcripts.transcribe(params)
708
+ );
615
709
  if (transcript.status === "error") {
616
710
  throw new Error(`AssemblyAI error: ${transcript.error}`);
617
711
  }
618
712
  const result = this.mapTranscript(transcript, hash);
619
713
  if (cachePath) {
620
- await mkdir2(dirname2(cachePath), { recursive: true });
714
+ await mkdir2(dirname3(cachePath), { recursive: true });
621
715
  await writeFile(cachePath, JSON.stringify(result, null, 2));
622
716
  }
623
717
  logger.info(
@@ -715,9 +809,315 @@ var WhisperGroqClient = class {
715
809
  }
716
810
  };
717
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
+
718
1117
  // src/transcribe/describe.ts
719
- function descriptionPrompt(fileName, instructions) {
720
- 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})` : ""}.
721
1121
 
722
1122
  Respond in TWO sections, clearly separated by a line containing only "---":
723
1123
 
@@ -727,17 +1127,24 @@ A short paragraph: what kind of recording this is, the setting, the main topics,
727
1127
  ROSTER
728
1128
  A bulleted speaker roster. For each distinct speaker you can identify, give:
729
1129
  - A short label to use consistently (a name/role if you can infer it, e.g. "Presenter (Hrishi)", else "Speaker A").
730
- - 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.
731
1131
  List the people you can distinguish. Do not invent names you didn't hear. If only one person speaks, say so.
732
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
+
733
1135
  File: ${fileName}`;
734
1136
  }
735
- async function describeMeeting(client, model, files, fileName, instructions) {
736
- const res = await client.generate(model, descriptionPrompt(fileName, instructions), files, {
737
- temperature: 0.2,
738
- maxRetries: 3,
739
- logKind: "describe"
740
- });
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
+ );
741
1148
  const text = res.text || "";
742
1149
  const parts = text.split(/\n---\n|\n\s*---\s*\n/);
743
1150
  const description = parts[0]?.trim() || text.trim();
@@ -754,14 +1161,23 @@ var TRANSCRIPT_SCHEMA = {
754
1161
  items: {
755
1162
  type: "OBJECT",
756
1163
  properties: {
757
- speaker: { type: "STRING", description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc." },
758
- 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
+ },
759
1172
  end: { type: "STRING", description: "Relative end time as mm:ss" },
760
- 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
+ },
761
1177
  tone: {
762
1178
  type: "ARRAY",
763
1179
  items: { type: "STRING" },
764
- 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."
765
1181
  }
766
1182
  },
767
1183
  required: ["speaker", "start", "end", "text"]
@@ -776,19 +1192,40 @@ function transcriptionPrompt(ctx) {
776
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.`
777
1193
  );
778
1194
  parts.push("");
779
- 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
+ );
780
1198
  parts.push("");
781
1199
  parts.push("For each segment provide:");
782
- 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.");
783
- 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.");
784
- parts.push("- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase.");
785
- 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
+ );
786
1212
  parts.push("");
787
1213
  parts.push("Rules:");
788
- parts.push("- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing.");
789
- parts.push("- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap.");
790
- parts.push("- Do not invent content not present in the audio. If inaudible, write [inaudible].");
791
- 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
+ );
792
1229
  if (ctx.description) {
793
1230
  parts.push("");
794
1231
  parts.push("MEETING CONTEXT:");
@@ -796,12 +1233,20 @@ function transcriptionPrompt(ctx) {
796
1233
  }
797
1234
  if (ctx.roster) {
798
1235
  parts.push("");
799
- 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
+ );
800
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
+ );
801
1244
  }
802
1245
  if (ctx.previousTail) {
803
1246
  parts.push("");
804
- 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
+ );
805
1250
  parts.push(ctx.previousTail);
806
1251
  }
807
1252
  if (ctx.instructions) {
@@ -810,7 +1255,9 @@ function transcriptionPrompt(ctx) {
810
1255
  parts.push(ctx.instructions);
811
1256
  }
812
1257
  parts.push("");
813
- 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
+ );
814
1261
  return parts.join("\n");
815
1262
  }
816
1263
 
@@ -835,6 +1282,16 @@ function parseMmSs(timeStr) {
835
1282
  if (seconds < 0 || seconds >= 60) return null;
836
1283
  return minutes * 60 + seconds;
837
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
+ }
838
1295
 
839
1296
  // src/transcribe/llm-transcribe.ts
840
1297
  var MIN_SEGMENTS = 3;
@@ -858,7 +1315,9 @@ function parseLlmSegments(data, chunkOffsetSec) {
858
1315
  const end = toAbsolute(seg.end, chunkOffsetSec);
859
1316
  if (start === null || end === null || end < start) {
860
1317
  dropped++;
861
- 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
+ );
862
1321
  continue;
863
1322
  }
864
1323
  out.push({
@@ -875,19 +1334,34 @@ function parseLlmSegments(data, chunkOffsetSec) {
875
1334
  }
876
1335
  function validate(segments, chunkDuration) {
877
1336
  if (segments.length < MIN_SEGMENTS) {
878
- 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
+ };
879
1343
  }
880
1344
  const first = segments[0].startSec;
881
1345
  const last = segments[segments.length - 1].endSec;
882
1346
  const span = last - first;
883
1347
  const minSpan = chunkDuration * MIN_SPAN_RATIO;
884
1348
  if (span < minSpan) {
885
- 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
+ };
886
1355
  }
887
- 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
+ };
888
1362
  }
889
- async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts2) {
890
- const validationRetries = opts2.validationRetries ?? 1;
1363
+ async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
1364
+ const validationRetries = opts.validationRetries ?? 1;
891
1365
  const prompt = transcriptionPrompt(ctx);
892
1366
  let lastResult;
893
1367
  for (let attempt = 0; attempt <= validationRetries; attempt++) {
@@ -897,7 +1371,7 @@ async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opt
897
1371
  [{ path: chunkPath }],
898
1372
  TRANSCRIPT_SCHEMA,
899
1373
  {
900
- temperature: opts2.temperature ?? 0.2,
1374
+ temperature: opts.temperature ?? 0.2,
901
1375
  maxRetries: 3,
902
1376
  logKind: "transcribe",
903
1377
  logChunk: ctx.index - 1
@@ -908,22 +1382,35 @@ async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opt
908
1382
  segments: [],
909
1383
  raw: gen.raw,
910
1384
  usage: gen.usage,
911
- 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
+ },
912
1391
  error: gen.error
913
1392
  };
914
- 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
+ );
915
1396
  continue;
916
1397
  }
917
1398
  const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
918
- const v = validate(segments, opts2.chunkDurationSec);
1399
+ const v = validate(segments, opts.chunkDurationSec);
919
1400
  lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
920
1401
  if (v.isValid) {
921
- 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
+ );
922
1405
  return lastResult;
923
1406
  }
924
- 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
+ );
925
1410
  }
926
- 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
+ );
927
1414
  return lastResult;
928
1415
  }
929
1416
 
@@ -935,8 +1422,8 @@ function tokenize(text) {
935
1422
  const out = [];
936
1423
  for (const raw of text.split(/\s+/)) {
937
1424
  if (!raw) continue;
938
- const norm = normalize(raw);
939
- if (norm) out.push({ original: raw, norm });
1425
+ const norm2 = normalize(raw);
1426
+ if (norm2) out.push({ original: raw, norm: norm2 });
940
1427
  }
941
1428
  return out;
942
1429
  }
@@ -1060,7 +1547,11 @@ function transferTiming(llm, asr, ops) {
1060
1547
  for (const op of ops) {
1061
1548
  if (op.type === "match" || op.type === "substitute") {
1062
1549
  const a = asr[op.asr];
1063
- 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
+ };
1064
1555
  }
1065
1556
  }
1066
1557
  for (let k = 0; k < times.length; k++) {
@@ -1098,9 +1589,9 @@ function transferTiming(llm, asr, ops) {
1098
1589
  }
1099
1590
  return times;
1100
1591
  }
1101
- function alignSegments(llmSegments, asrWords, opts2 = {}) {
1102
- const confThreshold = opts2.confidenceThreshold ?? 0.5;
1103
- const margin = opts2.timeMarginSec ?? 0;
1592
+ function alignSegments(llmSegments, asrWords, opts = {}) {
1593
+ const confThreshold = opts.confidenceThreshold ?? 0.5;
1594
+ const margin = opts.timeMarginSec ?? 0;
1104
1595
  const sorted = [...llmSegments].map((s, i) => ({ s, i })).sort((a, b) => a.s.startSec - b.s.startSec);
1105
1596
  const flat = [];
1106
1597
  const segRanges = [];
@@ -1229,7 +1720,12 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
1229
1720
  tone: [],
1230
1721
  confidence: 0,
1231
1722
  timingSource: "timestamped",
1232
- 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
+ })),
1233
1729
  sourceIndex: -1
1234
1730
  });
1235
1731
  }
@@ -1242,10 +1738,21 @@ function overlap(s1, e1, s2, e2) {
1242
1738
  return Math.max(0, Math.min(e1, e2) - Math.max(s1, s2));
1243
1739
  }
1244
1740
  function isGenericLabel(label) {
1245
- 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
+ );
1246
1744
  }
1247
- function assignGlobalSpeakers(segments, asrUtterances, opts2 = {}) {
1248
- const hasDiarization = opts2.hasDiarization ?? true;
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;
1752
+ }
1753
+ var MAX_MERGE_TRANSITIONS = 3;
1754
+ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
1755
+ const hasDiarization = opts.hasDiarization ?? true;
1249
1756
  const out = segments.map((seg) => ({ seg, asrSpeaker: "" }));
1250
1757
  const labelVotes = {};
1251
1758
  const asrDuration = {};
@@ -1295,7 +1802,18 @@ function assignGlobalSpeakers(segments, asrUtterances, opts2 = {}) {
1295
1802
  const label = dominantLabel[asrSp] ?? asrSp;
1296
1803
  let groupId;
1297
1804
  if (!isGenericLabel(label)) {
1298
- 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
+ }
1299
1817
  }
1300
1818
  if (!groupId) {
1301
1819
  groupId = asrSp;
@@ -1305,15 +1823,24 @@ function assignGlobalSpeakers(segments, asrUtterances, opts2 = {}) {
1305
1823
  groupTalk[groupId] = (groupTalk[groupId] ?? 0) + (asrDuration[asrSp] ?? 0);
1306
1824
  (groupAsrVoices[groupId] ??= []).push(asrSp);
1307
1825
  }
1308
- 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
+ );
1309
1829
  const groupToGlobal = {};
1310
1830
  groupsByTalk.forEach((g, i) => {
1311
1831
  groupToGlobal[g] = `Speaker ${String.fromCharCode(65 + i)}`;
1312
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
+ }
1313
1839
  const displayNames = {};
1314
1840
  for (const g of groupsByTalk) {
1315
1841
  const label = groupLabel[g];
1316
- 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;
1317
1844
  }
1318
1845
  const llmLabelToAsr = {};
1319
1846
  for (const o of out) {
@@ -1347,6 +1874,111 @@ function assignGlobalSpeakers(segments, asrUtterances, opts2 = {}) {
1347
1874
  return { segments: updated, speakers, displayNames, llmLabelToAsr };
1348
1875
  }
1349
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
+
1350
1982
  // src/providers/openai-compat.ts
1351
1983
  var PROVIDER_BASE = {
1352
1984
  deepseek: "https://api.deepseek.com/v1",
@@ -1368,18 +2000,21 @@ var OpenAICompatClient = class _OpenAICompatClient {
1368
2000
  const base = PROVIDER_BASE[provider] ?? provider;
1369
2001
  return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
1370
2002
  }
1371
- async chat(model, messages, opts2 = {}) {
2003
+ async chat(model, messages, opts = {}) {
1372
2004
  const m = model ?? this.defaultModel;
1373
- const maxRetries = opts2.maxRetries ?? 2;
2005
+ const maxRetries = opts.maxRetries ?? 5;
1374
2006
  const body = {
1375
2007
  model: m,
1376
2008
  messages,
1377
- temperature: opts2.temperature ?? 0.2
2009
+ temperature: opts.temperature ?? 0.2
1378
2010
  };
1379
- if (opts2.maxTokens) body.max_tokens = opts2.maxTokens;
1380
- if (opts2.responseJson) {
2011
+ if (opts.maxTokens) body.max_tokens = opts.maxTokens;
2012
+ if (opts.responseJson) {
1381
2013
  body.response_format = { type: "json_object" };
1382
2014
  }
2015
+ if (this.providerName === "gemini") {
2016
+ body.reasoning_effort = "low";
2017
+ }
1383
2018
  let lastError;
1384
2019
  const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
1385
2020
  for (let attempt = 0; attempt < maxRetries; attempt++) {
@@ -1407,7 +2042,7 @@ var OpenAICompatClient = class _OpenAICompatClient {
1407
2042
  ts: new Date(t0).toISOString(),
1408
2043
  provider: this.providerName,
1409
2044
  model: m,
1410
- kind: opts2.logKind,
2045
+ kind: opts.logKind,
1411
2046
  prompt: promptStr,
1412
2047
  response: text,
1413
2048
  usage,
@@ -1417,72 +2052,128 @@ var OpenAICompatClient = class _OpenAICompatClient {
1417
2052
  return { text, usage };
1418
2053
  } catch (err) {
1419
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
+ }
1420
2063
  logLlmCall({
1421
2064
  ts: new Date(t0).toISOString(),
1422
2065
  provider: this.providerName,
1423
2066
  model: m,
1424
- kind: opts2.logKind,
2067
+ kind: opts.logKind,
1425
2068
  prompt: promptStr,
1426
2069
  response: "",
1427
2070
  durationMs: Date.now() - t0,
1428
2071
  attempt: attempt + 1,
1429
2072
  error: lastError
1430
2073
  });
1431
- 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));
1432
2076
  }
1433
2077
  }
1434
2078
  return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
1435
2079
  }
1436
- async chatJson(model, messages, opts2 = {}) {
1437
- const res = await this.chat(model, messages, { ...opts2, responseJson: true });
1438
- if (res.error || !res.text) return { data: null, raw: res.text, error: res.error };
1439
- try {
1440
- let txt = res.text.trim();
1441
- const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
1442
- if (fence && fence[1]) txt = fence[1];
1443
- return { data: JSON.parse(txt), raw: res.text };
1444
- } catch (err) {
1445
- 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
+ }
1446
2096
  }
2097
+ return { data: null, raw: lastRaw, error: lastError };
1447
2098
  }
1448
2099
  };
1449
2100
 
1450
2101
  // src/diarize/identify.ts
2102
+ var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
1451
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
+ }
1452
2119
  const bySpeaker = {};
1453
2120
  for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
1454
2121
  const parts = [];
1455
2122
  for (const sp of speakers) {
1456
2123
  const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
1457
- const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
1458
- parts.push(
1459
- `### ${sp.id} (${sp.name || "unknown"}, ${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s${voices})`
1460
- );
2124
+ parts.push(`### ${speakerHeader(sp)}`);
1461
2125
  for (const s of segs) parts.push(` ${s.text}`);
1462
2126
  }
1463
2127
  return parts.join("\n");
1464
2128
  }
1465
- function identifyPrompt(transcriptExcerpt, roster, knownSpeakers) {
1466
- 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.
1467
2137
 
1468
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 ("").
1469
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
+
1470
2146
  ${knownSpeakers && knownSpeakers.length ? `Known possible speakers: ${knownSpeakers.join(", ")}
2147
+ ` : ""}${sourceFileName ? `RECORDING FILENAME (often names participants): ${sourceFileName}
1471
2148
  ` : ""}ROSTER:
1472
2149
  ${roster}
1473
-
1474
- TRANSCRIPT EXCERPTS BY SPEAKER:
2150
+ ${hintBlock}
2151
+ TRANSCRIPT:
1475
2152
  ${transcriptExcerpt}
1476
2153
 
1477
- 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" }
1478
- 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.`;
1479
2156
  }
1480
- async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers) {
2157
+ async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers, nameHints, sourceFileName) {
1481
2158
  const excerpt = buildTranscriptExcerpt(segments, speakers);
1482
2159
  const { data, error } = await client.chatJson(
1483
2160
  model,
1484
- [{ role: "user", content: identifyPrompt(excerpt, roster, knownSpeakers) }],
1485
- { 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" }
1486
2177
  );
1487
2178
  if (error || !data) {
1488
2179
  return { nameMap: {}, speakers: [], reasoning: error || "no response" };
@@ -1494,48 +2185,499 @@ async function identifySpeakers(client, model, segments, speakers, roster, known
1494
2185
  return { nameMap, speakers: data.speakers || [], reasoning: data.reasoning || "" };
1495
2186
  }
1496
2187
 
1497
- // src/finalize/finalize.ts
1498
- var MIN_DUR = 0.5;
1499
- var MAX_DUR = 7;
1500
- var OVERLAP_GAP = 0.05;
1501
- function textSimilarity(a, b) {
1502
- const ta = new Set(tokenize(a).map((t) => t.norm));
1503
- const tb = new Set(tokenize(b).map((t) => t.norm));
1504
- if (ta.size === 0 && tb.size === 0) return 1;
1505
- if (ta.size === 0 || tb.size === 0) return 0;
1506
- let inter = 0;
1507
- for (const t of ta) if (tb.has(t)) inter++;
1508
- return inter / (ta.size + tb.size - inter);
1509
- }
1510
- function timeOverlapFrac(a, b) {
1511
- const ov = Math.max(0, Math.min(a.end, b.end) - Math.max(a.start, b.start));
1512
- const shorter = Math.min(a.end - a.start, b.end - b.start);
1513
- return shorter > 0 ? ov / shorter : 0;
1514
- }
1515
- function dedupSegments(segments) {
1516
- const sorted = [...segments].sort((a, b) => a.start - b.start);
1517
- const kept = [];
1518
- for (const seg of sorted) {
1519
- const dup = kept.find(
1520
- (k) => k.speaker === seg.speaker && textSimilarity(k.text, seg.text) > 0.7 && timeOverlapFrac(k, seg) > 0.2
1521
- );
1522
- if (dup) {
1523
- if (seg.confidence > dup.confidence) {
1524
- Object.assign(dup, seg);
1525
- }
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++;
1526
2201
  continue;
1527
2202
  }
1528
- kept.push(seg);
2203
+ if (++edits > 1) return false;
2204
+ if (s.length === l.length) i++;
2205
+ j++;
1529
2206
  }
1530
- return kept;
2207
+ return edits + (l.length - j) <= 1;
1531
2208
  }
1532
- function fixOverlaps(segments) {
1533
- if (segments.length === 0) return segments;
1534
- const sorted = [...segments].sort((a, b) => a.start - b.start);
1535
- for (let pass = 0; pass < 10; pass++) {
1536
- let changed = false;
1537
- for (let i = 0; i < sorted.length - 1; i++) {
1538
- const cur = sorted[i];
2209
+ function tokensMatch(a, b) {
2210
+ if (a === b) return true;
2211
+ return a.length >= 5 && b.length >= 5 && withinOneEdit(a, b);
2212
+ }
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
+ });
2285
+ }
2286
+ }
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;
2673
+ }
2674
+ function fixOverlaps(segments) {
2675
+ if (segments.length === 0) return segments;
2676
+ const sorted = [...segments].sort((a, b) => a.start - b.start);
2677
+ for (let pass = 0; pass < 10; pass++) {
2678
+ let changed = false;
2679
+ for (let i = 0; i < sorted.length - 1; i++) {
2680
+ const cur = sorted[i];
1539
2681
  const next = sorted[i + 1];
1540
2682
  if (cur.end > next.start) {
1541
2683
  const targetEnd = next.start - OVERLAP_GAP;
@@ -1565,9 +2707,9 @@ function clampAndFix(segments) {
1565
2707
  }
1566
2708
  return fixOverlaps(segments);
1567
2709
  }
1568
- function finalizeSegments(segments, opts2 = {}) {
1569
- const minSeg = opts2.minSegmentSec ?? 0.2;
1570
- let deduped = dedupSegments(segments);
2710
+ function finalizeSegments(segments, opts = {}) {
2711
+ const minSeg = opts.minSegmentSec ?? 0.2;
2712
+ let deduped = dedupSegments(trimSeamOverlaps(segments));
1571
2713
  deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
1572
2714
  const out = deduped.map((s, i) => ({
1573
2715
  id: i + 1,
@@ -1589,11 +2731,17 @@ function finalizeSegments(segments, opts2 = {}) {
1589
2731
  // src/finalize/format.ts
1590
2732
  var MAX_CHARS = 84;
1591
2733
  var MAX_BLOCK_SEC = 7;
1592
- function splitIntoBlocks(seg) {
1593
- const words = seg.words && seg.words.length > 0 ? seg.words : null;
1594
- if (!words) {
1595
- return [{ start: seg.start, end: seg.end, text: seg.text }];
1596
- }
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;
1597
2745
  const blocks = [];
1598
2746
  let curWords = [];
1599
2747
  let curLen = 0;
@@ -1620,64 +2768,287 @@ function splitIntoBlocks(seg) {
1620
2768
  curLen += addLen;
1621
2769
  }
1622
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);
1623
2801
  return blocks.length ? blocks : [{ start: seg.start, end: seg.end, text: seg.text }];
1624
2802
  }
1625
- function formatSrt(result, opts2 = {}) {
1626
- const labelSpeakers = opts2.labelSpeakers ?? true;
1627
- const showTone = opts2.showTone ?? true;
2803
+ function formatSrt(result, opts = {}) {
2804
+ const labelSpeakers = opts.labelSpeakers ?? true;
2805
+ const showTone = opts.showTone ?? true;
1628
2806
  let idx = 1;
1629
2807
  const blocks = [];
1630
2808
  for (const seg of result.segments) {
1631
2809
  const tone = showTone && seg.tone && seg.tone.length ? ` (${seg.tone.join(", ")})` : "";
1632
2810
  const speaker = labelSpeakers ? `${seg.speakerName || seg.speaker}: ` : "";
1633
- for (const b of splitIntoBlocks(seg)) {
1634
- 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}
1635
2817
  ${formatSrtTiming(b.start, b.end)}
1636
- ${speaker}${b.text}${tone}
1637
- `);
2818
+ ${speaker}${b.text}${t}
2819
+ `
2820
+ );
1638
2821
  idx++;
1639
2822
  }
1640
2823
  }
1641
2824
  return blocks.join("\n");
1642
2825
  }
1643
- 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) {
1644
2837
  const parts = [];
1645
- parts.push(`# ${opts2.title || "Transcript"}
1646
- `);
1647
- 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"}
1648
2853
  `);
2854
+ parts.push(
2855
+ `*Duration: ${formatDuration(result.metadata.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns*
2856
+ `
2857
+ );
1649
2858
  parts.push("\n## Speakers\n");
1650
2859
  for (const s of result.speakers) {
1651
- const talk = s.talkTime ? ` (${Math.round(s.talkTime)}s)` : "";
1652
- 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}`);
1653
2863
  }
1654
2864
  parts.push("\n## Transcript\n");
1655
- for (const seg of result.segments) {
1656
- const mm = Math.floor(seg.start / 60).toString().padStart(2, "0");
1657
- const ss = Math.floor(seg.start % 60).toString().padStart(2, "0");
1658
- const tone = seg.tone && seg.tone.length ? ` *(${seg.tone.join(", ")})*` : "";
1659
- 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)}
1660
2878
  `);
1661
2879
  }
1662
2880
  return parts.join("\n");
1663
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
+ }
1664
2897
  function formatJson(result) {
1665
2898
  return JSON.stringify(result, null, 2);
1666
2899
  }
1667
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
+
1668
3039
  // src/core/pipeline.ts
1669
3040
  import { basename as basename3, resolve as resolve2 } from "path";
1670
3041
  var JSON_OPTS = { encoding: "utf-8" };
1671
3042
  function readJson(p) {
1672
- if (!existsSync2(p)) return null;
3043
+ if (!existsSync3(p)) return null;
1673
3044
  try {
1674
- return JSON.parse(readFileSync(p, JSON_OPTS));
3045
+ return JSON.parse(readFileSync2(p, JSON_OPTS));
1675
3046
  } catch {
1676
3047
  return null;
1677
3048
  }
1678
3049
  }
1679
3050
  function writeJson(p, data) {
1680
- writeFileSync(p, JSON.stringify(data, null, 2), JSON_OPTS);
3051
+ writeFileSync2(p, JSON.stringify(data, null, 2), JSON_OPTS);
1681
3052
  }
1682
3053
  async function mapPool(items, limit, fn) {
1683
3054
  const results = new Array(items.length);
@@ -1692,30 +3063,44 @@ async function mapPool(items, limit, fn) {
1692
3063
  await Promise.all(workers);
1693
3064
  return results;
1694
3065
  }
1695
- function has(passes2, p) {
1696
- return passes2.includes(p);
3066
+ function has(passes, p) {
3067
+ return passes.includes(p);
1697
3068
  }
1698
- async function transcribe(opts2) {
1699
- if (!opts2 || typeof opts2.input !== "string" || opts2.input.length === 0) {
1700
- throw new Error("transcribe(options): 'input' (path to the audio/video file) is required");
1701
- }
1702
- if (typeof opts2.outputDir !== "string" || opts2.outputDir.length === 0) {
1703
- throw new Error("transcribe(options): 'outputDir' (directory for outputs) is required");
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) {
3080
+ throw new Error(
3081
+ "transcribe(options): 'input' (path to the audio/video file) is required"
3082
+ );
1704
3083
  }
1705
- const options = resolveOptions(opts2);
3084
+ const options = resolveOptions(opts);
1706
3085
  const keys = resolveKeys(options.apiKeys);
1707
3086
  logger.setLevel(options.logLevel);
1708
- if (!existsSync2(options.input)) {
3087
+ if (!existsSync3(options.input)) {
1709
3088
  throw new Error(`Input file not found: ${options.input}`);
1710
3089
  }
1711
- mkdirSync(options.intermediatesDir, { recursive: true });
1712
- mkdirSync(options.outputDir, { recursive: true });
1713
- logger.info(`intermediates: ${resolve2(options.intermediatesDir)} (file://${resolve2(options.intermediatesDir)})`);
3090
+ mkdirSync2(options.intermediatesDir, { recursive: true });
3091
+ mkdirSync2(options.outputDir, { recursive: true });
3092
+ logger.info(
3093
+ `intermediates: ${resolve2(options.intermediatesDir)} (file://${resolve2(options.intermediatesDir)})`
3094
+ );
1714
3095
  setLlmLogPath(options.llmLog ? `${options.intermediatesDir}/llm-calls.jsonl` : null);
3096
+ resetLlmUsage();
3097
+ const runStartedAt = Date.now();
1715
3098
  const sourcePath = `${options.intermediatesDir}/source.json`;
1716
3099
  const sig = inputSignature(options.input);
1717
- const cfgSig = configSignature(opts2);
1718
- const prevSig = readJson(sourcePath);
3100
+ const cfgSig = configSignature(opts);
3101
+ const prevSig = readJson(
3102
+ sourcePath
3103
+ );
1719
3104
  const inputChanged = !prevSig || prevSig.signature !== sig;
1720
3105
  const configChanged = !prevSig || prevSig.config !== cfgSig;
1721
3106
  if (inputChanged && prevSig) {
@@ -1734,45 +3119,60 @@ async function transcribe(opts2) {
1734
3119
  config: cfgSig,
1735
3120
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1736
3121
  });
1737
- const passes2 = options.passes;
3122
+ const passes = options.passes;
1738
3123
  const models = {
1739
3124
  transcribe: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
1740
3125
  reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL
1741
3126
  };
3127
+ const checkAbort = () => {
3128
+ options.signal?.throwIfAborted();
3129
+ };
1742
3130
  if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
1743
3131
  if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
1744
3132
  const tsProvider = options.timestampedProvider ?? "assemblyai";
1745
- const willTimestamp = has(passes2, "timestamped") || has(passes2, "align");
3133
+ const willTimestamp = has(passes, "timestamped") || has(passes, "align");
1746
3134
  if (willTimestamp) {
1747
3135
  if (tsProvider === "assemblyai" && !keys.assemblyai) {
1748
3136
  throw new Error(
1749
- "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)"
1750
3138
  );
1751
3139
  }
1752
3140
  if (tsProvider === "whisper-groq" && !keys.groq) {
1753
3141
  throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
1754
3142
  }
3143
+ if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
3144
+ throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3145
+ }
1755
3146
  }
1756
3147
  let probeInfo = null;
1757
3148
  const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
1758
3149
  const audioPath = `${options.intermediatesDir}/audio.mp3`;
1759
3150
  const probePath = `${options.intermediatesDir}/probe.json`;
1760
- if (has(passes2, "preprocess")) {
3151
+ if (has(passes, "preprocess")) {
3152
+ checkAbort();
1761
3153
  logger.info("=== preprocess ===");
1762
3154
  probeInfo = forceAll ? null : readJson(probePath);
1763
3155
  if (!probeInfo) {
1764
- probeInfo = await probe(options.input);
3156
+ probeInfo = await probe(options.input).catch(stageTag("preprocess"));
1765
3157
  writeJson(probePath, probeInfo);
1766
3158
  }
1767
- if (!existsSync2(audioPath) || forceAll) {
3159
+ if (!existsSync3(audioPath) || forceAll) {
1768
3160
  logger.info("extracting audio (mono 16kHz mp3)...");
1769
- await extractAudio(options.input, audioPath, AUDIO_OPTS);
3161
+ await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
3162
+ stageTag("preprocess")
3163
+ );
1770
3164
  }
1771
3165
  if (probeInfo.hasVideo) {
1772
3166
  const kfDir = `${options.intermediatesDir}/keyframes`;
1773
- if (!existsSync2(kfDir) || forceAll) {
3167
+ if (!existsSync3(kfDir) || forceAll) {
1774
3168
  logger.info("extracting keyframes...");
1775
- 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
+ );
1776
3176
  }
1777
3177
  }
1778
3178
  } else {
@@ -1780,71 +3180,136 @@ async function transcribe(opts2) {
1780
3180
  }
1781
3181
  if (!probeInfo) throw new Error("probe info missing (run preprocess)");
1782
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
+ );
1783
3195
  let description = null;
1784
- if (has(passes2, "describe")) {
3196
+ if (has(passes, "describe")) {
1785
3197
  const descPath = `${options.intermediatesDir}/description.json`;
1786
3198
  description = forceAll ? null : readJson(descPath);
1787
3199
  if (!description) {
3200
+ checkAbort();
1788
3201
  logger.info("=== describe ===");
1789
3202
  const client = new GeminiClient(keys.gemini);
1790
- const samplePath = `${options.intermediatesDir}/sample.mp3`;
1791
- if (!existsSync2(samplePath) || forceAll) {
1792
- 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 });
1793
3216
  }
1794
- const files = [{ path: samplePath }];
3217
+ const audioSampleCount = files.length;
1795
3218
  const kfDir = `${options.intermediatesDir}/keyframes`;
1796
- if (existsSync2(kfDir)) {
3219
+ if (existsSync3(kfDir)) {
1797
3220
  for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
1798
3221
  const p = `${kfDir}/${f}`;
1799
- if (existsSync2(p)) files.push({ path: p });
3222
+ if (existsSync3(p)) files.push({ path: p });
1800
3223
  }
1801
3224
  }
1802
- description = await describeMeeting(client, models.transcribe, files, basename3(options.input), options.instructions);
3225
+ description = await describeMeeting(
3226
+ client,
3227
+ models.transcribe,
3228
+ files,
3229
+ basename3(options.input),
3230
+ options.instructions,
3231
+ audioSampleCount
3232
+ ).catch(stageTag("describe"));
1803
3233
  writeJson(descPath, description);
1804
3234
  logger.info(`description: ${description.description.slice(0, 120)}...`);
1805
3235
  }
1806
3236
  } else {
1807
3237
  description = forceAll ? null : readJson(`${options.intermediatesDir}/description.json`);
1808
3238
  }
1809
- 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");
1810
3240
  let chunks = [];
1811
3241
  if (needChunks) {
1812
3242
  let silences = [];
1813
3243
  try {
1814
3244
  silences = await detectSilence(audioPath, { noiseDb: -15, minDuration: 0.3 });
1815
- if (silences.length < 3) silences = await detectSilence(audioPath, { noiseDb: -12, minDuration: 0.25 });
3245
+ if (silences.length < 3)
3246
+ silences = await detectSilence(audioPath, { noiseDb: -12, minDuration: 0.25 });
1816
3247
  } catch {
1817
3248
  }
1818
3249
  chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
1819
3250
  if (silences.length > 3) {
1820
3251
  chunks = chunks.map((c) => {
1821
- const snapped = snapToSilence(c.start, silences, Math.min(10, options.chunkOverlapSec / 2));
3252
+ const snapped = snapToSilence(
3253
+ c.start,
3254
+ silences,
3255
+ Math.min(10, options.chunkOverlapSec / 2)
3256
+ );
1822
3257
  return { ...c, start: snapped, trustedStart: snapped + c.overlapWithPrevious };
1823
3258
  });
1824
3259
  }
1825
3260
  }
1826
3261
  const tagWith = (r, chunk) => ({
1827
3262
  ...r,
1828
- segments: r.segments.map((s) => ({ ...s, chunkIndex: chunk.index, trustedStart: chunk.trustedStart }))
3263
+ segments: r.segments.map((s) => ({
3264
+ ...s,
3265
+ chunkIndex: chunk.index,
3266
+ trustedStart: chunk.trustedStart
3267
+ }))
1829
3268
  });
1830
3269
  let llmChunkResults = [];
1831
- if (has(passes2, "llm-transcribe")) {
3270
+ if (has(passes, "llm-transcribe")) {
1832
3271
  logger.info("=== llm-transcribe ===");
1833
3272
  let runChunks = chunks;
1834
- if (options.onlyChunk !== void 0) runChunks = chunks.filter((c) => c.index === options.onlyChunk);
1835
- logger.info(`${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`);
3273
+ if (options.onlyChunk !== void 0)
3274
+ runChunks = chunks.filter((c) => c.index === options.onlyChunk);
3275
+ logger.info(
3276
+ `${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`
3277
+ );
1836
3278
  const client = new GeminiClient(keys.gemini);
1837
3279
  const llmDir = `${options.intermediatesDir}/llm`;
1838
- 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
+ };
1839
3302
  llmChunkResults = await mapPool(runChunks, options.concurrency, async (chunk) => {
3303
+ checkAbort();
1840
3304
  const parsedPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_parsed.json`;
1841
3305
  const cached = forceAll ? null : readJson(parsedPath);
1842
3306
  if (cached && cached.segments.length > 0) {
1843
3307
  logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
3308
+ completed.push(cached);
1844
3309
  return tagWith(cached, chunk);
1845
3310
  }
1846
3311
  const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
1847
- if (!existsSync2(chunkPath) || forceAll) {
3312
+ if (!existsSync3(chunkPath) || forceAll) {
1848
3313
  await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
1849
3314
  }
1850
3315
  let previousTail;
@@ -1856,7 +3321,9 @@ async function transcribe(opts2) {
1856
3321
  previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
1857
3322
  }
1858
3323
  }
1859
- logger.info(`chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`);
3324
+ logger.info(
3325
+ `chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`
3326
+ );
1860
3327
  const result2 = await transcribeChunk(
1861
3328
  client,
1862
3329
  models.transcribe,
@@ -1873,7 +3340,12 @@ async function transcribe(opts2) {
1873
3340
  { chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
1874
3341
  );
1875
3342
  writeJson(parsedPath, result2);
1876
- writeFileSync(`${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`, result2.raw);
3343
+ writeFileSync2(
3344
+ `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
3345
+ result2.raw
3346
+ );
3347
+ completed.push(result2);
3348
+ writePartial();
1877
3349
  return tagWith(result2, chunk);
1878
3350
  });
1879
3351
  const errored = llmChunkResults.filter((r) => r.error);
@@ -1885,7 +3357,7 @@ async function transcribe(opts2) {
1885
3357
  }
1886
3358
  } else {
1887
3359
  const llmDir = `${options.intermediatesDir}/llm`;
1888
- if (!forceAll && existsSync2(llmDir)) {
3360
+ if (!forceAll && existsSync3(llmDir)) {
1889
3361
  const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
1890
3362
  llmChunkResults = files.map((f, i) => {
1891
3363
  const r = readJson(`${llmDir}/${f}`);
@@ -1903,31 +3375,57 @@ async function transcribe(opts2) {
1903
3375
  }
1904
3376
  logger.info(`total LLM segments: ${allLlmSegments.length}`);
1905
3377
  let asrResult = null;
1906
- if (has(passes2, "timestamped") || has(passes2, "align")) {
3378
+ if (has(passes, "timestamped") || has(passes, "align")) {
3379
+ checkAbort();
1907
3380
  const provider = options.timestampedProvider ?? "assemblyai";
1908
3381
  if (provider === "whisper-groq") {
1909
3382
  logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
1910
3383
  if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
1911
- if (!existsSync2(audioPath) || forceAll) {
3384
+ if (!existsSync3(audioPath) || forceAll) {
1912
3385
  await extractAudio(options.input, audioPath, AUDIO_OPTS);
1913
3386
  }
1914
3387
  const { readFile: readFile2 } = await import("fs/promises");
1915
3388
  const buf = await readFile2(audioPath);
1916
3389
  const groq = new WhisperGroqClient(keys.groq);
1917
- asrResult = await groq.transcribe(buf);
3390
+ asrResult = await groq.transcribe(buf).catch(stageTag("asr"));
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
+ }
1918
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
+ );
1919
3411
  } else {
1920
3412
  logger.info("=== timestamped (AssemblyAI) ===");
1921
- if (!keys.assemblyai) throw new Error("ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)");
1922
- const aai = new AssemblyAIProvider({ apiKey: keys.assemblyai, cacheDir: `${options.intermediatesDir}/assemblyai` });
1923
- asrResult = await aai.transcribe(audioPath);
3413
+ if (!keys.assemblyai)
3414
+ throw new Error(
3415
+ "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
3416
+ );
3417
+ const aai = new AssemblyAIProvider({
3418
+ apiKey: keys.assemblyai,
3419
+ cacheDir: `${options.intermediatesDir}/assemblyai`
3420
+ });
3421
+ asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
1924
3422
  writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
1925
3423
  }
1926
3424
  } else {
1927
3425
  asrResult = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
1928
3426
  }
1929
3427
  let aligned = [];
1930
- if (has(passes2, "align") && asrResult) {
3428
+ if (has(passes, "align") && asrResult) {
1931
3429
  logger.info("=== align ===");
1932
3430
  aligned = alignSegments(allLlmSegments, asrResult.words, { timeMarginSec: 30 });
1933
3431
  writeJson(`${options.intermediatesDir}/aligned.json`, aligned);
@@ -1936,15 +3434,18 @@ async function transcribe(opts2) {
1936
3434
  }
1937
3435
  const alignedOk = aligned.filter((a) => a.timingSource !== "coarse").length;
1938
3436
  logger.info(`aligned: ${alignedOk}/${aligned.length} with ASR timing`);
1939
- if (asrResult && (has(passes2, "align") || has(passes2, "consistency"))) {
3437
+ if (asrResult && (has(passes, "align") || has(passes, "consistency"))) {
1940
3438
  const before = aligned.length;
1941
3439
  aligned = fillAsrGaps(aligned, asrResult.words, asrResult.utterances);
1942
3440
  const added = aligned.length - before;
1943
3441
  if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
1944
3442
  }
3443
+ if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
3444
+ aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
3445
+ }
1945
3446
  let segments = aligned;
1946
3447
  let speakers = [];
1947
- if (has(passes2, "consistency") && asrResult) {
3448
+ if (has(passes, "consistency") && asrResult) {
1948
3449
  logger.info("=== consistency ===");
1949
3450
  const cons = assignGlobalSpeakers(aligned, asrResult.utterances, {
1950
3451
  hasDiarization: asrResult.hasDiarization ?? true
@@ -1961,28 +3462,78 @@ async function transcribe(opts2) {
1961
3462
  speakers = c.speakers;
1962
3463
  }
1963
3464
  }
1964
- if (options.diarizationLevel >= 3 && has(passes2, "identify") && keys.deepseek && description) {
1965
- logger.info("=== identify (DeepSeek) ===");
1966
- const dsClient = OpenAICompatClient.fromProvider("deepseek", keys.deepseek, models.reasoner);
1967
- const id = await identifySpeakers(
1968
- dsClient,
1969
- models.reasoner,
1970
- segments.map((s) => ({ speaker: s.speaker, text: s.text })),
1971
- speakers,
1972
- description.roster,
1973
- options.knownSpeakers
1974
- );
1975
- logger.info(`identified ${Object.keys(id.nameMap).length} speakers: ${JSON.stringify(id.nameMap)}`);
1976
- writeJson(`${options.intermediatesDir}/identified.json`, id);
1977
- segments = segments.map(
1978
- (s) => id.nameMap[s.speaker] ? { ...s, speakerName: id.nameMap[s.speaker] } : s
1979
- );
1980
- speakers = speakers.map(
1981
- (sp) => id.nameMap[sp.id] ? { ...sp, name: id.nameMap[sp.id] } : sp
1982
- );
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
+ }
1983
3534
  }
1984
3535
  let finalSegments = [];
1985
- if (has(passes2, "finalize")) {
3536
+ if (has(passes, "finalize")) {
1986
3537
  logger.info("=== finalize ===");
1987
3538
  finalSegments = finalizeSegments(segments);
1988
3539
  writeJson(`${options.intermediatesDir}/final.json`, finalSegments);
@@ -1990,24 +3541,106 @@ async function transcribe(opts2) {
1990
3541
  finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
1991
3542
  }
1992
3543
  logger.info(`final segments: ${finalSegments.length}`);
3544
+ const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
3545
+ const wallMs = Date.now() - runStartedAt;
1993
3546
  const metadata = {
1994
3547
  sourceFile: options.input,
1995
3548
  duration,
1996
3549
  processedAt: (/* @__PURE__ */ new Date()).toISOString(),
1997
3550
  models: {
1998
3551
  transcribe: models.transcribe,
1999
- 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"
2000
3553
  },
2001
- 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
+ }
2002
3565
  };
2003
3566
  const result = { segments: finalSegments, speakers, metadata };
3567
+ writeJson(`${options.intermediatesDir}/result.json`, result);
2004
3568
  for (const fmt of options.formats) {
2005
3569
  const base = basename3(options.input, ext(options.input));
2006
- if (fmt === "srt") writeFileSync(`${options.outputDir}/${base}.srt`, formatSrt(result, { title: base }));
2007
- if (fmt === "md") writeFileSync(`${options.outputDir}/${base}.md`, formatMarkdown(result, { title: base }));
2008
- if (fmt === "json") writeFileSync(`${options.outputDir}/${base}.json`, formatJson(result));
3570
+ if (fmt === "srt")
3571
+ writeFileSync2(
3572
+ `${options.outputDir}/${base}.srt`,
3573
+ formatSrt(result, { title: base })
3574
+ );
3575
+ if (fmt === "md")
3576
+ writeFileSync2(
3577
+ `${options.outputDir}/${base}.md`,
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 })
3589
+ );
3590
+ if (fmt === "json")
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 {
2009
3619
  }
2010
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
+ );
2011
3644
  return result;
2012
3645
  }
2013
3646
  function ext(p) {
@@ -2015,59 +3648,1101 @@ function ext(p) {
2015
3648
  return i >= 0 ? p.slice(i) : "";
2016
3649
  }
2017
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
+
2018
4540
  // src/cli.ts
2019
4541
  var packageVersion = "0.0.0";
2020
4542
  try {
2021
- const here = dirname3(fileURLToPath(import.meta.url));
2022
- 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"));
2023
4545
  packageVersion = pkg.version;
2024
4546
  } catch {
2025
4547
  }
2026
4548
  var program = new Command();
2027
- 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", "./output").option(
2028
- "-i, --intermediates <dir>",
2029
- "intermediates directory (default: auto-derived per input file so caches never collide)"
2030
- ).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", "srt,md,json").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");
2031
- program.parse();
2032
- var opts = program.opts();
2033
- var input = program.args[0];
2034
- if (!input) {
2035
- console.error("Error: input file is required.");
2036
- process.exit(1);
2037
- }
2038
- var passes = opts.passes?.split(",");
2039
- var level = parseInt(opts.level, 10);
2040
- transcribe({
2041
- input,
2042
- outputDir: opts.output,
2043
- intermediatesDir: opts.intermediates,
2044
- instructions: opts.instructions,
2045
- passes,
2046
- chunkDurationSec: parseInt(opts.chunkSeconds, 10),
2047
- chunkOverlapSec: parseInt(opts.overlapSeconds, 10),
2048
- concurrency: parseInt(opts.concurrency, 10),
2049
- screenshotCount: parseInt(opts.screenshots, 10),
2050
- formats: opts.formats.split(","),
2051
- diarizationLevel: level,
2052
- model: opts.model,
2053
- reasoner: opts.reasoner,
2054
- timestampedProvider: opts.timestamped,
2055
- force: opts.force,
2056
- onlyChunk: opts.onlyChunk ? parseInt(opts.onlyChunk, 10) : void 0,
2057
- saveIntermediates: opts.saveIntermediates,
2058
- showProgress: opts.progress,
2059
- llmLog: opts.llmLog,
2060
- logLevel: opts.logLevel
2061
- }).then((result) => {
2062
- const segs = result.segments.length;
2063
- console.log(`Done. ${segs} segments.`);
2064
- }).catch((err) => {
2065
- const msg = err instanceof Error ? err.message : String(err);
2066
- 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(`
2067
4697
  \u2717 ${msg}`);
2068
- if (opts.logLevel === "debug" || process.env.OFFMUTE_DEBUG) {
2069
- 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);
2070
4705
  }
2071
- process.exit(1);
2072
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();
2073
4748
  //# sourceMappingURL=cli.js.map