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/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // src/core/pipeline.ts
2
- import { existsSync as existsSync2, mkdirSync, readFileSync, writeFileSync } from "fs";
2
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
3
3
 
4
4
  // src/core/config.ts
5
5
  import { createHash } from "crypto";
6
- import { basename, resolve } from "path";
6
+ import { basename, dirname, resolve } from "path";
7
7
  import { statSync } from "fs";
8
8
  import { tmpdir } from "os";
9
9
  var DEFAULT_PASSES = [
@@ -19,12 +19,14 @@ var MODELS = {
19
19
  gemini25Pro: "gemini-2.5-pro",
20
20
  gemini25Flash: "gemini-2.5-flash",
21
21
  gemini3Pro: "gemini-3-pro-preview",
22
+ gemini31Pro: "gemini-3.1-pro-preview",
23
+ geminiFlashLatest: "gemini-flash-latest",
22
24
  deepseek: "deepseek-chat",
23
25
  deepseekReasoner: "deepseek-reasoner",
24
26
  gpt4o: "gpt-4o",
25
27
  claudeSonnet: "claude-sonnet-4-5"
26
28
  };
27
- var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini25Flash;
29
+ var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini31Pro;
28
30
  var DEFAULT_REASONER_MODEL = MODELS.deepseek;
29
31
  function resolveKeys(injected) {
30
32
  const env = process.env;
@@ -35,19 +37,23 @@ function resolveKeys(injected) {
35
37
  deepseek: injected?.deepseek || env.DEEPSEEK_API_KEY,
36
38
  groq: injected?.groq || env.GROQ_API_KEY,
37
39
  assemblyai: injected?.assemblyai || env.ASSEMBLYAI_API_KEY,
38
- anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY
40
+ anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY,
41
+ zai: injected?.zai || env.ZAI_API_KEY || env.GLM_API_KEY,
42
+ kimi: injected?.kimi || env.KIMI_API_KEY || env.MOONSHOT_API_KEY,
43
+ elevenlabs: injected?.elevenlabs || env.ELEVENLABS_API_KEY
39
44
  };
40
45
  }
41
46
  function resolveOptions(opts) {
42
47
  return {
43
48
  input: opts.input,
44
- outputDir: opts.outputDir,
49
+ // Default: write next to the input file (e.g. meeting.md beside meeting.mp4) — no ./output folder.
50
+ outputDir: opts.outputDir ?? dirname(resolve(opts.input)),
45
51
  intermediatesDir: opts.intermediatesDir ?? deriveIntermediatesDir(opts.input),
46
52
  instructions: opts.instructions,
47
53
  knownSpeakers: opts.knownSpeakers,
48
54
  passes: (() => {
49
55
  const p = opts.passes ?? DEFAULT_PASSES;
50
- if ((opts.diarizationLevel ?? 2) >= 3 && !p.includes("identify")) {
56
+ if ((opts.diarizationLevel ?? 3) >= 3 && !p.includes("identify")) {
51
57
  const out = [...p];
52
58
  const fi = out.indexOf("finalize");
53
59
  if (fi >= 0) out.splice(fi, 0, "identify");
@@ -61,8 +67,14 @@ function resolveOptions(opts) {
61
67
  screenshotCount: opts.screenshotCount ?? 6,
62
68
  concurrency: opts.concurrency ?? 4,
63
69
  saveIntermediates: opts.saveIntermediates ?? true,
64
- formats: opts.formats ?? ["srt", "md", "json"],
65
- diarizationLevel: opts.diarizationLevel ?? 2,
70
+ formats: opts.formats ?? ["md"],
71
+ mdStyle: opts.mdStyle ?? "merged",
72
+ summary: opts.summary ?? false,
73
+ // Level 3 is the default: display names must come from the VERIFIED identify pass.
74
+ // (A describe-pass roster once bound names to the wrong voices and level 2 shipped
75
+ // them unchecked — the Jay-call flip. Level 2 now shows honest Speaker A/B labels.)
76
+ diarizationLevel: opts.diarizationLevel ?? 3,
77
+ identifyMode: opts.identifyMode ?? "dual",
66
78
  apiKeys: opts.apiKeys,
67
79
  model: opts.model,
68
80
  reasoner: opts.reasoner,
@@ -71,7 +83,8 @@ function resolveOptions(opts) {
71
83
  onlyChunk: opts.onlyChunk,
72
84
  showProgress: opts.showProgress ?? true,
73
85
  llmLog: opts.llmLog ?? true,
74
- logLevel: opts.logLevel ?? "info"
86
+ logLevel: opts.logLevel ?? "info",
87
+ signal: opts.signal
75
88
  };
76
89
  }
77
90
  function deriveIntermediatesDir(input) {
@@ -104,7 +117,7 @@ function configSignature(o) {
104
117
  chunkDurationSec: o.chunkDurationSec ?? 600,
105
118
  chunkOverlapSec: o.chunkOverlapSec ?? 60,
106
119
  screenshotCount: o.screenshotCount ?? 6,
107
- diarizationLevel: o.diarizationLevel ?? 2,
120
+ diarizationLevel: o.diarizationLevel ?? 3,
108
121
  timestampedProvider: o.timestampedProvider ?? "assemblyai"
109
122
  };
110
123
  return createHash("sha1").update(JSON.stringify(relevant)).digest("hex");
@@ -139,11 +152,13 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
139
152
  // src/utils/logger.ts
140
153
  var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
141
154
  var currentLevel = "info";
155
+ var sink = null;
142
156
  function setLogLevel(level) {
143
157
  currentLevel = level;
144
158
  }
145
159
  function log(level, msg, extra) {
146
160
  if (LEVELS[level] < LEVELS[currentLevel]) return;
161
+ if (sink && extra === void 0 && sink(level, msg)) return;
147
162
  const ts = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
148
163
  const prefix = `[${ts}] ${level.toUpperCase().padEnd(5)}`;
149
164
  if (extra !== void 0) {
@@ -157,13 +172,16 @@ var logger = {
157
172
  info: (msg, extra) => log("info", msg, extra),
158
173
  warn: (msg, extra) => log("warn", msg, extra),
159
174
  error: (msg, extra) => log("error", msg, extra),
160
- setLevel: setLogLevel
175
+ setLevel: setLogLevel,
176
+ setSink: (s) => {
177
+ sink = s;
178
+ }
161
179
  };
162
180
 
163
181
  // src/audio/ffmpeg.ts
164
182
  import { spawn } from "child_process";
165
183
  import { mkdir } from "fs/promises";
166
- import { dirname } from "path";
184
+ import { dirname as dirname2 } from "path";
167
185
  function run(cmd, args, _opts = {}) {
168
186
  return new Promise((resolve3, reject) => {
169
187
  const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
@@ -234,12 +252,12 @@ function audioArgs(opts) {
234
252
  }
235
253
  }
236
254
  async function extractAudio(input, output, opts = {}) {
237
- await mkdir(dirname(output), { recursive: true });
255
+ await mkdir(dirname2(output), { recursive: true });
238
256
  const args = ["-y", "-i", input, ...audioArgs(opts), output];
239
257
  await run("ffmpeg", args);
240
258
  }
241
259
  async function extractChunk(input, output, startSec, endSec, opts = {}) {
242
- await mkdir(dirname(output), { recursive: true });
260
+ await mkdir(dirname2(output), { recursive: true });
243
261
  const duration = Math.max(0, endSec - startSec);
244
262
  const args = [
245
263
  "-y",
@@ -370,10 +388,35 @@ import { basename as basename2 } from "path";
370
388
  // src/providers/llm-log.ts
371
389
  import { appendFileSync } from "fs";
372
390
  var logPath = null;
391
+ var usageRecords = /* @__PURE__ */ new Map();
373
392
  function setLlmLogPath(path) {
374
393
  logPath = path ?? null;
375
394
  }
395
+ function resetLlmUsage() {
396
+ usageRecords = /* @__PURE__ */ new Map();
397
+ }
398
+ function getLlmUsage() {
399
+ return [...usageRecords.values()];
400
+ }
376
401
  function logLlmCall(entry) {
402
+ try {
403
+ const key = `${entry.model}|${entry.kind ?? ""}`;
404
+ const rec = usageRecords.get(key) ?? {
405
+ provider: entry.provider,
406
+ model: entry.model,
407
+ kind: entry.kind,
408
+ inputTokens: 0,
409
+ outputTokens: 0,
410
+ calls: 0,
411
+ errors: 0
412
+ };
413
+ rec.inputTokens += entry.usage?.inputTokens ?? 0;
414
+ rec.outputTokens += entry.usage?.outputTokens ?? 0;
415
+ rec.calls += 1;
416
+ if (entry.error) rec.errors += 1;
417
+ usageRecords.set(key, rec);
418
+ } catch {
419
+ }
377
420
  if (!logPath) return;
378
421
  try {
379
422
  appendFileSync(logPath, JSON.stringify(entry) + "\n", { encoding: "utf-8" });
@@ -381,7 +424,39 @@ function logLlmCall(entry) {
381
424
  }
382
425
  }
383
426
 
427
+ // src/utils/retry.ts
428
+ 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;
429
+ function isTransient(err) {
430
+ const msg = err instanceof Error ? `${err.message} ${err.cause ?? ""}` : String(err);
431
+ return TRANSIENT_RE.test(msg);
432
+ }
433
+ async function withRetry(label, fn, opts = {}) {
434
+ const retries = opts.retries ?? 5;
435
+ const base = opts.baseDelayMs ?? 2e3;
436
+ let lastErr;
437
+ for (let attempt = 0; attempt <= retries; attempt++) {
438
+ try {
439
+ return await fn();
440
+ } catch (err) {
441
+ lastErr = err;
442
+ if (attempt === retries || !isTransient(err)) throw err;
443
+ const delay = base * 2 ** attempt * (0.7 + Math.random() * 0.6);
444
+ logger.warn(
445
+ `[${label}] transient failure (${err instanceof Error ? err.message : err}) \u2014 retry ${attempt + 1}/${retries} in ${(delay / 1e3).toFixed(1)}s`
446
+ );
447
+ await new Promise((r) => setTimeout(r, delay));
448
+ }
449
+ }
450
+ throw lastErr;
451
+ }
452
+
384
453
  // src/providers/gemini.ts
454
+ var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
455
+ var originalWarn = console.warn.bind(console);
456
+ console.warn = (...args) => {
457
+ if (typeof args[0] === "string" && args[0].startsWith(SDK_KEY_WARNING)) return;
458
+ originalWarn(...args);
459
+ };
385
460
  var MIME_BY_EXT = {
386
461
  ".flac": "audio/flac",
387
462
  ".mp3": "audio/mp3",
@@ -423,11 +498,16 @@ var GeminiClient = class {
423
498
  constructor(apiKey) {
424
499
  this.ai = new GoogleGenAI({ apiKey });
425
500
  }
426
- /** Upload a file and wait until it's done processing. */
501
+ /** Upload a file and wait until it's done processing. Uploads ride one long HTTP
502
+ * request each — the retry loop in generate() doesn't cover them, and transient
503
+ * "fetch failed" blips here killed live runs, so they get their own retry. */
427
504
  async upload(path, mimeType) {
428
505
  const mt = mimeType || detectMime(path);
429
506
  logger.debug(`[gemini] uploading ${basename2(path)} (${mt})...`);
430
- let file = await this.ai.files.upload({ file: path, config: { mimeType: mt } });
507
+ let file = await withRetry(
508
+ `gemini upload ${basename2(path)}`,
509
+ () => this.ai.files.upload({ file: path, config: { mimeType: mt } })
510
+ );
431
511
  let tries = 0;
432
512
  while (file.state === "PROCESSING" && tries < 120) {
433
513
  await sleep(2e3);
@@ -506,10 +586,14 @@ var GeminiClient = class {
506
586
  lastError = err instanceof Error ? err.message : String(err);
507
587
  if (config.thinkingConfig && isThinkingConfigError(lastError)) {
508
588
  delete config.thinkingConfig;
509
- logger.warn(`[gemini] model ${model} rejected thinking config \u2014 retrying without it`);
589
+ logger.warn(
590
+ `[gemini] model ${model} rejected thinking config \u2014 retrying without it`
591
+ );
510
592
  continue;
511
593
  }
512
- logger.warn(`[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`);
594
+ logger.warn(
595
+ `[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`
596
+ );
513
597
  logLlmCall({
514
598
  ts: new Date(t0).toISOString(),
515
599
  provider: "gemini",
@@ -525,7 +609,11 @@ var GeminiClient = class {
525
609
  if (attempt < maxRetries - 1) await sleep(retryDelayMs * (attempt + 1));
526
610
  }
527
611
  }
528
- return { text: "", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, error: lastError };
612
+ return {
613
+ text: "",
614
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
615
+ error: lastError
616
+ };
529
617
  } finally {
530
618
  await this.cleanup(uploaded);
531
619
  }
@@ -570,7 +658,7 @@ import { AssemblyAI } from "assemblyai";
570
658
  import { createHash as createHash2 } from "crypto";
571
659
  import { readFile, mkdir as mkdir2, writeFile } from "fs/promises";
572
660
  import { existsSync } from "fs";
573
- import { dirname as dirname2 } from "path";
661
+ import { dirname as dirname3 } from "path";
574
662
  async function fileHash(path) {
575
663
  const buf = await readFile(path);
576
664
  return createHash2("sha256").update(buf).digest("hex").slice(0, 24);
@@ -595,7 +683,10 @@ var AssemblyAIProvider = class {
595
683
  return JSON.parse(await readFile(cachePath, "utf-8"));
596
684
  }
597
685
  logger.info(`[assemblyai] uploading ${filePath}...`);
598
- const uploadUrl = await this.client.files.upload(filePath);
686
+ const uploadUrl = await withRetry(
687
+ "assemblyai upload",
688
+ () => this.client.files.upload(filePath)
689
+ );
599
690
  logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
600
691
  const params = {
601
692
  audio: uploadUrl,
@@ -603,13 +694,16 @@ var AssemblyAIProvider = class {
603
694
  speech_model: this.speechModel
604
695
  };
605
696
  if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
606
- const transcript = await this.client.transcripts.transcribe(params);
697
+ const transcript = await withRetry(
698
+ "assemblyai transcribe",
699
+ () => this.client.transcripts.transcribe(params)
700
+ );
607
701
  if (transcript.status === "error") {
608
702
  throw new Error(`AssemblyAI error: ${transcript.error}`);
609
703
  }
610
704
  const result = this.mapTranscript(transcript, hash);
611
705
  if (cachePath) {
612
- await mkdir2(dirname2(cachePath), { recursive: true });
706
+ await mkdir2(dirname3(cachePath), { recursive: true });
613
707
  await writeFile(cachePath, JSON.stringify(result, null, 2));
614
708
  }
615
709
  logger.info(
@@ -707,9 +801,315 @@ var WhisperGroqClient = class {
707
801
  }
708
802
  };
709
803
 
804
+ // src/providers/elevenlabs.ts
805
+ var MAX_UTTERANCE_GAP_SEC = 1.5;
806
+ var ElevenLabsClient = class {
807
+ constructor(apiKey, baseUrl = "https://api.elevenlabs.io/v1") {
808
+ this.apiKey = apiKey;
809
+ this.baseUrl = baseUrl;
810
+ }
811
+ apiKey;
812
+ baseUrl;
813
+ async transcribe(audio, opts = {}) {
814
+ const model = opts.model ?? "scribe_v2";
815
+ const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
816
+ const form = new FormData();
817
+ form.append("file", blob, "audio.mp3");
818
+ form.append("model_id", model);
819
+ form.append("timestamps_granularity", "word");
820
+ form.append("diarize", "true");
821
+ form.append("tag_audio_events", "false");
822
+ if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
823
+ for (const term of opts.keyterms ?? []) form.append("keyterms", term);
824
+ const data = await withRetry("elevenlabs", async () => {
825
+ const res = await fetch(`${this.baseUrl}/speech-to-text`, {
826
+ method: "POST",
827
+ headers: { "xi-api-key": this.apiKey },
828
+ body: form
829
+ });
830
+ if (!res.ok) {
831
+ const txt = await res.text();
832
+ throw new Error(`ElevenLabs Scribe ${res.status}: ${txt.slice(0, 300)}`);
833
+ }
834
+ return await res.json();
835
+ });
836
+ const words = [];
837
+ for (const w of data.words ?? []) {
838
+ if (w.type !== "word") continue;
839
+ if (w.start === void 0 || w.end === void 0) continue;
840
+ words.push({
841
+ text: w.text.trim(),
842
+ start: w.start,
843
+ end: w.end,
844
+ speaker: w.speaker_id ?? "speaker_0"
845
+ });
846
+ }
847
+ const utterances = [];
848
+ let cur = [];
849
+ const flush = () => {
850
+ if (cur.length === 0) return;
851
+ utterances.push({
852
+ speaker: cur[0].speaker,
853
+ start: cur[0].start,
854
+ end: cur[cur.length - 1].end,
855
+ text: cur.map((w) => w.text).join(" "),
856
+ words: cur.map(({ text, start, end }) => ({ text, start, end }))
857
+ });
858
+ cur = [];
859
+ };
860
+ for (const w of words) {
861
+ const prev = cur[cur.length - 1];
862
+ if (prev && (w.speaker !== prev.speaker || w.start - prev.end > MAX_UTTERANCE_GAP_SEC)) {
863
+ flush();
864
+ }
865
+ cur.push(w);
866
+ }
867
+ flush();
868
+ const speakers = [...new Set(words.map((w) => w.speaker))];
869
+ return {
870
+ utterances,
871
+ words: words.map(({ text, start, end }) => ({ text, start, end })),
872
+ durationSec: data.audio_duration_secs ?? (words.length ? words[words.length - 1].end : 0),
873
+ speakers,
874
+ hasDiarization: true,
875
+ transcriptId: data.transcription_id ?? `elevenlabs-${model}`
876
+ };
877
+ }
878
+ };
879
+
880
+ // src/core/pricing.ts
881
+ var PRICES_AS_OF = "2026-07";
882
+ var MODEL_PRICES = {
883
+ // Gemini (ai.google.dev/gemini-api/docs/pricing, standard tier, <=200k prompts)
884
+ "gemini-3.1-pro-preview": { textIn: 2, out: 12 },
885
+ "gemini-3-pro-preview": { textIn: 2, out: 12 },
886
+ "gemini-3.5-flash": { textIn: 1.5, out: 9 },
887
+ "gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
888
+ "gemini-2.5-pro": { textIn: 1.25, out: 10 },
889
+ "gemini-2.5-flash": { textIn: 0.3, audioIn: 1, out: 2.5 },
890
+ "gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
891
+ // Moving aliases — priced as their current targets.
892
+ "gemini-pro-latest": { textIn: 2, out: 12 },
893
+ "gemini-flash-latest": { textIn: 1.5, out: 9 },
894
+ "gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
895
+ // Text reasoners
896
+ "deepseek-chat": { textIn: 0.28, out: 0.42 },
897
+ "deepseek-reasoner": { textIn: 0.28, out: 0.42 },
898
+ "gpt-4o-mini": { textIn: 0.15, out: 0.6 },
899
+ "glm-4.7": { textIn: 0.6, out: 2.2 }
900
+ };
901
+ var ASR_HOURLY = {
902
+ assemblyai: 0.15,
903
+ // universal-2, diarization included
904
+ elevenlabs: 0.4,
905
+ // scribe v2 (standard tier; business tier is lower)
906
+ "whisper-groq": 0.04,
907
+ // whisper-large-v3-turbo
908
+ none: 0
909
+ };
910
+ var AUDIO_TOKENS_PER_SEC = 32;
911
+ function priceFor(model) {
912
+ if (MODEL_PRICES[model]) return MODEL_PRICES[model];
913
+ const hit = Object.keys(MODEL_PRICES).find((k) => model.startsWith(k));
914
+ return hit ? MODEL_PRICES[hit] : null;
915
+ }
916
+ function asrCost(provider, durationSec) {
917
+ const hourly = ASR_HOURLY[provider];
918
+ if (hourly === void 0) return null;
919
+ return durationSec / 3600 * hourly;
920
+ }
921
+ function estimateRunCost(opts) {
922
+ const lines = [];
923
+ let total = 0;
924
+ let incomplete = false;
925
+ const p = priceFor(opts.model);
926
+ const chunks = Math.max(
927
+ 1,
928
+ Math.ceil((opts.durationSec - opts.overlapSec) / (opts.chunkSec - opts.overlapSec))
929
+ );
930
+ const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
931
+ if (p) {
932
+ const audioTok = billedAudioSec * AUDIO_TOKENS_PER_SEC;
933
+ const promptTok = chunks * 1500;
934
+ const outTok = opts.durationSec / 60 * 150 + 1500;
935
+ const inRate = p.audioIn ?? p.textIn;
936
+ const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
937
+ total += llmUsd;
938
+ lines.push(
939
+ `${opts.model}: ${chunks} chunk${chunks > 1 ? "s" : ""} + describe \u2248 $${llmUsd.toFixed(2)}`
940
+ );
941
+ } else {
942
+ incomplete = true;
943
+ lines.push(`${opts.model}: unpriced`);
944
+ }
945
+ const asr = asrCost(opts.tsProvider, opts.durationSec);
946
+ if (asr !== null && opts.tsProvider !== "none") {
947
+ total += asr;
948
+ lines.push(
949
+ `${opts.tsProvider}: ${(opts.durationSec / 60).toFixed(0)}min \u2248 $${asr.toFixed(2)}`
950
+ );
951
+ }
952
+ if (opts.identify && opts.reasoner) {
953
+ const rp = priceFor(opts.reasoner);
954
+ if (rp) {
955
+ const idUsd = (8e3 * rp.textIn + 1e3 * rp.out) / 1e6;
956
+ total += idUsd;
957
+ lines.push(`${opts.reasoner} (identify) \u2248 $${idUsd.toFixed(3)}`);
958
+ }
959
+ }
960
+ return { totalUsd: total, lines, incomplete };
961
+ }
962
+ function computeReceipt(usage, tsProvider, durationSec) {
963
+ let llmUsd = 0;
964
+ let incomplete = false;
965
+ const lines = [];
966
+ const perModel = {};
967
+ const totals = { calls: 0, inputTokens: 0, outputTokens: 0 };
968
+ const byModel = /* @__PURE__ */ new Map();
969
+ for (const r of usage) {
970
+ totals.calls += r.calls;
971
+ totals.inputTokens += r.inputTokens;
972
+ totals.outputTokens += r.outputTokens;
973
+ const m = byModel.get(r.model) ?? { in: 0, out: 0, calls: 0 };
974
+ m.in += r.inputTokens;
975
+ m.out += r.outputTokens;
976
+ m.calls += r.calls;
977
+ byModel.set(r.model, m);
978
+ }
979
+ for (const [model, m] of byModel) {
980
+ const p = priceFor(model);
981
+ if (!p) {
982
+ incomplete = true;
983
+ lines.push(
984
+ `${model}: ${m.calls} calls \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 unpriced`
985
+ );
986
+ continue;
987
+ }
988
+ const usd = (m.in * (p.audioIn ?? p.textIn) + m.out * p.out) / 1e6;
989
+ llmUsd += usd;
990
+ perModel[model] = usd;
991
+ lines.push(
992
+ `${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
993
+ );
994
+ }
995
+ const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
996
+ if (asrUsd !== null && tsProvider !== "none") {
997
+ perModel[tsProvider] = asrUsd;
998
+ lines.push(
999
+ `${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 $${asrUsd.toFixed(2)}`
1000
+ );
1001
+ }
1002
+ return {
1003
+ totalUsd: llmUsd + (asrUsd ?? 0),
1004
+ llmUsd,
1005
+ asrUsd,
1006
+ lines,
1007
+ totals,
1008
+ perModel,
1009
+ incomplete
1010
+ };
1011
+ }
1012
+ function fmtTok(n) {
1013
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
1014
+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
1015
+ return String(n);
1016
+ }
1017
+
1018
+ // src/core/stats.ts
1019
+ import {
1020
+ appendFileSync as appendFileSync2,
1021
+ existsSync as existsSync2,
1022
+ mkdirSync,
1023
+ readFileSync,
1024
+ rmdirSync,
1025
+ writeFileSync
1026
+ } from "fs";
1027
+ import { homedir } from "os";
1028
+ import { join } from "path";
1029
+ function statsDir() {
1030
+ return process.env.OFFMUTE_HOME || join(homedir(), ".offmute");
1031
+ }
1032
+ function statsEnabled() {
1033
+ return !process.env.OFFMUTE_NO_STATS;
1034
+ }
1035
+ var EMPTY = {
1036
+ runs: 0,
1037
+ mediaSeconds: 0,
1038
+ characters: 0,
1039
+ llmCalls: 0,
1040
+ inputTokens: 0,
1041
+ outputTokens: 0,
1042
+ costUsd: 0,
1043
+ costByModel: {},
1044
+ runsByModel: {}
1045
+ };
1046
+ function readStats() {
1047
+ try {
1048
+ const p = join(statsDir(), "stats.json");
1049
+ if (!existsSync2(p)) return { ...EMPTY };
1050
+ return { ...EMPTY, ...JSON.parse(readFileSync(p, "utf-8")) };
1051
+ } catch {
1052
+ return { ...EMPTY };
1053
+ }
1054
+ }
1055
+ function withStatsLock(dir, fn) {
1056
+ const lock = join(dir, ".stats.lock");
1057
+ const deadline = Date.now() + 2e3;
1058
+ for (; ; ) {
1059
+ try {
1060
+ mkdirSync(lock);
1061
+ break;
1062
+ } catch {
1063
+ if (Date.now() > deadline) break;
1064
+ const until = Date.now() + 25;
1065
+ while (Date.now() < until) {
1066
+ }
1067
+ }
1068
+ }
1069
+ try {
1070
+ fn();
1071
+ } finally {
1072
+ try {
1073
+ rmdirSync(lock);
1074
+ } catch {
1075
+ }
1076
+ }
1077
+ }
1078
+ function recordRun(rec, perModelCost) {
1079
+ if (!statsEnabled()) return;
1080
+ try {
1081
+ const dir = statsDir();
1082
+ mkdirSync(dir, { recursive: true });
1083
+ appendFileSync2(join(dir, "history.jsonl"), JSON.stringify(rec) + "\n");
1084
+ withStatsLock(dir, () => {
1085
+ foldIntoAggregates(rec, perModelCost, dir);
1086
+ });
1087
+ } catch {
1088
+ }
1089
+ }
1090
+ function foldIntoAggregates(rec, perModelCost, dir) {
1091
+ const s = readStats();
1092
+ s.runs += 1;
1093
+ s.mediaSeconds += rec.durationSec;
1094
+ s.characters += rec.characters;
1095
+ s.llmCalls += rec.llmCalls;
1096
+ s.inputTokens += rec.inputTokens;
1097
+ s.outputTokens += rec.outputTokens;
1098
+ if (rec.costUsd !== null) s.costUsd += rec.costUsd;
1099
+ for (const [model, usd] of Object.entries(perModelCost)) {
1100
+ s.costByModel[model] = (s.costByModel[model] ?? 0) + usd;
1101
+ }
1102
+ const tModel = rec.models.transcribe;
1103
+ if (tModel) s.runsByModel[tModel] = (s.runsByModel[tModel] ?? 0) + 1;
1104
+ s.firstRun ??= rec.ts;
1105
+ s.lastRun = rec.ts;
1106
+ writeFileSync(join(dir, "stats.json"), JSON.stringify(s, null, 2));
1107
+ }
1108
+
710
1109
  // src/transcribe/describe.ts
711
- function descriptionPrompt(fileName, instructions) {
712
- return `You are listening to a recording to prepare a transcription engine. Describe what you hear${instructions ? ` (note: ${instructions})` : ""}.
1110
+ function descriptionPrompt(fileName, instructions, sampleCount = 1) {
1111
+ 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.`;
1112
+ return `${sampleNote} Your job is to prepare context for a transcription engine. Describe what you hear${instructions ? ` (note: ${instructions})` : ""}.
713
1113
 
714
1114
  Respond in TWO sections, clearly separated by a line containing only "---":
715
1115
 
@@ -719,17 +1119,24 @@ A short paragraph: what kind of recording this is, the setting, the main topics,
719
1119
  ROSTER
720
1120
  A bulleted speaker roster. For each distinct speaker you can identify, give:
721
1121
  - A short label to use consistently (a name/role if you can infer it, e.g. "Presenter (Hrishi)", else "Speaker A").
722
- - A one-line description (voice, role, accent if notable).
1122
+ - A one-line description anchored to the VOICE itself (pitch, pace, accent, audio quality/mic distance) plus role if evident.
723
1123
  List the people you can distinguish. Do not invent names you didn't hear. If only one person speaks, say so.
724
1124
 
1125
+ 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.
1126
+
725
1127
  File: ${fileName}`;
726
1128
  }
727
- async function describeMeeting(client, model, files, fileName, instructions) {
728
- const res = await client.generate(model, descriptionPrompt(fileName, instructions), files, {
729
- temperature: 0.2,
730
- maxRetries: 3,
731
- logKind: "describe"
732
- });
1129
+ async function describeMeeting(client, model, files, fileName, instructions, audioSampleCount = 1) {
1130
+ const res = await client.generate(
1131
+ model,
1132
+ descriptionPrompt(fileName, instructions, audioSampleCount),
1133
+ files,
1134
+ {
1135
+ temperature: 0.2,
1136
+ maxRetries: 3,
1137
+ logKind: "describe"
1138
+ }
1139
+ );
733
1140
  const text = res.text || "";
734
1141
  const parts = text.split(/\n---\n|\n\s*---\s*\n/);
735
1142
  const description = parts[0]?.trim() || text.trim();
@@ -746,14 +1153,23 @@ var TRANSCRIPT_SCHEMA = {
746
1153
  items: {
747
1154
  type: "OBJECT",
748
1155
  properties: {
749
- speaker: { type: "STRING", description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc." },
750
- start: { type: "STRING", description: "Relative start time as mm:ss (00:00 = start of this audio chunk)" },
1156
+ speaker: {
1157
+ type: "STRING",
1158
+ description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc."
1159
+ },
1160
+ start: {
1161
+ type: "STRING",
1162
+ description: "Relative start time as mm:ss (00:00 = start of this audio chunk)"
1163
+ },
751
1164
  end: { type: "STRING", description: "Relative end time as mm:ss" },
752
- text: { type: "STRING", description: "Verbatim transcribed words, including fillers and false starts" },
1165
+ text: {
1166
+ type: "STRING",
1167
+ description: "Verbatim transcribed words, including fillers and false starts"
1168
+ },
753
1169
  tone: {
754
1170
  type: "ARRAY",
755
1171
  items: { type: "STRING" },
756
- description: "Tone/behavior tags e.g. hesitant, laughing, contemplating, urgent, sarcastic. Empty array if neutral."
1172
+ description: "Tone tags ONLY when something clearly stands out (laughing, sarcastic, agitated, whispering). Empty array for normal speech \u2014 most segments."
757
1173
  }
758
1174
  },
759
1175
  required: ["speaker", "start", "end", "text"]
@@ -768,19 +1184,40 @@ function transcriptionPrompt(ctx) {
768
1184
  `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.`
769
1185
  );
770
1186
  parts.push("");
771
- parts.push("Output one segment per speaker turn (a new segment whenever the speaker changes, or after a long pause, or at an interruption).");
1187
+ parts.push(
1188
+ `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.`
1189
+ );
772
1190
  parts.push("");
773
1191
  parts.push("For each segment provide:");
774
- 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.");
775
- 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.");
776
- parts.push("- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase.");
777
- 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.");
1192
+ parts.push(
1193
+ "- 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."
1194
+ );
1195
+ parts.push(
1196
+ "- 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."
1197
+ );
1198
+ parts.push(
1199
+ "- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase."
1200
+ );
1201
+ parts.push(
1202
+ '- 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".'
1203
+ );
778
1204
  parts.push("");
779
1205
  parts.push("Rules:");
780
- parts.push("- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing.");
781
- parts.push("- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap.");
782
- parts.push("- Do not invent content not present in the audio. If inaudible, write [inaudible].");
783
- parts.push("- Keep speaker labels consistent within this chunk; the same voice = same label.");
1206
+ parts.push(
1207
+ "- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing."
1208
+ );
1209
+ parts.push(
1210
+ "- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap."
1211
+ );
1212
+ parts.push(
1213
+ "- Listen for voice characteristics (pitch, accent, mic distance), not just content. Two people agreeing with each other are still two segments."
1214
+ );
1215
+ parts.push(
1216
+ "- Do not invent content not present in the audio. If inaudible, write [inaudible]."
1217
+ );
1218
+ parts.push(
1219
+ "- Keep speaker labels consistent within this chunk; the same voice = same label."
1220
+ );
784
1221
  if (ctx.description) {
785
1222
  parts.push("");
786
1223
  parts.push("MEETING CONTEXT:");
@@ -788,12 +1225,20 @@ function transcriptionPrompt(ctx) {
788
1225
  }
789
1226
  if (ctx.roster) {
790
1227
  parts.push("");
791
- parts.push("SPEAKER ROSTER (prefer these labels/names when you can identify the voice):");
1228
+ parts.push(
1229
+ "SPEAKER ROSTER (context about who is present \u2014 but its name-to-voice binding may be wrong):"
1230
+ );
792
1231
  parts.push(ctx.roster);
1232
+ parts.push("");
1233
+ parts.push(
1234
+ "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."
1235
+ );
793
1236
  }
794
1237
  if (ctx.previousTail) {
795
1238
  parts.push("");
796
- parts.push("TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):");
1239
+ parts.push(
1240
+ "TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
1241
+ );
797
1242
  parts.push(ctx.previousTail);
798
1243
  }
799
1244
  if (ctx.instructions) {
@@ -802,7 +1247,9 @@ function transcriptionPrompt(ctx) {
802
1247
  parts.push(ctx.instructions);
803
1248
  }
804
1249
  parts.push("");
805
- parts.push("Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }");
1250
+ parts.push(
1251
+ "Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }"
1252
+ );
806
1253
  return parts.join("\n");
807
1254
  }
808
1255
 
@@ -828,7 +1275,10 @@ function timestampToSeconds(timestamp) {
828
1275
  function parseSrtTiming(timingString) {
829
1276
  const parts = timingString.split("-->");
830
1277
  if (parts.length !== 2) return null;
831
- return { start: timestampToSeconds(parts[0].trim()), end: timestampToSeconds(parts[1].trim()) };
1278
+ return {
1279
+ start: timestampToSeconds(parts[0].trim()),
1280
+ end: timestampToSeconds(parts[1].trim())
1281
+ };
832
1282
  }
833
1283
  function formatSrtTiming(startSeconds, endSeconds) {
834
1284
  return `${secondsToTimestamp(startSeconds)} --> ${secondsToTimestamp(endSeconds)}`;
@@ -842,6 +1292,16 @@ function parseMmSs(timeStr) {
842
1292
  if (seconds < 0 || seconds >= 60) return null;
843
1293
  return minutes * 60 + seconds;
844
1294
  }
1295
+ function formatDuration(seconds) {
1296
+ const hours = Math.floor(seconds / 3600);
1297
+ const minutes = Math.floor(seconds % 3600 / 60);
1298
+ const remaining = Math.floor(seconds % 60);
1299
+ const parts = [];
1300
+ if (hours > 0) parts.push(`${hours}h`);
1301
+ if (minutes > 0) parts.push(`${minutes}m`);
1302
+ parts.push(`${remaining}s`);
1303
+ return parts.join(" ");
1304
+ }
845
1305
 
846
1306
  // src/transcribe/llm-transcribe.ts
847
1307
  var MIN_SEGMENTS = 3;
@@ -865,7 +1325,9 @@ function parseLlmSegments(data, chunkOffsetSec) {
865
1325
  const end = toAbsolute(seg.end, chunkOffsetSec);
866
1326
  if (start === null || end === null || end < start) {
867
1327
  dropped++;
868
- logger.debug(`[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`);
1328
+ logger.debug(
1329
+ `[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`
1330
+ );
869
1331
  continue;
870
1332
  }
871
1333
  out.push({
@@ -882,16 +1344,31 @@ function parseLlmSegments(data, chunkOffsetSec) {
882
1344
  }
883
1345
  function validate(segments, chunkDuration) {
884
1346
  if (segments.length < MIN_SEGMENTS) {
885
- return { isValid: false, spanSec: 0, segmentCount: segments.length, message: `only ${segments.length} segments (min ${MIN_SEGMENTS})` };
1347
+ return {
1348
+ isValid: false,
1349
+ spanSec: 0,
1350
+ segmentCount: segments.length,
1351
+ message: `only ${segments.length} segments (min ${MIN_SEGMENTS})`
1352
+ };
886
1353
  }
887
1354
  const first = segments[0].startSec;
888
1355
  const last = segments[segments.length - 1].endSec;
889
1356
  const span = last - first;
890
1357
  const minSpan = chunkDuration * MIN_SPAN_RATIO;
891
1358
  if (span < minSpan) {
892
- 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)` };
1359
+ return {
1360
+ isValid: false,
1361
+ spanSec: span,
1362
+ segmentCount: segments.length,
1363
+ message: `span ${span.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)`
1364
+ };
893
1365
  }
894
- return { isValid: true, spanSec: span, segmentCount: segments.length, message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)` };
1366
+ return {
1367
+ isValid: true,
1368
+ spanSec: span,
1369
+ segmentCount: segments.length,
1370
+ message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)`
1371
+ };
895
1372
  }
896
1373
  async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
897
1374
  const validationRetries = opts.validationRetries ?? 1;
@@ -915,22 +1392,35 @@ async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opt
915
1392
  segments: [],
916
1393
  raw: gen.raw,
917
1394
  usage: gen.usage,
918
- validation: { isValid: false, spanSec: 0, segmentCount: 0, message: gen.error || "no data" },
1395
+ validation: {
1396
+ isValid: false,
1397
+ spanSec: 0,
1398
+ segmentCount: 0,
1399
+ message: gen.error || "no data"
1400
+ },
919
1401
  error: gen.error
920
1402
  };
921
- logger.warn(`[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`);
1403
+ logger.warn(
1404
+ `[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
1405
+ );
922
1406
  continue;
923
1407
  }
924
1408
  const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
925
1409
  const v = validate(segments, opts.chunkDurationSec);
926
1410
  lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
927
1411
  if (v.isValid) {
928
- logger.info(`[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`);
1412
+ logger.info(
1413
+ `[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
1414
+ );
929
1415
  return lastResult;
930
1416
  }
931
- logger.warn(`[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`);
1417
+ logger.warn(
1418
+ `[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
1419
+ );
932
1420
  }
933
- logger.error(`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`);
1421
+ logger.error(
1422
+ `[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
1423
+ );
934
1424
  return lastResult;
935
1425
  }
936
1426
 
@@ -942,8 +1432,8 @@ function tokenize(text) {
942
1432
  const out = [];
943
1433
  for (const raw of text.split(/\s+/)) {
944
1434
  if (!raw) continue;
945
- const norm = normalize(raw);
946
- if (norm) out.push({ original: raw, norm });
1435
+ const norm2 = normalize(raw);
1436
+ if (norm2) out.push({ original: raw, norm: norm2 });
947
1437
  }
948
1438
  return out;
949
1439
  }
@@ -1067,7 +1557,11 @@ function transferTiming(llm, asr, ops) {
1067
1557
  for (const op of ops) {
1068
1558
  if (op.type === "match" || op.type === "substitute") {
1069
1559
  const a = asr[op.asr];
1070
- times[op.llm] = { start: a.start, end: a.end, matched: op.type === "match" && !op.fuzzy };
1560
+ times[op.llm] = {
1561
+ start: a.start,
1562
+ end: a.end,
1563
+ matched: op.type === "match" && !op.fuzzy
1564
+ };
1071
1565
  }
1072
1566
  }
1073
1567
  for (let k = 0; k < times.length; k++) {
@@ -1236,7 +1730,12 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
1236
1730
  tone: [],
1237
1731
  confidence: 0,
1238
1732
  timingSource: "timestamped",
1239
- words: words.map((w) => ({ text: w.text, start: w.start, end: w.end, matched: true })),
1733
+ words: words.map((w) => ({
1734
+ text: w.text,
1735
+ start: w.start,
1736
+ end: w.end,
1737
+ matched: true
1738
+ })),
1240
1739
  sourceIndex: -1
1241
1740
  });
1242
1741
  }
@@ -1249,8 +1748,19 @@ function overlap(s1, e1, s2, e2) {
1249
1748
  return Math.max(0, Math.min(e1, e2) - Math.max(s1, s2));
1250
1749
  }
1251
1750
  function isGenericLabel(label) {
1252
- return /^(speaker\s+[a-z0-9]+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(label.trim());
1751
+ return /^(speaker\s+[a-z0-9]+|voice\s+\S+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(
1752
+ label.trim()
1753
+ );
1754
+ }
1755
+ function countTurnTransitions(utterances, a, b) {
1756
+ const seq = [...utterances].sort((x, y) => x.start - y.start).map((u) => u.speaker).filter((s) => s === a || s === b);
1757
+ let transitions = 0;
1758
+ for (let i = 1; i < seq.length; i++) {
1759
+ if (seq[i] !== seq[i - 1]) transitions++;
1760
+ }
1761
+ return transitions;
1253
1762
  }
1763
+ var MAX_MERGE_TRANSITIONS = 3;
1254
1764
  function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
1255
1765
  const hasDiarization = opts.hasDiarization ?? true;
1256
1766
  const out = segments.map((seg) => ({ seg, asrSpeaker: "" }));
@@ -1302,7 +1812,18 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
1302
1812
  const label = dominantLabel[asrSp] ?? asrSp;
1303
1813
  let groupId;
1304
1814
  if (!isGenericLabel(label)) {
1305
- groupId = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
1815
+ const candidate = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
1816
+ if (candidate && hasDiarization) {
1817
+ const partners = groupAsrVoices[candidate] ?? [];
1818
+ const maxTransitions = Math.max(
1819
+ ...partners.map((p) => countTurnTransitions(asrUtterances, p, asrSp))
1820
+ );
1821
+ if (maxTransitions <= MAX_MERGE_TRANSITIONS) {
1822
+ groupId = candidate;
1823
+ }
1824
+ } else if (candidate) {
1825
+ groupId = candidate;
1826
+ }
1306
1827
  }
1307
1828
  if (!groupId) {
1308
1829
  groupId = asrSp;
@@ -1312,15 +1833,24 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
1312
1833
  groupTalk[groupId] = (groupTalk[groupId] ?? 0) + (asrDuration[asrSp] ?? 0);
1313
1834
  (groupAsrVoices[groupId] ??= []).push(asrSp);
1314
1835
  }
1315
- const groupsByTalk = Object.keys(groupTalk).sort((a, b) => groupTalk[b] - groupTalk[a]);
1836
+ const groupsByTalk = Object.keys(groupTalk).sort(
1837
+ (a, b) => groupTalk[b] - groupTalk[a]
1838
+ );
1316
1839
  const groupToGlobal = {};
1317
1840
  groupsByTalk.forEach((g, i) => {
1318
1841
  groupToGlobal[g] = `Speaker ${String.fromCharCode(65 + i)}`;
1319
1842
  });
1843
+ const labelGroupCount = {};
1844
+ for (const g of groupsByTalk) {
1845
+ const label = groupLabel[g];
1846
+ if (!isGenericLabel(label))
1847
+ labelGroupCount[label] = (labelGroupCount[label] ?? 0) + 1;
1848
+ }
1320
1849
  const displayNames = {};
1321
1850
  for (const g of groupsByTalk) {
1322
1851
  const label = groupLabel[g];
1323
- displayNames[groupToGlobal[g]] = isGenericLabel(label) ? groupToGlobal[g] : label;
1852
+ const contested = (labelGroupCount[label] ?? 0) > 1;
1853
+ displayNames[groupToGlobal[g]] = isGenericLabel(label) || contested ? groupToGlobal[g] : label;
1324
1854
  }
1325
1855
  const llmLabelToAsr = {};
1326
1856
  for (const o of out) {
@@ -1354,6 +1884,111 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
1354
1884
  return { segments: updated, speakers, displayNames, llmLabelToAsr };
1355
1885
  }
1356
1886
 
1887
+ // src/diarize/split-mixed.ts
1888
+ var MIN_RUN_WORDS = 5;
1889
+ var MIN_RUN_SEC = 2;
1890
+ function clusterAt(utterances, t) {
1891
+ let best = "";
1892
+ let bestDist = Infinity;
1893
+ for (const u of utterances) {
1894
+ if (t >= u.start && t <= u.end) return u.speaker;
1895
+ const d = t < u.start ? u.start - t : t - u.end;
1896
+ if (d < bestDist) {
1897
+ bestDist = d;
1898
+ best = u.speaker;
1899
+ }
1900
+ }
1901
+ return best;
1902
+ }
1903
+ function buildRuns(words, utterances) {
1904
+ const clusters = words.map(
1905
+ (w) => w.matched ? clusterAt(utterances, (w.start + w.end) / 2) : null
1906
+ );
1907
+ for (let i = 1; i < clusters.length; i++) {
1908
+ if (clusters[i] === null) clusters[i] = clusters[i - 1] ?? null;
1909
+ }
1910
+ for (let i = clusters.length - 2; i >= 0; i--) {
1911
+ if (clusters[i] === null) clusters[i] = clusters[i + 1] ?? null;
1912
+ }
1913
+ const runs = [];
1914
+ for (let i = 0; i < clusters.length; i++) {
1915
+ const c = clusters[i] ?? "";
1916
+ const last = runs[runs.length - 1];
1917
+ if (last && last.cluster === c) last.endIdx = i + 1;
1918
+ else runs.push({ cluster: c, startIdx: i, endIdx: i + 1 });
1919
+ }
1920
+ return runs;
1921
+ }
1922
+ function runSec(run2, words) {
1923
+ return words[run2.endIdx - 1].end - words[run2.startIdx].start;
1924
+ }
1925
+ function foldShortRuns(runs, words) {
1926
+ let out = runs;
1927
+ let changed = true;
1928
+ while (changed && out.length > 1) {
1929
+ changed = false;
1930
+ for (let i = 0; i < out.length; i++) {
1931
+ const r = out[i];
1932
+ const nWords = r.endIdx - r.startIdx;
1933
+ if (nWords >= MIN_RUN_WORDS || runSec(r, words) >= MIN_RUN_SEC) continue;
1934
+ const prev = out[i - 1];
1935
+ const next = out[i + 1];
1936
+ const target = prev && next ? prev.endIdx - prev.startIdx >= next.endIdx - next.startIdx ? prev : next : prev ?? next;
1937
+ if (!target) continue;
1938
+ if (target === prev) prev.endIdx = r.endIdx;
1939
+ else next.startIdx = r.startIdx;
1940
+ out = out.filter((_, j) => j !== i);
1941
+ changed = true;
1942
+ break;
1943
+ }
1944
+ const merged = [];
1945
+ for (const r of out) {
1946
+ const last = merged[merged.length - 1];
1947
+ if (last && last.cluster === r.cluster) last.endIdx = r.endIdx;
1948
+ else merged.push({ ...r });
1949
+ }
1950
+ out = merged;
1951
+ }
1952
+ return out;
1953
+ }
1954
+ function splitMixedVoiceSegments(segments, utterances) {
1955
+ if (utterances.length === 0) return segments;
1956
+ const out = [];
1957
+ let splits = 0;
1958
+ for (const seg of segments) {
1959
+ const matched = seg.words.filter((w) => w.matched).length;
1960
+ if (seg.words.length < MIN_RUN_WORDS * 2 || matched < seg.words.length * 0.4) {
1961
+ out.push(seg);
1962
+ continue;
1963
+ }
1964
+ const runs = foldShortRuns(buildRuns(seg.words, utterances), seg.words);
1965
+ if (runs.length <= 1) {
1966
+ out.push(seg);
1967
+ continue;
1968
+ }
1969
+ splits += runs.length - 1;
1970
+ const lens = runs.map((r) => r.endIdx - r.startIdx);
1971
+ const dominantIdx = lens.indexOf(Math.max(...lens));
1972
+ runs.forEach((run2, ri) => {
1973
+ const words = seg.words.slice(run2.startIdx, run2.endIdx);
1974
+ out.push({
1975
+ ...seg,
1976
+ start: words[0].start,
1977
+ end: words[words.length - 1].end,
1978
+ text: words.map((w) => w.text).join(" "),
1979
+ words,
1980
+ speaker: ri === dominantIdx ? seg.speaker : `Voice ${run2.cluster}`
1981
+ });
1982
+ });
1983
+ }
1984
+ if (splits > 0) {
1985
+ logger.info(
1986
+ `split ${splits} mixed-voice boundary(ies) across ${segments.length} segments`
1987
+ );
1988
+ }
1989
+ return out.sort((a, b) => a.start - b.start);
1990
+ }
1991
+
1357
1992
  // src/providers/openai-compat.ts
1358
1993
  var PROVIDER_BASE = {
1359
1994
  deepseek: "https://api.deepseek.com/v1",
@@ -1377,7 +2012,7 @@ var OpenAICompatClient = class _OpenAICompatClient {
1377
2012
  }
1378
2013
  async chat(model, messages, opts = {}) {
1379
2014
  const m = model ?? this.defaultModel;
1380
- const maxRetries = opts.maxRetries ?? 2;
2015
+ const maxRetries = opts.maxRetries ?? 5;
1381
2016
  const body = {
1382
2017
  model: m,
1383
2018
  messages,
@@ -1387,6 +2022,9 @@ var OpenAICompatClient = class _OpenAICompatClient {
1387
2022
  if (opts.responseJson) {
1388
2023
  body.response_format = { type: "json_object" };
1389
2024
  }
2025
+ if (this.providerName === "gemini") {
2026
+ body.reasoning_effort = "low";
2027
+ }
1390
2028
  let lastError;
1391
2029
  const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
1392
2030
  for (let attempt = 0; attempt < maxRetries; attempt++) {
@@ -1424,6 +2062,14 @@ var OpenAICompatClient = class _OpenAICompatClient {
1424
2062
  return { text, usage };
1425
2063
  } catch (err) {
1426
2064
  lastError = err instanceof Error ? err.message : String(err);
2065
+ if (body.response_format && /response_format/i.test(lastError)) {
2066
+ delete body.response_format;
2067
+ continue;
2068
+ }
2069
+ if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
2070
+ delete body.reasoning_effort;
2071
+ continue;
2072
+ }
1427
2073
  logLlmCall({
1428
2074
  ts: new Date(t0).toISOString(),
1429
2075
  provider: this.providerName,
@@ -1435,61 +2081,109 @@ var OpenAICompatClient = class _OpenAICompatClient {
1435
2081
  attempt: attempt + 1,
1436
2082
  error: lastError
1437
2083
  });
1438
- if (attempt < maxRetries - 1) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
2084
+ if (attempt < maxRetries - 1)
2085
+ await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
1439
2086
  }
1440
2087
  }
1441
2088
  return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
1442
2089
  }
1443
2090
  async chatJson(model, messages, opts = {}) {
1444
- const res = await this.chat(model, messages, { ...opts, responseJson: true });
1445
- if (res.error || !res.text) return { data: null, raw: res.text, error: res.error };
1446
- try {
1447
- let txt = res.text.trim();
1448
- const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
1449
- if (fence && fence[1]) txt = fence[1];
1450
- return { data: JSON.parse(txt), raw: res.text };
1451
- } catch (err) {
1452
- return { data: null, raw: res.text, error: `JSON parse: ${err instanceof Error ? err.message : String(err)}` };
2091
+ let lastRaw = "";
2092
+ let lastError;
2093
+ for (let attempt = 0; attempt < 2; attempt++) {
2094
+ const res = await this.chat(model, messages, { ...opts, responseJson: true });
2095
+ lastRaw = res.text;
2096
+ lastError = res.error;
2097
+ if (res.error || !res.text) continue;
2098
+ try {
2099
+ let txt = res.text.trim();
2100
+ const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
2101
+ if (fence && fence[1]) txt = fence[1];
2102
+ return { data: JSON.parse(txt), raw: res.text };
2103
+ } catch (err) {
2104
+ lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
2105
+ }
1453
2106
  }
2107
+ return { data: null, raw: lastRaw, error: lastError };
1454
2108
  }
1455
2109
  };
1456
2110
 
1457
2111
  // src/diarize/identify.ts
2112
+ var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
1458
2113
  function buildTranscriptExcerpt(segments, speakers) {
2114
+ const speakerHeader = (sp) => {
2115
+ const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
2116
+ return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
2117
+ };
2118
+ const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
2119
+ if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
2120
+ const parts2 = [
2121
+ "SPEAKERS:",
2122
+ ...speakers.map((sp) => `- ${speakerHeader(sp)}`),
2123
+ "",
2124
+ "FULL TRANSCRIPT (in order):"
2125
+ ];
2126
+ for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
2127
+ return parts2.join("\n");
2128
+ }
1459
2129
  const bySpeaker = {};
1460
2130
  for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
1461
2131
  const parts = [];
1462
2132
  for (const sp of speakers) {
1463
2133
  const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
1464
- const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
1465
- parts.push(
1466
- `### ${sp.id} (${sp.name || "unknown"}, ${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s${voices})`
1467
- );
2134
+ parts.push(`### ${speakerHeader(sp)}`);
1468
2135
  for (const s of segs) parts.push(` ${s.text}`);
1469
2136
  }
1470
2137
  return parts.join("\n");
1471
2138
  }
1472
- function identifyPrompt(transcriptExcerpt, roster, knownSpeakers) {
1473
- 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.
2139
+ function identifyPrompt(transcriptExcerpt, roster, knownSpeakers, nameHints, sourceFileName) {
2140
+ const hintBlock = nameHints && Object.keys(nameHints).length ? `
2141
+ 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):
2142
+ ${Object.entries(
2143
+ nameHints
2144
+ ).map(([id, n]) => ` ${id} was tentatively called "${n}"`).join("\n")}
2145
+ ` : "";
2146
+ 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.
1474
2147
 
1475
2148
  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 ("").
1476
2149
 
2150
+ 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.
2151
+
2152
+ 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.
2153
+
2154
+ 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).
2155
+
1477
2156
  ${knownSpeakers && knownSpeakers.length ? `Known possible speakers: ${knownSpeakers.join(", ")}
2157
+ ` : ""}${sourceFileName ? `RECORDING FILENAME (often names participants): ${sourceFileName}
1478
2158
  ` : ""}ROSTER:
1479
2159
  ${roster}
1480
-
1481
- TRANSCRIPT EXCERPTS BY SPEAKER:
2160
+ ${hintBlock}
2161
+ TRANSCRIPT:
1482
2162
  ${transcriptExcerpt}
1483
2163
 
1484
- 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" }
1485
- Use the EXACT speaker id strings from the headers above (e.g. "Speaker A").`;
2164
+ 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" }
2165
+ 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.`;
1486
2166
  }
1487
- async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers) {
2167
+ async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers, nameHints, sourceFileName) {
1488
2168
  const excerpt = buildTranscriptExcerpt(segments, speakers);
1489
2169
  const { data, error } = await client.chatJson(
1490
2170
  model,
1491
- [{ role: "user", content: identifyPrompt(excerpt, roster, knownSpeakers) }],
1492
- { temperature: 0.1, maxTokens: 2e3, logKind: "identify" }
2171
+ [
2172
+ {
2173
+ role: "user",
2174
+ content: identifyPrompt(
2175
+ excerpt,
2176
+ roster,
2177
+ knownSpeakers,
2178
+ nameHints,
2179
+ sourceFileName
2180
+ )
2181
+ }
2182
+ ],
2183
+ // 8000 tokens: verbose models quote long verbatim evidence, and Gemini's compat
2184
+ // endpoint spends part of the budget on thinking — tighter caps truncated
2185
+ // mid-JSON and silently emptied whole identify passes (observed live, twice).
2186
+ { temperature: 0.1, maxTokens: 8e3, logKind: "identify" }
1493
2187
  );
1494
2188
  if (error || !data) {
1495
2189
  return { nameMap: {}, speakers: [], reasoning: error || "no response" };
@@ -1501,6 +2195,368 @@ async function identifySpeakers(client, model, segments, speakers, roster, known
1501
2195
  return { nameMap, speakers: data.speakers || [], reasoning: data.reasoning || "" };
1502
2196
  }
1503
2197
 
2198
+ // src/diarize/identify2.ts
2199
+ var norm = (s) => s.toLowerCase().replace(/['’]/g, "").replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
2200
+ function withinOneEdit(a, b) {
2201
+ if (a === b) return true;
2202
+ if (Math.abs(a.length - b.length) > 1) return false;
2203
+ const [s, l] = a.length <= b.length ? [a, b] : [b, a];
2204
+ let i = 0;
2205
+ let j = 0;
2206
+ let edits = 0;
2207
+ while (i < s.length && j < l.length) {
2208
+ if (s[i] === l[j]) {
2209
+ i++;
2210
+ j++;
2211
+ continue;
2212
+ }
2213
+ if (++edits > 1) return false;
2214
+ if (s.length === l.length) i++;
2215
+ j++;
2216
+ }
2217
+ return edits + (l.length - j) <= 1;
2218
+ }
2219
+ function tokensMatch(a, b) {
2220
+ if (a === b) return true;
2221
+ return a.length >= 5 && b.length >= 5 && withinOneEdit(a, b);
2222
+ }
2223
+ function namesMatch(a, b) {
2224
+ const na = norm(a);
2225
+ const nb = norm(b);
2226
+ if (!na || !nb) return false;
2227
+ if (na === nb) return true;
2228
+ const ta = na.split(" ");
2229
+ const tb = nb.split(" ");
2230
+ const [small, big] = ta.length <= tb.length ? [ta, tb] : [tb, ta];
2231
+ return small.every((t) => big.some((u) => tokensMatch(t, u)));
2232
+ }
2233
+ function evidenceInTranscript(evidence, transcript) {
2234
+ if (!evidence) return false;
2235
+ const ne = norm(evidence);
2236
+ if (ne.length < 8) return false;
2237
+ return transcript.includes(ne);
2238
+ }
2239
+ var INTRO_RE = /\b(?:[Mm]y name is|I am|I'm)[,\s]+([A-Z][\p{L}'’-]+(?:\s+[A-Z][\p{L}'’-]+)?)/gu;
2240
+ var INTRO_STOPWORDS = /* @__PURE__ */ new Set([
2241
+ "i",
2242
+ "im",
2243
+ "ive",
2244
+ "id",
2245
+ "ill",
2246
+ "you",
2247
+ "we",
2248
+ "they",
2249
+ "he",
2250
+ "she",
2251
+ "it",
2252
+ "so",
2253
+ "not",
2254
+ "just",
2255
+ "here",
2256
+ "there",
2257
+ "going",
2258
+ "gonna",
2259
+ "really",
2260
+ "very",
2261
+ "also",
2262
+ "still",
2263
+ "sure",
2264
+ "sorry",
2265
+ "happy",
2266
+ "glad",
2267
+ "excited",
2268
+ "curious",
2269
+ "the",
2270
+ "a",
2271
+ "an",
2272
+ "okay",
2273
+ "ok",
2274
+ "now",
2275
+ "like",
2276
+ "actually",
2277
+ "basically",
2278
+ "kind",
2279
+ "sort",
2280
+ "definitely"
2281
+ ]);
2282
+ function findSelfIntroductions(segments) {
2283
+ const out = [];
2284
+ for (const seg of segments) {
2285
+ for (const m of seg.text.matchAll(INTRO_RE)) {
2286
+ const name = m[1].trim();
2287
+ const tokens = name.split(/\s+/).map((t) => t.toLowerCase().replace(/['’]/g, ""));
2288
+ if (tokens.some((t) => INTRO_STOPWORDS.has(t))) continue;
2289
+ if (name.replace(/[^\p{L}]/gu, "").length < 3) continue;
2290
+ out.push({
2291
+ speakerId: seg.speaker,
2292
+ introducedName: name,
2293
+ segmentText: seg.text.slice(0, 160)
2294
+ });
2295
+ }
2296
+ }
2297
+ return out;
2298
+ }
2299
+ function pickCompleteName(a, b) {
2300
+ if (!a) return b ?? "";
2301
+ if (!b) return a;
2302
+ return b.trim().split(/\s+/).length > a.trim().split(/\s+/).length ? b.trim() : a.trim();
2303
+ }
2304
+ function adjudicate(speakerId, a, b, transcriptNorm, intro, introCorroborated = false) {
2305
+ const base = {
2306
+ speakerId,
2307
+ nameA: a.name,
2308
+ nameB: b?.name,
2309
+ outcome: "kept-generic"
2310
+ };
2311
+ const aName = a.name?.trim() || void 0;
2312
+ const bName = b?.name?.trim() || void 0;
2313
+ if (b === void 0) {
2314
+ if (!aName) return base;
2315
+ return { ...base, outcome: "a-only", finalName: aName };
2316
+ }
2317
+ if (aName && bName && namesMatch(aName, bName)) {
2318
+ return { ...base, outcome: "agreed", finalName: pickCompleteName(aName, bName) };
2319
+ }
2320
+ if (intro) {
2321
+ if (aName && namesMatch(aName, intro))
2322
+ return { ...base, outcome: "tripwire", finalName: aName, note: `intro "${intro}"` };
2323
+ if (bName && namesMatch(bName, intro))
2324
+ return { ...base, outcome: "tripwire", finalName: bName, note: `intro "${intro}"` };
2325
+ if (introCorroborated) {
2326
+ return {
2327
+ ...base,
2328
+ outcome: "tripwire",
2329
+ finalName: intro,
2330
+ note: `intro "${intro}" corroborated by roster/known speakers`
2331
+ };
2332
+ }
2333
+ }
2334
+ if (aName && !bName) return { ...base, outcome: "a-only", finalName: aName };
2335
+ if (bName && !aName) return { ...base, outcome: "b-only", finalName: bName };
2336
+ const aOk = evidenceInTranscript(a.evidence, transcriptNorm);
2337
+ const bOk = evidenceInTranscript(b.evidence, transcriptNorm);
2338
+ if (aOk && !bOk)
2339
+ return {
2340
+ ...base,
2341
+ outcome: "evidence-break",
2342
+ finalName: aName,
2343
+ note: "B evidence not in transcript"
2344
+ };
2345
+ if (bOk && !aOk)
2346
+ return {
2347
+ ...base,
2348
+ outcome: "evidence-break",
2349
+ finalName: bName,
2350
+ note: "A evidence not in transcript"
2351
+ };
2352
+ return {
2353
+ ...base,
2354
+ outcome: "kept-generic",
2355
+ note: "disagreement unresolved \u2014 not inventing a name"
2356
+ };
2357
+ }
2358
+ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts) {
2359
+ const mode = opts.mode ?? "dual";
2360
+ const runPass = (r) => identifySpeakers(
2361
+ r.client,
2362
+ r.model,
2363
+ segments,
2364
+ speakers,
2365
+ opts.roster,
2366
+ opts.knownSpeakers,
2367
+ opts.nameHints,
2368
+ opts.sourceFileName
2369
+ );
2370
+ const wantB = mode === "dual" && reasonerB !== null;
2371
+ const [resA, resB] = await Promise.all([
2372
+ runPass(reasonerA),
2373
+ wantB ? runPass(reasonerB) : Promise.resolve(void 0)
2374
+ ]);
2375
+ const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
2376
+ if (passFailed(resA) && (!wantB || passFailed(resB))) {
2377
+ logger.warn(
2378
+ `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).`
2379
+ );
2380
+ }
2381
+ const transcriptNorm = norm(segments.map((s) => s.text).join(" "));
2382
+ const tripwires = findSelfIntroductions(segments);
2383
+ const introBySpeaker = /* @__PURE__ */ new Map();
2384
+ const conflicted = /* @__PURE__ */ new Set();
2385
+ for (const t of tripwires) {
2386
+ const prev = introBySpeaker.get(t.speakerId);
2387
+ if (prev && !namesMatch(prev, t.introducedName)) conflicted.add(t.speakerId);
2388
+ else introBySpeaker.set(t.speakerId, t.introducedName);
2389
+ }
2390
+ for (const id of conflicted) introBySpeaker.delete(id);
2391
+ const byIdA = new Map(resA.speakers.map((s) => [s.id, s]));
2392
+ const byIdB = resB ? new Map(resB.speakers.map((s) => [s.id, s])) : void 0;
2393
+ const decisions = [];
2394
+ const corroborationText = norm(
2395
+ `${opts.roster ?? ""} ${(opts.knownSpeakers ?? []).join(" ")}`
2396
+ );
2397
+ const isCorroborated = (name) => {
2398
+ if (!name) return false;
2399
+ const n = norm(name);
2400
+ return n.length >= 3 && corroborationText.includes(n);
2401
+ };
2402
+ const nameMap = {};
2403
+ for (const sp of speakers) {
2404
+ const a = byIdA.get(sp.id) ?? { name: resA.nameMap[sp.id] };
2405
+ const b = byIdB ? byIdB.get(sp.id) ?? { name: resB.nameMap[sp.id] } : void 0;
2406
+ const intro = introBySpeaker.get(sp.id);
2407
+ const d = adjudicate(
2408
+ sp.id,
2409
+ a ?? {},
2410
+ wantB ? b ?? {} : void 0,
2411
+ transcriptNorm,
2412
+ intro,
2413
+ isCorroborated(intro)
2414
+ );
2415
+ decisions.push(d);
2416
+ if (d.finalName) nameMap[sp.id] = d.finalName;
2417
+ }
2418
+ const STRENGTH = {
2419
+ agreed: 4,
2420
+ tripwire: 3,
2421
+ "evidence-break": 2,
2422
+ "a-only": 1,
2423
+ "b-only": 1,
2424
+ elimination: 1,
2425
+ "conflict-fallback": 0,
2426
+ "kept-generic": 0
2427
+ };
2428
+ const named = decisions.filter((d) => d.finalName);
2429
+ for (let i = 0; i < named.length; i++) {
2430
+ for (let j = i + 1; j < named.length; j++) {
2431
+ const di = named[i];
2432
+ const dj = named[j];
2433
+ if (!di.finalName || !dj.finalName) continue;
2434
+ if (!namesMatch(di.finalName, dj.finalName)) continue;
2435
+ const si = STRENGTH[di.outcome];
2436
+ const sj = STRENGTH[dj.outcome];
2437
+ const losers = si === sj ? [di, dj] : si < sj ? [di] : [dj];
2438
+ for (const loser of losers) {
2439
+ loser.note = `demoted: "${loser.finalName}" also claimed by another speaker with ${si === sj ? "equal" : "stronger"} evidence`;
2440
+ loser.finalName = void 0;
2441
+ loser.outcome = "conflict-fallback";
2442
+ delete nameMap[loser.speakerId];
2443
+ }
2444
+ }
2445
+ }
2446
+ if (opts.knownSpeakers?.length) {
2447
+ const unusedNames = opts.knownSpeakers.filter(
2448
+ (n) => !decisions.some((d) => d.finalName && namesMatch(d.finalName, n))
2449
+ );
2450
+ const unnamed = decisions.filter((d) => !d.finalName);
2451
+ if (unusedNames.length === 1 && unnamed.length === 1) {
2452
+ const d = unnamed[0];
2453
+ d.finalName = unusedNames[0];
2454
+ d.outcome = "elimination";
2455
+ d.note = `only remaining known speaker`;
2456
+ nameMap[d.speakerId] = d.finalName;
2457
+ logger.info(
2458
+ `identify: "${d.speakerId}" \u2192 ${d.finalName} (by elimination from --speakers)`
2459
+ );
2460
+ }
2461
+ }
2462
+ for (const d of decisions) {
2463
+ if (d.outcome === "conflict-fallback") {
2464
+ logger.info(`identify: "${d.speakerId}" kept generic \u2014 ${d.note}`);
2465
+ }
2466
+ if (d.outcome === "kept-generic" && (d.nameA || d.nameB)) {
2467
+ logger.info(
2468
+ `identify: kept "${d.speakerId}" generic \u2014 passes disagreed (${d.nameA ?? "\u2014"} vs ${d.nameB ?? "\u2014"})`
2469
+ );
2470
+ } else if (d.outcome === "tripwire") {
2471
+ logger.info(
2472
+ `identify: "${d.speakerId}" \u2192 ${d.finalName} (self-introduction tripwire)`
2473
+ );
2474
+ }
2475
+ }
2476
+ return {
2477
+ nameMap,
2478
+ decisions,
2479
+ tripwires,
2480
+ passA: { ...resA, model: reasonerA.model },
2481
+ passB: resB ? { ...resB, model: reasonerB.model } : void 0
2482
+ };
2483
+ }
2484
+
2485
+ // src/providers/reasoner.ts
2486
+ var PROVIDERS = {
2487
+ deepseek: { baseUrl: "https://api.deepseek.com/v1", keyName: "deepseek" },
2488
+ openai: { baseUrl: "https://api.openai.com/v1", keyName: "openai" },
2489
+ groq: { baseUrl: "https://api.groq.com/openai/v1", keyName: "groq" },
2490
+ gemini: {
2491
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
2492
+ keyName: "gemini"
2493
+ },
2494
+ zai: { baseUrl: "https://api.z.ai/api/paas/v4", keyName: "zai" },
2495
+ kimi: { baseUrl: "https://api.moonshot.ai/v1", keyName: "kimi" },
2496
+ anthropic: { baseUrl: "https://api.anthropic.com/v1", keyName: "anthropic" }
2497
+ };
2498
+ function inferProvider(model) {
2499
+ const m = model.toLowerCase();
2500
+ if (m.startsWith("deepseek")) return "deepseek";
2501
+ if (m.startsWith("gemini") || m.startsWith("gemma")) return "gemini";
2502
+ if (m.startsWith("glm")) return "zai";
2503
+ if (m.startsWith("kimi") || m.startsWith("moonshot")) return "kimi";
2504
+ if (m.startsWith("claude")) return "anthropic";
2505
+ if (m.startsWith("gpt") || m.startsWith("o1") || m.startsWith("o3") || m.startsWith("o4"))
2506
+ return "openai";
2507
+ if (m.includes("llama") || m.includes("mixtral")) return "groq";
2508
+ return "openai";
2509
+ }
2510
+ function resolveReasonerInfo(spec) {
2511
+ let provider;
2512
+ let model;
2513
+ const colon = spec.indexOf(":");
2514
+ if (colon > 0 && PROVIDERS[spec.slice(0, colon)]) {
2515
+ provider = spec.slice(0, colon);
2516
+ model = spec.slice(colon + 1);
2517
+ } else {
2518
+ model = spec;
2519
+ provider = inferProvider(spec);
2520
+ }
2521
+ const p = PROVIDERS[provider] ?? PROVIDERS.openai;
2522
+ return { provider, model, keyName: p.keyName, baseUrl: p.baseUrl };
2523
+ }
2524
+ function reasonerKey(info, keys) {
2525
+ if (info.keyName === "gemini") return keys.gemini || keys.google;
2526
+ return keys[info.keyName];
2527
+ }
2528
+ function resolveReasoner(spec, keys) {
2529
+ const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
2530
+ (s) => !!s
2531
+ );
2532
+ for (const c of candidates) {
2533
+ const info = resolveReasonerInfo(c);
2534
+ const key = reasonerKey(info, keys);
2535
+ if (key) {
2536
+ return {
2537
+ client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2538
+ info
2539
+ };
2540
+ }
2541
+ }
2542
+ return null;
2543
+ }
2544
+ function resolveSecondReasoner(first, keys) {
2545
+ const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
2546
+ for (const c of candidates) {
2547
+ const info = resolveReasonerInfo(c);
2548
+ if (info.provider === first.provider) continue;
2549
+ const key = reasonerKey(info, keys);
2550
+ if (key) {
2551
+ return {
2552
+ client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2553
+ info
2554
+ };
2555
+ }
2556
+ }
2557
+ return null;
2558
+ }
2559
+
1504
2560
  // src/finalize/finalize.ts
1505
2561
  var MIN_DUR = 0.5;
1506
2562
  var MAX_DUR = 7;
@@ -1519,6 +2575,87 @@ function timeOverlapFrac(a, b) {
1519
2575
  const shorter = Math.min(a.end - a.start, b.end - b.start);
1520
2576
  return shorter > 0 ? ov / shorter : 0;
1521
2577
  }
2578
+ var SEAM_WINDOW = 250;
2579
+ var SEAM_MIN_TOKENS = 6;
2580
+ var SEAM_MIN_SCORE_RATIO = 0.5;
2581
+ function suffixPrefixOverlap(a, b) {
2582
+ const n = a.length;
2583
+ const m = b.length;
2584
+ if (n === 0 || m === 0) return null;
2585
+ const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
2586
+ const origin = Array.from(
2587
+ { length: n + 1 },
2588
+ () => new Array(m + 1).fill(0)
2589
+ );
2590
+ for (let i = 0; i <= n; i++) {
2591
+ dp[i][0] = 0;
2592
+ origin[i][0] = i;
2593
+ }
2594
+ for (let j = 1; j <= m; j++) {
2595
+ dp[0][j] = -j;
2596
+ origin[0][j] = 0;
2597
+ }
2598
+ for (let i = 1; i <= n; i++) {
2599
+ for (let j = 1; j <= m; j++) {
2600
+ const diag = dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 1 : -1);
2601
+ const up = dp[i - 1][j] - 1;
2602
+ const left = dp[i][j - 1] - 1;
2603
+ if (diag >= up && diag >= left) {
2604
+ dp[i][j] = diag;
2605
+ origin[i][j] = origin[i - 1][j - 1];
2606
+ } else if (up >= left) {
2607
+ dp[i][j] = up;
2608
+ origin[i][j] = origin[i - 1][j];
2609
+ } else {
2610
+ dp[i][j] = left;
2611
+ origin[i][j] = origin[i][j - 1];
2612
+ }
2613
+ }
2614
+ }
2615
+ let bestJ = 0;
2616
+ let bestScore = -Infinity;
2617
+ for (let j = 1; j <= m; j++) {
2618
+ if (dp[n][j] > bestScore) {
2619
+ bestScore = dp[n][j];
2620
+ bestJ = j;
2621
+ }
2622
+ }
2623
+ if (bestJ < SEAM_MIN_TOKENS) return null;
2624
+ if (bestScore < bestJ * SEAM_MIN_SCORE_RATIO) return null;
2625
+ return { aStart: origin[n][bestJ], bLen: bestJ };
2626
+ }
2627
+ function trimSeamOverlaps(segments) {
2628
+ const sorted = [...segments].sort((a, b) => a.start - b.start);
2629
+ const lastIdxBySpeaker = /* @__PURE__ */ new Map();
2630
+ const out = [];
2631
+ for (const seg of sorted) {
2632
+ const prevIdx = lastIdxBySpeaker.get(seg.speaker);
2633
+ const prev = prevIdx !== void 0 ? out[prevIdx] : void 0;
2634
+ if (prev && prev.words?.length && seg.words?.length) {
2635
+ const prevWin = Math.min(SEAM_WINDOW, prev.words.length);
2636
+ const prevToks = prev.words.slice(-prevWin).map((w) => tokenize(w.text)[0]?.norm ?? "");
2637
+ const segToks = seg.words.slice(0, SEAM_WINDOW).map((w) => tokenize(w.text)[0]?.norm ?? "");
2638
+ const hit = suffixPrefixOverlap(prevToks, segToks);
2639
+ if (hit) {
2640
+ const trimFrom = prev.words.length - prevWin + hit.aStart;
2641
+ const kept = prev.words.slice(0, trimFrom);
2642
+ if (kept.length === 0) {
2643
+ out[prevIdx] = null;
2644
+ } else {
2645
+ out[prevIdx] = {
2646
+ ...prev,
2647
+ words: kept,
2648
+ end: kept[kept.length - 1].end,
2649
+ text: kept.map((w) => w.text).join(" ")
2650
+ };
2651
+ }
2652
+ }
2653
+ }
2654
+ out.push(seg);
2655
+ lastIdxBySpeaker.set(seg.speaker, out.length - 1);
2656
+ }
2657
+ return out.filter((s) => s !== null);
2658
+ }
1522
2659
  function dedupSegments(segments) {
1523
2660
  const sorted = [...segments].sort((a, b) => a.start - b.start);
1524
2661
  const kept = [];
@@ -1574,7 +2711,7 @@ function clampAndFix(segments) {
1574
2711
  }
1575
2712
  function finalizeSegments(segments, opts = {}) {
1576
2713
  const minSeg = opts.minSegmentSec ?? 0.2;
1577
- let deduped = dedupSegments(segments);
2714
+ let deduped = dedupSegments(trimSeamOverlaps(segments));
1578
2715
  deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
1579
2716
  const out = deduped.map((s, i) => ({
1580
2717
  id: i + 1,
@@ -1596,11 +2733,17 @@ function finalizeSegments(segments, opts = {}) {
1596
2733
  // src/finalize/format.ts
1597
2734
  var MAX_CHARS = 84;
1598
2735
  var MAX_BLOCK_SEC = 7;
1599
- function splitIntoBlocks(seg) {
1600
- const words = seg.words && seg.words.length > 0 ? seg.words : null;
1601
- if (!words) {
1602
- return [{ start: seg.start, end: seg.end, text: seg.text }];
1603
- }
2736
+ function compactTime(sec) {
2737
+ const s = Math.max(0, Math.floor(sec));
2738
+ const h = Math.floor(s / 3600);
2739
+ const m = Math.floor(s % 3600 / 60);
2740
+ const r = s % 60;
2741
+ const mm = m.toString().padStart(2, "0");
2742
+ const rr = r.toString().padStart(2, "0");
2743
+ return h > 0 ? `${h}:${mm}:${rr}` : `${mm}:${rr}`;
2744
+ }
2745
+ function splitByWords(seg) {
2746
+ const words = seg.words;
1604
2747
  const blocks = [];
1605
2748
  let curWords = [];
1606
2749
  let curLen = 0;
@@ -1627,6 +2770,36 @@ function splitIntoBlocks(seg) {
1627
2770
  curLen += addLen;
1628
2771
  }
1629
2772
  flush();
2773
+ return blocks;
2774
+ }
2775
+ function splitByChars(seg) {
2776
+ const text = seg.text.trim();
2777
+ if (text.length <= MAX_CHARS) return [{ start: seg.start, end: seg.end, text }];
2778
+ const words = text.split(/\s+/);
2779
+ const lines = [];
2780
+ let cur = "";
2781
+ for (const w of words) {
2782
+ if (cur && cur.length + 1 + w.length > MAX_CHARS) {
2783
+ lines.push(cur);
2784
+ cur = w;
2785
+ } else {
2786
+ cur = cur ? `${cur} ${w}` : w;
2787
+ }
2788
+ }
2789
+ if (cur) lines.push(cur);
2790
+ const total = lines.reduce((n, l) => n + l.length, 0) || 1;
2791
+ const dur = Math.max(0, seg.end - seg.start);
2792
+ const blocks = [];
2793
+ let t = seg.start;
2794
+ for (const line of lines) {
2795
+ const span = line.length / total * dur;
2796
+ blocks.push({ start: t, end: Math.min(seg.end, t + span), text: line });
2797
+ t += span;
2798
+ }
2799
+ return blocks;
2800
+ }
2801
+ function splitIntoBlocks(seg) {
2802
+ const blocks = seg.words && seg.words.length > 0 ? splitByWords(seg) : splitByChars(seg);
1630
2803
  return blocks.length ? blocks : [{ start: seg.start, end: seg.end, text: seg.text }];
1631
2804
  }
1632
2805
  function formatSrt(result, opts = {}) {
@@ -1637,54 +2810,247 @@ function formatSrt(result, opts = {}) {
1637
2810
  for (const seg of result.segments) {
1638
2811
  const tone = showTone && seg.tone && seg.tone.length ? ` (${seg.tone.join(", ")})` : "";
1639
2812
  const speaker = labelSpeakers ? `${seg.speakerName || seg.speaker}: ` : "";
1640
- for (const b of splitIntoBlocks(seg)) {
1641
- blocks.push(`${idx}
2813
+ const segBlocks = splitIntoBlocks(seg);
2814
+ for (let i = 0; i < segBlocks.length; i++) {
2815
+ const b = segBlocks[i];
2816
+ const t = i === 0 ? tone : "";
2817
+ blocks.push(
2818
+ `${idx}
1642
2819
  ${formatSrtTiming(b.start, b.end)}
1643
- ${speaker}${b.text}${tone}
1644
- `);
2820
+ ${speaker}${b.text}${t}
2821
+ `
2822
+ );
1645
2823
  idx++;
1646
2824
  }
1647
2825
  }
1648
2826
  return blocks.join("\n");
1649
2827
  }
1650
- function formatMarkdown(result, opts = {}) {
2828
+ function groupBySpeaker(segments) {
2829
+ const groups = [];
2830
+ for (const seg of segments) {
2831
+ const last = groups[groups.length - 1];
2832
+ const key = (s) => s.speakerName || s.speaker;
2833
+ if (last && key(last[0]) === key(seg)) last.push(seg);
2834
+ else groups.push([seg]);
2835
+ }
2836
+ return groups;
2837
+ }
2838
+ function groupText(group, showTone) {
2839
+ const parts = [];
2840
+ let lastTone = "";
2841
+ for (const s of group) {
2842
+ const toneStr = s.tone && s.tone.length ? s.tone.join(", ") : "";
2843
+ if (showTone && toneStr && toneStr !== lastTone) {
2844
+ parts.push(`*(${toneStr})* ${s.text}`);
2845
+ } else {
2846
+ parts.push(s.text);
2847
+ }
2848
+ lastTone = toneStr;
2849
+ }
2850
+ return parts.join(" ");
2851
+ }
2852
+ function mdHeader(result, opts) {
1651
2853
  const parts = [];
1652
2854
  parts.push(`# ${opts.title || "Transcript"}
1653
2855
  `);
1654
- parts.push(`*Duration: ${Math.round(result.metadata.duration)}s \xB7 Speakers: ${result.speakers.length}*
1655
- `);
2856
+ parts.push(
2857
+ `*Duration: ${formatDuration(result.metadata.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns*
2858
+ `
2859
+ );
1656
2860
  parts.push("\n## Speakers\n");
1657
2861
  for (const s of result.speakers) {
1658
- const talk = s.talkTime ? ` (${Math.round(s.talkTime)}s)` : "";
1659
- parts.push(`- **${s.name || s.id}**${talk}`);
2862
+ const talk = s.talkTime ? ` \u2014 ${formatDuration(Math.round(s.talkTime))}` : "";
2863
+ const desc = s.description ? ` \xB7 ${s.description}` : "";
2864
+ parts.push(`- **${s.name || s.id}**${talk}${desc}`);
1660
2865
  }
1661
2866
  parts.push("\n## Transcript\n");
1662
- for (const seg of result.segments) {
1663
- const mm = Math.floor(seg.start / 60).toString().padStart(2, "0");
1664
- const ss = Math.floor(seg.start % 60).toString().padStart(2, "0");
1665
- const tone = seg.tone && seg.tone.length ? ` *(${seg.tone.join(", ")})*` : "";
1666
- parts.push(`[${mm}:${ss}] **${seg.speakerName || seg.speaker}**${tone}: ${seg.text}
2867
+ return parts;
2868
+ }
2869
+ function formatMarkdown(result, opts = {}) {
2870
+ const showTone = opts.showTone ?? true;
2871
+ const timestamps = opts.timestamps ?? true;
2872
+ const style = opts.mdStyle ?? "merged";
2873
+ const parts = mdHeader(result, opts);
2874
+ const groups = style === "merged" ? groupBySpeaker(result.segments) : result.segments.map((s) => [s]);
2875
+ for (const group of groups) {
2876
+ const first = group[0];
2877
+ const ts = timestamps ? `\`[${compactTime(first.start)}]\` ` : "";
2878
+ const name = first.speakerName || first.speaker;
2879
+ parts.push(`${ts}**${name}:** ${groupText(group, showTone)}
1667
2880
  `);
1668
2881
  }
1669
2882
  return parts.join("\n");
1670
2883
  }
2884
+ function formatText(result, opts = {}) {
2885
+ const timestamps = opts.timestamps ?? true;
2886
+ const showTone = opts.showTone ?? false;
2887
+ const lines = [];
2888
+ for (const group of groupBySpeaker(result.segments)) {
2889
+ const first = group[0];
2890
+ const ts = timestamps ? `[${compactTime(first.start)}] ` : "";
2891
+ const name = first.speakerName || first.speaker;
2892
+ const text = group.map(
2893
+ (s) => showTone && s.tone?.length ? `(${s.tone.join(", ")}) ${s.text}` : s.text
2894
+ ).join(" ");
2895
+ lines.push(`${ts}${name}: ${text}`);
2896
+ }
2897
+ return lines.join("\n\n") + "\n";
2898
+ }
1671
2899
  function formatJson(result) {
1672
2900
  return JSON.stringify(result, null, 2);
1673
2901
  }
1674
2902
 
2903
+ // src/finalize/html.ts
2904
+ var PALETTE = [
2905
+ "#2563eb",
2906
+ "#059669",
2907
+ "#d97706",
2908
+ "#dc2626",
2909
+ "#7c3aed",
2910
+ "#0891b2",
2911
+ "#be185d",
2912
+ "#4d7c0f",
2913
+ "#b45309",
2914
+ "#6d28d9"
2915
+ ];
2916
+ var esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2917
+ function groupBySpeaker2(segments) {
2918
+ const groups = [];
2919
+ for (const seg of segments) {
2920
+ const last = groups[groups.length - 1];
2921
+ const key = (s) => s.speakerName || s.speaker;
2922
+ if (last && key(last[0]) === key(seg)) last.push(seg);
2923
+ else groups.push([seg]);
2924
+ }
2925
+ return groups;
2926
+ }
2927
+ function formatHtml(result, opts = {}) {
2928
+ const title = opts.title || "Transcript";
2929
+ const colorOf = /* @__PURE__ */ new Map();
2930
+ result.speakers.forEach((sp, i) => {
2931
+ colorOf.set(sp.name || sp.id, PALETTE[i % PALETTE.length]);
2932
+ });
2933
+ const color = (name) => colorOf.get(name) ?? "#64748b";
2934
+ const legend = result.speakers.map((sp) => {
2935
+ const name = sp.name || sp.id;
2936
+ const talk = sp.talkTime ? ` \xB7 ${formatDuration(Math.round(sp.talkTime))}` : "";
2937
+ return `<span class="who"><i style="background:${color(name)}"></i>${esc(name)}<small>${talk}</small></span>`;
2938
+ }).join("");
2939
+ const paragraphs = groupBySpeaker2(result.segments).map((group) => {
2940
+ const first = group[0];
2941
+ const name = first.speakerName || first.speaker;
2942
+ let lastTone = "";
2943
+ const body = group.map((s) => {
2944
+ const toneStr = s.tone?.length ? s.tone.join(", ") : "";
2945
+ const badge = toneStr && toneStr !== lastTone ? `<em class="tone">${esc(toneStr)}</em> ` : "";
2946
+ lastTone = toneStr;
2947
+ return `${badge}${esc(s.text)}`;
2948
+ }).join(" ");
2949
+ return `<div class="turn" style="border-color:${color(name)}">
2950
+ <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>
2951
+ <p>${body}</p>
2952
+ </div>`;
2953
+ }).join("\n");
2954
+ const m = result.metadata;
2955
+ const cost = m.cost ? ` \xB7 ~$${m.cost.actualUsd.toFixed(2)}` : "";
2956
+ const footer = `${esc(m.models.transcribe ?? "")} + ${esc(m.models.timestamped ?? "")}${cost} \xB7 ${new Date(m.processedAt).toLocaleDateString()}`;
2957
+ return `<!doctype html>
2958
+ <html lang="en">
2959
+ <meta charset="utf-8">
2960
+ <meta name="viewport" content="width=device-width,initial-scale=1">
2961
+ <title>${esc(title)}</title>
2962
+ <style>
2963
+ :root{--bg:#ffffff;--fg:#1e293b;--muted:#64748b;--line:#e2e8f0;--chip:#f1f5f9}
2964
+ @media(prefers-color-scheme:dark){:root{--bg:#0f172a;--fg:#e2e8f0;--muted:#94a3b8;--line:#1e293b;--chip:#1e293b}}
2965
+ *{box-sizing:border-box}
2966
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
2967
+ main{max-width:760px;margin:0 auto;padding:2rem 1.25rem 4rem}
2968
+ h1{font-size:1.5rem;margin:0 0 .25rem}
2969
+ .sub{color:var(--muted);font-size:.9rem;margin-bottom:1rem}
2970
+ 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}
2971
+ .who{display:inline-flex;align-items:center;gap:.4rem;font-size:.85rem}
2972
+ .who i{width:.65rem;height:.65rem;border-radius:50%;display:inline-block}
2973
+ .who small{color:var(--muted)}
2974
+ .turn{border-left:3px solid;padding:.15rem 0 .15rem 1rem;margin:1.1rem 0}
2975
+ .turn .meta{display:flex;align-items:baseline;gap:.6rem;font-size:.85rem}
2976
+ .turn time{color:var(--muted);font-family:ui-monospace,Menlo,monospace;font-size:.78rem;cursor:pointer}
2977
+ .turn time:hover{text-decoration:underline}
2978
+ .turn p{margin:.25rem 0 0}
2979
+ .tone{background:var(--chip);color:var(--muted);border-radius:.5rem;padding:0 .45rem;font-size:.75rem;font-style:italic;white-space:nowrap}
2980
+ footer{margin-top:3rem;color:var(--muted);font-size:.8rem;border-top:1px solid var(--line);padding-top:1rem}
2981
+ </style>
2982
+ <main>
2983
+ <h1>${esc(title)}</h1>
2984
+ <div class="sub">${formatDuration(m.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns</div>
2985
+ <header class="legend">${legend}</header>
2986
+ ${paragraphs}
2987
+ <footer>${footer}</footer>
2988
+ </main>
2989
+ <script>
2990
+ document.querySelectorAll("time").forEach(t=>t.addEventListener("click",()=>{
2991
+ navigator.clipboard&&navigator.clipboard.writeText(t.dataset.t);
2992
+ const o=t.textContent;t.textContent="copied";setTimeout(()=>t.textContent=o,700);
2993
+ }));
2994
+ </script>
2995
+ </html>
2996
+ `;
2997
+ }
2998
+
2999
+ // src/finalize/summary.ts
3000
+ function summaryPrompt(result, instructions) {
3001
+ const lines = result.segments.map((s) => {
3002
+ const name = s.speakerName || s.speaker;
3003
+ return `[${compactTime(s.start)}] ${name}: ${s.text}`;
3004
+ });
3005
+ 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):
3006
+
3007
+ ## TL;DR
3008
+ 2-4 sentences. What was this, what mattered.
3009
+
3010
+ ## Decisions
3011
+ Bullet list of decisions actually made (not topics discussed). Attribute who decided when clear.
3012
+
3013
+ ## Action items
3014
+ Bullet list, "**Owner** \u2014 action" format. Only real commitments, with the timestamp in [mm:ss].
3015
+
3016
+ ## By speaker
3017
+ One short paragraph per speaker: their main points and positions.
3018
+
3019
+ ## Open questions
3020
+ Things raised but not resolved.
3021
+
3022
+ Be specific and quote sparingly. Do not invent content.${instructions ? `
3023
+
3024
+ Additional instructions: ${instructions}` : ""}
3025
+
3026
+ TRANSCRIPT:
3027
+ ${lines.join("\n")}`;
3028
+ }
3029
+ async function summarizeTranscript(client, model, result, instructions) {
3030
+ const res = await client.chat(
3031
+ model,
3032
+ [{ role: "user", content: summaryPrompt(result, instructions) }],
3033
+ { temperature: 0.3, maxTokens: 4e3, logKind: "summary" }
3034
+ );
3035
+ if (res.error || !res.text) {
3036
+ throw new Error(`summary failed: ${res.error || "empty response"}`);
3037
+ }
3038
+ return res.text.trim() + "\n";
3039
+ }
3040
+
1675
3041
  // src/core/pipeline.ts
1676
3042
  import { basename as basename3, resolve as resolve2 } from "path";
1677
3043
  var JSON_OPTS = { encoding: "utf-8" };
1678
3044
  function readJson(p) {
1679
- if (!existsSync2(p)) return null;
3045
+ if (!existsSync3(p)) return null;
1680
3046
  try {
1681
- return JSON.parse(readFileSync(p, JSON_OPTS));
3047
+ return JSON.parse(readFileSync2(p, JSON_OPTS));
1682
3048
  } catch {
1683
3049
  return null;
1684
3050
  }
1685
3051
  }
1686
3052
  function writeJson(p, data) {
1687
- writeFileSync(p, JSON.stringify(data, null, 2), JSON_OPTS);
3053
+ writeFileSync2(p, JSON.stringify(data, null, 2), JSON_OPTS);
1688
3054
  }
1689
3055
  async function mapPool(items, limit, fn) {
1690
3056
  const results = new Array(items.length);
@@ -1702,27 +3068,41 @@ async function mapPool(items, limit, fn) {
1702
3068
  function has(passes, p) {
1703
3069
  return passes.includes(p);
1704
3070
  }
3071
+ function stageTag(name) {
3072
+ return (err) => {
3073
+ const msg = err instanceof Error ? err.message : String(err);
3074
+ if (msg.startsWith(`[${name}]`)) throw err;
3075
+ const e = new Error(`[${name}] ${msg}`);
3076
+ if (err instanceof Error && err.stack) e.stack = err.stack;
3077
+ throw e;
3078
+ };
3079
+ }
1705
3080
  async function transcribe(opts) {
1706
3081
  if (!opts || typeof opts.input !== "string" || opts.input.length === 0) {
1707
- throw new Error("transcribe(options): 'input' (path to the audio/video file) is required");
1708
- }
1709
- if (typeof opts.outputDir !== "string" || opts.outputDir.length === 0) {
1710
- throw new Error("transcribe(options): 'outputDir' (directory for outputs) is required");
3082
+ throw new Error(
3083
+ "transcribe(options): 'input' (path to the audio/video file) is required"
3084
+ );
1711
3085
  }
1712
3086
  const options = resolveOptions(opts);
1713
3087
  const keys = resolveKeys(options.apiKeys);
1714
3088
  logger.setLevel(options.logLevel);
1715
- if (!existsSync2(options.input)) {
3089
+ if (!existsSync3(options.input)) {
1716
3090
  throw new Error(`Input file not found: ${options.input}`);
1717
3091
  }
1718
- mkdirSync(options.intermediatesDir, { recursive: true });
1719
- mkdirSync(options.outputDir, { recursive: true });
1720
- logger.info(`intermediates: ${resolve2(options.intermediatesDir)} (file://${resolve2(options.intermediatesDir)})`);
3092
+ mkdirSync2(options.intermediatesDir, { recursive: true });
3093
+ mkdirSync2(options.outputDir, { recursive: true });
3094
+ logger.info(
3095
+ `intermediates: ${resolve2(options.intermediatesDir)} (file://${resolve2(options.intermediatesDir)})`
3096
+ );
1721
3097
  setLlmLogPath(options.llmLog ? `${options.intermediatesDir}/llm-calls.jsonl` : null);
3098
+ resetLlmUsage();
3099
+ const runStartedAt = Date.now();
1722
3100
  const sourcePath = `${options.intermediatesDir}/source.json`;
1723
3101
  const sig = inputSignature(options.input);
1724
3102
  const cfgSig = configSignature(opts);
1725
- const prevSig = readJson(sourcePath);
3103
+ const prevSig = readJson(
3104
+ sourcePath
3105
+ );
1726
3106
  const inputChanged = !prevSig || prevSig.signature !== sig;
1727
3107
  const configChanged = !prevSig || prevSig.config !== cfgSig;
1728
3108
  if (inputChanged && prevSig) {
@@ -1746,6 +3126,9 @@ async function transcribe(opts) {
1746
3126
  transcribe: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
1747
3127
  reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL
1748
3128
  };
3129
+ const checkAbort = () => {
3130
+ options.signal?.throwIfAborted();
3131
+ };
1749
3132
  if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
1750
3133
  if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
1751
3134
  const tsProvider = options.timestampedProvider ?? "assemblyai";
@@ -1753,33 +3136,45 @@ async function transcribe(opts) {
1753
3136
  if (willTimestamp) {
1754
3137
  if (tsProvider === "assemblyai" && !keys.assemblyai) {
1755
3138
  throw new Error(
1756
- "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
3139
+ "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
1757
3140
  );
1758
3141
  }
1759
3142
  if (tsProvider === "whisper-groq" && !keys.groq) {
1760
3143
  throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
1761
3144
  }
3145
+ if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
3146
+ throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3147
+ }
1762
3148
  }
1763
3149
  let probeInfo = null;
1764
3150
  const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
1765
3151
  const audioPath = `${options.intermediatesDir}/audio.mp3`;
1766
3152
  const probePath = `${options.intermediatesDir}/probe.json`;
1767
3153
  if (has(passes, "preprocess")) {
3154
+ checkAbort();
1768
3155
  logger.info("=== preprocess ===");
1769
3156
  probeInfo = forceAll ? null : readJson(probePath);
1770
3157
  if (!probeInfo) {
1771
- probeInfo = await probe(options.input);
3158
+ probeInfo = await probe(options.input).catch(stageTag("preprocess"));
1772
3159
  writeJson(probePath, probeInfo);
1773
3160
  }
1774
- if (!existsSync2(audioPath) || forceAll) {
3161
+ if (!existsSync3(audioPath) || forceAll) {
1775
3162
  logger.info("extracting audio (mono 16kHz mp3)...");
1776
- await extractAudio(options.input, audioPath, AUDIO_OPTS);
3163
+ await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
3164
+ stageTag("preprocess")
3165
+ );
1777
3166
  }
1778
3167
  if (probeInfo.hasVideo) {
1779
3168
  const kfDir = `${options.intermediatesDir}/keyframes`;
1780
- if (!existsSync2(kfDir) || forceAll) {
3169
+ if (!existsSync3(kfDir) || forceAll) {
1781
3170
  logger.info("extracting keyframes...");
1782
- await extractKeyframes(options.input, kfDir, options.screenshotCount);
3171
+ await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
3172
+ (err) => {
3173
+ logger.warn(
3174
+ `keyframe extraction failed (continuing audio-only): ${err instanceof Error ? err.message : err}`
3175
+ );
3176
+ }
3177
+ );
1783
3178
  }
1784
3179
  }
1785
3180
  } else {
@@ -1787,26 +3182,56 @@ async function transcribe(opts) {
1787
3182
  }
1788
3183
  if (!probeInfo) throw new Error("probe info missing (run preprocess)");
1789
3184
  const duration = probeInfo.duration;
3185
+ const estimate = estimateRunCost({
3186
+ durationSec: duration,
3187
+ model: models.transcribe,
3188
+ reasoner: models.reasoner,
3189
+ tsProvider,
3190
+ chunkSec: options.chunkDurationSec,
3191
+ overlapSec: options.chunkOverlapSec,
3192
+ identify: options.diarizationLevel >= 3 && has(passes, "identify")
3193
+ });
3194
+ logger.info(
3195
+ `estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
3196
+ );
1790
3197
  let description = null;
1791
3198
  if (has(passes, "describe")) {
1792
3199
  const descPath = `${options.intermediatesDir}/description.json`;
1793
3200
  description = forceAll ? null : readJson(descPath);
1794
3201
  if (!description) {
3202
+ checkAbort();
1795
3203
  logger.info("=== describe ===");
1796
3204
  const client = new GeminiClient(keys.gemini);
1797
- const samplePath = `${options.intermediatesDir}/sample.mp3`;
1798
- if (!existsSync2(samplePath) || forceAll) {
1799
- await extractChunk(audioPath, samplePath, 0, Math.min(300, duration), AUDIO_OPTS);
3205
+ const sampleSpans = duration <= 360 ? [[0, duration]] : [
3206
+ [0, 150],
3207
+ [Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
3208
+ [Math.max(0, duration - 120), duration]
3209
+ ];
3210
+ const files = [];
3211
+ for (let i = 0; i < sampleSpans.length; i++) {
3212
+ const [s, e] = sampleSpans[i];
3213
+ const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
3214
+ if (!existsSync3(samplePath) || forceAll) {
3215
+ await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
3216
+ }
3217
+ files.push({ path: samplePath });
1800
3218
  }
1801
- const files = [{ path: samplePath }];
3219
+ const audioSampleCount = files.length;
1802
3220
  const kfDir = `${options.intermediatesDir}/keyframes`;
1803
- if (existsSync2(kfDir)) {
3221
+ if (existsSync3(kfDir)) {
1804
3222
  for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
1805
3223
  const p = `${kfDir}/${f}`;
1806
- if (existsSync2(p)) files.push({ path: p });
3224
+ if (existsSync3(p)) files.push({ path: p });
1807
3225
  }
1808
3226
  }
1809
- description = await describeMeeting(client, models.transcribe, files, basename3(options.input), options.instructions);
3227
+ description = await describeMeeting(
3228
+ client,
3229
+ models.transcribe,
3230
+ files,
3231
+ basename3(options.input),
3232
+ options.instructions,
3233
+ audioSampleCount
3234
+ ).catch(stageTag("describe"));
1810
3235
  writeJson(descPath, description);
1811
3236
  logger.info(`description: ${description.description.slice(0, 120)}...`);
1812
3237
  }
@@ -1819,39 +3244,74 @@ async function transcribe(opts) {
1819
3244
  let silences = [];
1820
3245
  try {
1821
3246
  silences = await detectSilence(audioPath, { noiseDb: -15, minDuration: 0.3 });
1822
- if (silences.length < 3) silences = await detectSilence(audioPath, { noiseDb: -12, minDuration: 0.25 });
3247
+ if (silences.length < 3)
3248
+ silences = await detectSilence(audioPath, { noiseDb: -12, minDuration: 0.25 });
1823
3249
  } catch {
1824
3250
  }
1825
3251
  chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
1826
3252
  if (silences.length > 3) {
1827
3253
  chunks = chunks.map((c) => {
1828
- const snapped = snapToSilence(c.start, silences, Math.min(10, options.chunkOverlapSec / 2));
3254
+ const snapped = snapToSilence(
3255
+ c.start,
3256
+ silences,
3257
+ Math.min(10, options.chunkOverlapSec / 2)
3258
+ );
1829
3259
  return { ...c, start: snapped, trustedStart: snapped + c.overlapWithPrevious };
1830
3260
  });
1831
3261
  }
1832
3262
  }
1833
3263
  const tagWith = (r, chunk) => ({
1834
3264
  ...r,
1835
- segments: r.segments.map((s) => ({ ...s, chunkIndex: chunk.index, trustedStart: chunk.trustedStart }))
3265
+ segments: r.segments.map((s) => ({
3266
+ ...s,
3267
+ chunkIndex: chunk.index,
3268
+ trustedStart: chunk.trustedStart
3269
+ }))
1836
3270
  });
1837
3271
  let llmChunkResults = [];
1838
3272
  if (has(passes, "llm-transcribe")) {
1839
3273
  logger.info("=== llm-transcribe ===");
1840
3274
  let runChunks = chunks;
1841
- if (options.onlyChunk !== void 0) runChunks = chunks.filter((c) => c.index === options.onlyChunk);
1842
- logger.info(`${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`);
3275
+ if (options.onlyChunk !== void 0)
3276
+ runChunks = chunks.filter((c) => c.index === options.onlyChunk);
3277
+ logger.info(
3278
+ `${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`
3279
+ );
1843
3280
  const client = new GeminiClient(keys.gemini);
1844
3281
  const llmDir = `${options.intermediatesDir}/llm`;
1845
- mkdirSync(llmDir, { recursive: true });
3282
+ mkdirSync2(llmDir, { recursive: true });
3283
+ const partialPath = `${options.outputDir}/${basename3(options.input, ext(options.input))}.partial.md`;
3284
+ const completed = [];
3285
+ const writePartial = () => {
3286
+ try {
3287
+ const segs = completed.flatMap((r) => r.segments).sort((a, b) => a.startSec - b.startSec);
3288
+ if (segs.length === 0) return;
3289
+ const lines = segs.map((s) => {
3290
+ const mm = Math.floor(s.startSec / 60).toString().padStart(2, "0");
3291
+ const ss = Math.floor(s.startSec % 60).toString().padStart(2, "0");
3292
+ return `[${mm}:${ss}] **${s.speaker}**: ${s.text}`;
3293
+ });
3294
+ writeFileSync2(
3295
+ partialPath,
3296
+ `> Partial transcript (run in progress \u2014 coarse LLM timings, speakers not yet unified)
3297
+
3298
+ ${lines.join("\n\n")}
3299
+ `
3300
+ );
3301
+ } catch {
3302
+ }
3303
+ };
1846
3304
  llmChunkResults = await mapPool(runChunks, options.concurrency, async (chunk) => {
3305
+ checkAbort();
1847
3306
  const parsedPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_parsed.json`;
1848
3307
  const cached = forceAll ? null : readJson(parsedPath);
1849
3308
  if (cached && cached.segments.length > 0) {
1850
3309
  logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
3310
+ completed.push(cached);
1851
3311
  return tagWith(cached, chunk);
1852
3312
  }
1853
3313
  const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
1854
- if (!existsSync2(chunkPath) || forceAll) {
3314
+ if (!existsSync3(chunkPath) || forceAll) {
1855
3315
  await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
1856
3316
  }
1857
3317
  let previousTail;
@@ -1863,7 +3323,9 @@ async function transcribe(opts) {
1863
3323
  previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
1864
3324
  }
1865
3325
  }
1866
- logger.info(`chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`);
3326
+ logger.info(
3327
+ `chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`
3328
+ );
1867
3329
  const result2 = await transcribeChunk(
1868
3330
  client,
1869
3331
  models.transcribe,
@@ -1880,7 +3342,12 @@ async function transcribe(opts) {
1880
3342
  { chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
1881
3343
  );
1882
3344
  writeJson(parsedPath, result2);
1883
- writeFileSync(`${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`, result2.raw);
3345
+ writeFileSync2(
3346
+ `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
3347
+ result2.raw
3348
+ );
3349
+ completed.push(result2);
3350
+ writePartial();
1884
3351
  return tagWith(result2, chunk);
1885
3352
  });
1886
3353
  const errored = llmChunkResults.filter((r) => r.error);
@@ -1892,7 +3359,7 @@ async function transcribe(opts) {
1892
3359
  }
1893
3360
  } else {
1894
3361
  const llmDir = `${options.intermediatesDir}/llm`;
1895
- if (!forceAll && existsSync2(llmDir)) {
3362
+ if (!forceAll && existsSync3(llmDir)) {
1896
3363
  const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
1897
3364
  llmChunkResults = files.map((f, i) => {
1898
3365
  const r = readJson(`${llmDir}/${f}`);
@@ -1911,23 +3378,49 @@ async function transcribe(opts) {
1911
3378
  logger.info(`total LLM segments: ${allLlmSegments.length}`);
1912
3379
  let asrResult = null;
1913
3380
  if (has(passes, "timestamped") || has(passes, "align")) {
3381
+ checkAbort();
1914
3382
  const provider = options.timestampedProvider ?? "assemblyai";
1915
3383
  if (provider === "whisper-groq") {
1916
3384
  logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
1917
3385
  if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
1918
- if (!existsSync2(audioPath) || forceAll) {
3386
+ if (!existsSync3(audioPath) || forceAll) {
1919
3387
  await extractAudio(options.input, audioPath, AUDIO_OPTS);
1920
3388
  }
1921
3389
  const { readFile: readFile2 } = await import("fs/promises");
1922
3390
  const buf = await readFile2(audioPath);
1923
3391
  const groq = new WhisperGroqClient(keys.groq);
1924
- asrResult = await groq.transcribe(buf);
3392
+ asrResult = await groq.transcribe(buf).catch(stageTag("asr"));
3393
+ writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3394
+ } else if (provider === "elevenlabs") {
3395
+ logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
3396
+ if (!keys.elevenlabs)
3397
+ throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3398
+ const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs.json`;
3399
+ asrResult = forceAll ? null : readJson(cachePath);
3400
+ if (!asrResult) {
3401
+ const { readFile: readFile2 } = await import("fs/promises");
3402
+ const buf = await readFile2(audioPath);
3403
+ const el = new ElevenLabsClient(keys.elevenlabs);
3404
+ asrResult = await el.transcribe(buf).catch(stageTag("asr"));
3405
+ writeJson(cachePath, asrResult);
3406
+ } else {
3407
+ logger.info("[elevenlabs] cache hit");
3408
+ }
1925
3409
  writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3410
+ logger.info(
3411
+ `[elevenlabs] ${asrResult.utterances.length} utterances, ${asrResult.words.length} words, ${asrResult.speakers?.length ?? "?"} speakers`
3412
+ );
1926
3413
  } else {
1927
3414
  logger.info("=== timestamped (AssemblyAI) ===");
1928
- if (!keys.assemblyai) throw new Error("ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)");
1929
- const aai = new AssemblyAIProvider({ apiKey: keys.assemblyai, cacheDir: `${options.intermediatesDir}/assemblyai` });
1930
- asrResult = await aai.transcribe(audioPath);
3415
+ if (!keys.assemblyai)
3416
+ throw new Error(
3417
+ "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
3418
+ );
3419
+ const aai = new AssemblyAIProvider({
3420
+ apiKey: keys.assemblyai,
3421
+ cacheDir: `${options.intermediatesDir}/assemblyai`
3422
+ });
3423
+ asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
1931
3424
  writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
1932
3425
  }
1933
3426
  } else {
@@ -1949,6 +3442,9 @@ async function transcribe(opts) {
1949
3442
  const added = aligned.length - before;
1950
3443
  if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
1951
3444
  }
3445
+ if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
3446
+ aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
3447
+ }
1952
3448
  let segments = aligned;
1953
3449
  let speakers = [];
1954
3450
  if (has(passes, "consistency") && asrResult) {
@@ -1968,25 +3464,75 @@ async function transcribe(opts) {
1968
3464
  speakers = c.speakers;
1969
3465
  }
1970
3466
  }
1971
- if (options.diarizationLevel >= 3 && has(passes, "identify") && keys.deepseek && description) {
1972
- logger.info("=== identify (DeepSeek) ===");
1973
- const dsClient = OpenAICompatClient.fromProvider("deepseek", keys.deepseek, models.reasoner);
1974
- const id = await identifySpeakers(
1975
- dsClient,
1976
- models.reasoner,
1977
- segments.map((s) => ({ speaker: s.speaker, text: s.text })),
1978
- speakers,
1979
- description.roster,
1980
- options.knownSpeakers
1981
- );
1982
- logger.info(`identified ${Object.keys(id.nameMap).length} speakers: ${JSON.stringify(id.nameMap)}`);
1983
- writeJson(`${options.intermediatesDir}/identified.json`, id);
1984
- segments = segments.map(
1985
- (s) => id.nameMap[s.speaker] ? { ...s, speakerName: id.nameMap[s.speaker] } : s
1986
- );
1987
- speakers = speakers.map(
1988
- (sp) => id.nameMap[sp.id] ? { ...sp, name: id.nameMap[sp.id] } : sp
1989
- );
3467
+ const nameHints = {};
3468
+ for (const sp of speakers) {
3469
+ if (sp.name && sp.name !== sp.id) nameHints[sp.id] = sp.name;
3470
+ }
3471
+ segments = segments.map(
3472
+ (s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
3473
+ );
3474
+ speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
3475
+ if (options.diarizationLevel >= 3 && has(passes, "identify")) {
3476
+ const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
3477
+ if (!reasonerA) {
3478
+ logger.warn(
3479
+ "identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
3480
+ );
3481
+ } else {
3482
+ const mode = options.identifyMode;
3483
+ const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
3484
+ const idConfig = {
3485
+ mode,
3486
+ reasonerA: reasonerA.info.model,
3487
+ reasonerB: reasonerB?.info.model ?? null
3488
+ };
3489
+ const idCachePath = `${options.intermediatesDir}/identified.json`;
3490
+ const cachedId = forceAll ? null : readJson(
3491
+ idCachePath
3492
+ );
3493
+ const idConfigMatches = cachedId?.config && JSON.stringify(cachedId.config) === JSON.stringify(idConfig);
3494
+ let nameMap = null;
3495
+ if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
3496
+ logger.info("=== identify (cached) ===");
3497
+ nameMap = cachedId.nameMap;
3498
+ } else {
3499
+ logger.info(
3500
+ `=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
3501
+ );
3502
+ checkAbort();
3503
+ const id = await identifySpeakersV2(
3504
+ {
3505
+ client: reasonerA.client,
3506
+ model: reasonerA.info.model,
3507
+ provider: reasonerA.info.provider
3508
+ },
3509
+ reasonerB ? {
3510
+ client: reasonerB.client,
3511
+ model: reasonerB.info.model,
3512
+ provider: reasonerB.info.provider
3513
+ } : null,
3514
+ segments.map((s) => ({ speaker: s.speaker, text: s.text })),
3515
+ speakers,
3516
+ {
3517
+ roster: description?.roster ?? "(no roster available \u2014 infer from the transcript alone)",
3518
+ knownSpeakers: options.knownSpeakers,
3519
+ mode,
3520
+ nameHints,
3521
+ sourceFileName: basename3(options.input)
3522
+ }
3523
+ ).catch(stageTag("identify"));
3524
+ writeJson(idCachePath, { ...id, config: idConfig });
3525
+ nameMap = id.nameMap;
3526
+ }
3527
+ logger.info(
3528
+ `identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
3529
+ );
3530
+ const nm = nameMap;
3531
+ segments = segments.map(
3532
+ (s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
3533
+ );
3534
+ speakers = speakers.map((sp) => nm[sp.id] ? { ...sp, name: nm[sp.id] } : sp);
3535
+ }
1990
3536
  }
1991
3537
  let finalSegments = [];
1992
3538
  if (has(passes, "finalize")) {
@@ -1997,24 +3543,106 @@ async function transcribe(opts) {
1997
3543
  finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
1998
3544
  }
1999
3545
  logger.info(`final segments: ${finalSegments.length}`);
3546
+ const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
3547
+ const wallMs = Date.now() - runStartedAt;
2000
3548
  const metadata = {
2001
3549
  sourceFile: options.input,
2002
3550
  duration,
2003
3551
  processedAt: (/* @__PURE__ */ new Date()).toISOString(),
2004
3552
  models: {
2005
3553
  transcribe: models.transcribe,
2006
- timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
3554
+ timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "elevenlabs" ? "scribe-v2 (elevenlabs)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
2007
3555
  },
2008
- passes
3556
+ passes,
3557
+ wallMs,
3558
+ cost: {
3559
+ estimatedUsd: estimate.totalUsd,
3560
+ actualUsd: receipt.totalUsd,
3561
+ pricesAsOf: PRICES_AS_OF,
3562
+ lines: receipt.lines,
3563
+ llmCalls: receipt.totals.calls,
3564
+ inputTokens: receipt.totals.inputTokens,
3565
+ outputTokens: receipt.totals.outputTokens
3566
+ }
2009
3567
  };
2010
3568
  const result = { segments: finalSegments, speakers, metadata };
3569
+ writeJson(`${options.intermediatesDir}/result.json`, result);
2011
3570
  for (const fmt of options.formats) {
2012
3571
  const base = basename3(options.input, ext(options.input));
2013
- if (fmt === "srt") writeFileSync(`${options.outputDir}/${base}.srt`, formatSrt(result, { title: base }));
2014
- if (fmt === "md") writeFileSync(`${options.outputDir}/${base}.md`, formatMarkdown(result, { title: base }));
2015
- if (fmt === "json") writeFileSync(`${options.outputDir}/${base}.json`, formatJson(result));
3572
+ if (fmt === "srt")
3573
+ writeFileSync2(
3574
+ `${options.outputDir}/${base}.srt`,
3575
+ formatSrt(result, { title: base })
3576
+ );
3577
+ if (fmt === "md")
3578
+ writeFileSync2(
3579
+ `${options.outputDir}/${base}.md`,
3580
+ formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
3581
+ );
3582
+ if (fmt === "txt")
3583
+ writeFileSync2(
3584
+ `${options.outputDir}/${base}.txt`,
3585
+ formatText(result, { title: base })
3586
+ );
3587
+ if (fmt === "html")
3588
+ writeFileSync2(
3589
+ `${options.outputDir}/${base}.html`,
3590
+ formatHtml(result, { title: base })
3591
+ );
3592
+ if (fmt === "json")
3593
+ writeFileSync2(`${options.outputDir}/${base}.json`, formatJson(result));
3594
+ }
3595
+ if (options.summary && finalSegments.length > 0) {
3596
+ const reasoner = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
3597
+ if (!reasoner) {
3598
+ logger.warn("summary: no reasoner-capable key \u2014 skipping");
3599
+ } else {
3600
+ logger.info(`=== summary (${reasoner.info.model}) ===`);
3601
+ try {
3602
+ const summary = await summarizeTranscript(
3603
+ reasoner.client,
3604
+ reasoner.info.model,
3605
+ result,
3606
+ options.instructions
3607
+ );
3608
+ const base = basename3(options.input, ext(options.input));
3609
+ writeFileSync2(`${options.outputDir}/${base}.summary.md`, summary);
3610
+ logger.info(`summary written to ${base}.summary.md`);
3611
+ } catch (err) {
3612
+ logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
3613
+ }
3614
+ }
3615
+ }
3616
+ try {
3617
+ const base = basename3(options.input, ext(options.input));
3618
+ const partial = `${options.outputDir}/${base}.partial.md`;
3619
+ if (existsSync3(partial)) (await import("fs/promises")).unlink(partial);
3620
+ } catch {
2016
3621
  }
2017
3622
  logger.info(`outputs written to ${options.outputDir}`);
3623
+ const mins = Math.floor(wallMs / 6e4);
3624
+ const secs = Math.round(wallMs % 6e4 / 1e3);
3625
+ logger.info(
3626
+ `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`
3627
+ );
3628
+ for (const line of receipt.lines) logger.info(` ${line}`);
3629
+ recordRun(
3630
+ {
3631
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
3632
+ input: basename3(options.input),
3633
+ durationSec: duration,
3634
+ wallMs,
3635
+ models: metadata.models,
3636
+ segments: finalSegments.length,
3637
+ characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
3638
+ speakers: speakers.length,
3639
+ llmCalls: receipt.totals.calls,
3640
+ inputTokens: receipt.totals.inputTokens,
3641
+ outputTokens: receipt.totals.outputTokens,
3642
+ costUsd: receipt.totalUsd
3643
+ },
3644
+ receipt.perModel
3645
+ );
2018
3646
  return result;
2019
3647
  }
2020
3648
  function ext(p) {
@@ -2055,12 +3683,15 @@ export {
2055
3683
  alignSegments,
2056
3684
  assignGlobalSpeakers,
2057
3685
  finalizeSegments,
3686
+ formatHtml,
2058
3687
  formatJson,
2059
3688
  formatMarkdown,
2060
3689
  formatSrt,
3690
+ formatText,
2061
3691
  identifySpeakers,
2062
3692
  parseSrt,
2063
3693
  planChunks,
3694
+ summarizeTranscript,
2064
3695
  transcribe
2065
3696
  };
2066
3697
  //# sourceMappingURL=index.js.map