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.cjs CHANGED
@@ -33,18 +33,21 @@ __export(src_exports, {
33
33
  alignSegments: () => alignSegments,
34
34
  assignGlobalSpeakers: () => assignGlobalSpeakers,
35
35
  finalizeSegments: () => finalizeSegments,
36
+ formatHtml: () => formatHtml,
36
37
  formatJson: () => formatJson,
37
38
  formatMarkdown: () => formatMarkdown,
38
39
  formatSrt: () => formatSrt,
40
+ formatText: () => formatText,
39
41
  identifySpeakers: () => identifySpeakers,
40
42
  parseSrt: () => parseSrt,
41
43
  planChunks: () => planChunks,
44
+ summarizeTranscript: () => summarizeTranscript,
42
45
  transcribe: () => transcribe
43
46
  });
44
47
  module.exports = __toCommonJS(src_exports);
45
48
 
46
49
  // src/core/pipeline.ts
47
- var import_node_fs4 = require("fs");
50
+ var import_node_fs5 = require("fs");
48
51
 
49
52
  // src/core/config.ts
50
53
  var import_node_crypto = require("crypto");
@@ -64,12 +67,14 @@ var MODELS = {
64
67
  gemini25Pro: "gemini-2.5-pro",
65
68
  gemini25Flash: "gemini-2.5-flash",
66
69
  gemini3Pro: "gemini-3-pro-preview",
70
+ gemini31Pro: "gemini-3.1-pro-preview",
71
+ geminiFlashLatest: "gemini-flash-latest",
67
72
  deepseek: "deepseek-chat",
68
73
  deepseekReasoner: "deepseek-reasoner",
69
74
  gpt4o: "gpt-4o",
70
75
  claudeSonnet: "claude-sonnet-4-5"
71
76
  };
72
- var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini25Flash;
77
+ var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini31Pro;
73
78
  var DEFAULT_REASONER_MODEL = MODELS.deepseek;
74
79
  function resolveKeys(injected) {
75
80
  const env = process.env;
@@ -80,19 +85,23 @@ function resolveKeys(injected) {
80
85
  deepseek: injected?.deepseek || env.DEEPSEEK_API_KEY,
81
86
  groq: injected?.groq || env.GROQ_API_KEY,
82
87
  assemblyai: injected?.assemblyai || env.ASSEMBLYAI_API_KEY,
83
- anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY
88
+ anthropic: injected?.anthropic || env.ANTHROPIC_API_KEY,
89
+ zai: injected?.zai || env.ZAI_API_KEY || env.GLM_API_KEY,
90
+ kimi: injected?.kimi || env.KIMI_API_KEY || env.MOONSHOT_API_KEY,
91
+ elevenlabs: injected?.elevenlabs || env.ELEVENLABS_API_KEY
84
92
  };
85
93
  }
86
94
  function resolveOptions(opts) {
87
95
  return {
88
96
  input: opts.input,
89
- outputDir: opts.outputDir,
97
+ // Default: write next to the input file (e.g. meeting.md beside meeting.mp4) — no ./output folder.
98
+ outputDir: opts.outputDir ?? (0, import_node_path.dirname)((0, import_node_path.resolve)(opts.input)),
90
99
  intermediatesDir: opts.intermediatesDir ?? deriveIntermediatesDir(opts.input),
91
100
  instructions: opts.instructions,
92
101
  knownSpeakers: opts.knownSpeakers,
93
102
  passes: (() => {
94
103
  const p = opts.passes ?? DEFAULT_PASSES;
95
- if ((opts.diarizationLevel ?? 2) >= 3 && !p.includes("identify")) {
104
+ if ((opts.diarizationLevel ?? 3) >= 3 && !p.includes("identify")) {
96
105
  const out = [...p];
97
106
  const fi = out.indexOf("finalize");
98
107
  if (fi >= 0) out.splice(fi, 0, "identify");
@@ -106,8 +115,14 @@ function resolveOptions(opts) {
106
115
  screenshotCount: opts.screenshotCount ?? 6,
107
116
  concurrency: opts.concurrency ?? 4,
108
117
  saveIntermediates: opts.saveIntermediates ?? true,
109
- formats: opts.formats ?? ["srt", "md", "json"],
110
- diarizationLevel: opts.diarizationLevel ?? 2,
118
+ formats: opts.formats ?? ["md"],
119
+ mdStyle: opts.mdStyle ?? "merged",
120
+ summary: opts.summary ?? false,
121
+ // Level 3 is the default: display names must come from the VERIFIED identify pass.
122
+ // (A describe-pass roster once bound names to the wrong voices and level 2 shipped
123
+ // them unchecked — the Jay-call flip. Level 2 now shows honest Speaker A/B labels.)
124
+ diarizationLevel: opts.diarizationLevel ?? 3,
125
+ identifyMode: opts.identifyMode ?? "dual",
111
126
  apiKeys: opts.apiKeys,
112
127
  model: opts.model,
113
128
  reasoner: opts.reasoner,
@@ -116,7 +131,8 @@ function resolveOptions(opts) {
116
131
  onlyChunk: opts.onlyChunk,
117
132
  showProgress: opts.showProgress ?? true,
118
133
  llmLog: opts.llmLog ?? true,
119
- logLevel: opts.logLevel ?? "info"
134
+ logLevel: opts.logLevel ?? "info",
135
+ signal: opts.signal
120
136
  };
121
137
  }
122
138
  function deriveIntermediatesDir(input) {
@@ -149,7 +165,7 @@ function configSignature(o) {
149
165
  chunkDurationSec: o.chunkDurationSec ?? 600,
150
166
  chunkOverlapSec: o.chunkOverlapSec ?? 60,
151
167
  screenshotCount: o.screenshotCount ?? 6,
152
- diarizationLevel: o.diarizationLevel ?? 2,
168
+ diarizationLevel: o.diarizationLevel ?? 3,
153
169
  timestampedProvider: o.timestampedProvider ?? "assemblyai"
154
170
  };
155
171
  return (0, import_node_crypto.createHash)("sha1").update(JSON.stringify(relevant)).digest("hex");
@@ -184,11 +200,13 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
184
200
  // src/utils/logger.ts
185
201
  var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
186
202
  var currentLevel = "info";
203
+ var sink = null;
187
204
  function setLogLevel(level) {
188
205
  currentLevel = level;
189
206
  }
190
207
  function log(level, msg, extra) {
191
208
  if (LEVELS[level] < LEVELS[currentLevel]) return;
209
+ if (sink && extra === void 0 && sink(level, msg)) return;
192
210
  const ts = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
193
211
  const prefix = `[${ts}] ${level.toUpperCase().padEnd(5)}`;
194
212
  if (extra !== void 0) {
@@ -202,7 +220,10 @@ var logger = {
202
220
  info: (msg, extra) => log("info", msg, extra),
203
221
  warn: (msg, extra) => log("warn", msg, extra),
204
222
  error: (msg, extra) => log("error", msg, extra),
205
- setLevel: setLogLevel
223
+ setLevel: setLogLevel,
224
+ setSink: (s) => {
225
+ sink = s;
226
+ }
206
227
  };
207
228
 
208
229
  // src/audio/ffmpeg.ts
@@ -415,10 +436,35 @@ var import_node_path3 = require("path");
415
436
  // src/providers/llm-log.ts
416
437
  var import_node_fs2 = require("fs");
417
438
  var logPath = null;
439
+ var usageRecords = /* @__PURE__ */ new Map();
418
440
  function setLlmLogPath(path) {
419
441
  logPath = path ?? null;
420
442
  }
443
+ function resetLlmUsage() {
444
+ usageRecords = /* @__PURE__ */ new Map();
445
+ }
446
+ function getLlmUsage() {
447
+ return [...usageRecords.values()];
448
+ }
421
449
  function logLlmCall(entry) {
450
+ try {
451
+ const key = `${entry.model}|${entry.kind ?? ""}`;
452
+ const rec = usageRecords.get(key) ?? {
453
+ provider: entry.provider,
454
+ model: entry.model,
455
+ kind: entry.kind,
456
+ inputTokens: 0,
457
+ outputTokens: 0,
458
+ calls: 0,
459
+ errors: 0
460
+ };
461
+ rec.inputTokens += entry.usage?.inputTokens ?? 0;
462
+ rec.outputTokens += entry.usage?.outputTokens ?? 0;
463
+ rec.calls += 1;
464
+ if (entry.error) rec.errors += 1;
465
+ usageRecords.set(key, rec);
466
+ } catch {
467
+ }
422
468
  if (!logPath) return;
423
469
  try {
424
470
  (0, import_node_fs2.appendFileSync)(logPath, JSON.stringify(entry) + "\n", { encoding: "utf-8" });
@@ -426,7 +472,39 @@ function logLlmCall(entry) {
426
472
  }
427
473
  }
428
474
 
475
+ // src/utils/retry.ts
476
+ 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;
477
+ function isTransient(err) {
478
+ const msg = err instanceof Error ? `${err.message} ${err.cause ?? ""}` : String(err);
479
+ return TRANSIENT_RE.test(msg);
480
+ }
481
+ async function withRetry(label, fn, opts = {}) {
482
+ const retries = opts.retries ?? 5;
483
+ const base = opts.baseDelayMs ?? 2e3;
484
+ let lastErr;
485
+ for (let attempt = 0; attempt <= retries; attempt++) {
486
+ try {
487
+ return await fn();
488
+ } catch (err) {
489
+ lastErr = err;
490
+ if (attempt === retries || !isTransient(err)) throw err;
491
+ const delay = base * 2 ** attempt * (0.7 + Math.random() * 0.6);
492
+ logger.warn(
493
+ `[${label}] transient failure (${err instanceof Error ? err.message : err}) \u2014 retry ${attempt + 1}/${retries} in ${(delay / 1e3).toFixed(1)}s`
494
+ );
495
+ await new Promise((r) => setTimeout(r, delay));
496
+ }
497
+ }
498
+ throw lastErr;
499
+ }
500
+
429
501
  // src/providers/gemini.ts
502
+ var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
503
+ var originalWarn = console.warn.bind(console);
504
+ console.warn = (...args) => {
505
+ if (typeof args[0] === "string" && args[0].startsWith(SDK_KEY_WARNING)) return;
506
+ originalWarn(...args);
507
+ };
430
508
  var MIME_BY_EXT = {
431
509
  ".flac": "audio/flac",
432
510
  ".mp3": "audio/mp3",
@@ -468,11 +546,16 @@ var GeminiClient = class {
468
546
  constructor(apiKey) {
469
547
  this.ai = new import_genai.GoogleGenAI({ apiKey });
470
548
  }
471
- /** Upload a file and wait until it's done processing. */
549
+ /** Upload a file and wait until it's done processing. Uploads ride one long HTTP
550
+ * request each — the retry loop in generate() doesn't cover them, and transient
551
+ * "fetch failed" blips here killed live runs, so they get their own retry. */
472
552
  async upload(path, mimeType) {
473
553
  const mt = mimeType || detectMime(path);
474
554
  logger.debug(`[gemini] uploading ${(0, import_node_path3.basename)(path)} (${mt})...`);
475
- let file = await this.ai.files.upload({ file: path, config: { mimeType: mt } });
555
+ let file = await withRetry(
556
+ `gemini upload ${(0, import_node_path3.basename)(path)}`,
557
+ () => this.ai.files.upload({ file: path, config: { mimeType: mt } })
558
+ );
476
559
  let tries = 0;
477
560
  while (file.state === "PROCESSING" && tries < 120) {
478
561
  await sleep(2e3);
@@ -551,10 +634,14 @@ var GeminiClient = class {
551
634
  lastError = err instanceof Error ? err.message : String(err);
552
635
  if (config.thinkingConfig && isThinkingConfigError(lastError)) {
553
636
  delete config.thinkingConfig;
554
- logger.warn(`[gemini] model ${model} rejected thinking config \u2014 retrying without it`);
637
+ logger.warn(
638
+ `[gemini] model ${model} rejected thinking config \u2014 retrying without it`
639
+ );
555
640
  continue;
556
641
  }
557
- logger.warn(`[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`);
642
+ logger.warn(
643
+ `[gemini] attempt ${attempt + 1}/${maxRetries} failed: ${lastError}`
644
+ );
558
645
  logLlmCall({
559
646
  ts: new Date(t0).toISOString(),
560
647
  provider: "gemini",
@@ -570,7 +657,11 @@ var GeminiClient = class {
570
657
  if (attempt < maxRetries - 1) await sleep(retryDelayMs * (attempt + 1));
571
658
  }
572
659
  }
573
- return { text: "", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, error: lastError };
660
+ return {
661
+ text: "",
662
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
663
+ error: lastError
664
+ };
574
665
  } finally {
575
666
  await this.cleanup(uploaded);
576
667
  }
@@ -640,7 +731,10 @@ var AssemblyAIProvider = class {
640
731
  return JSON.parse(await (0, import_promises2.readFile)(cachePath, "utf-8"));
641
732
  }
642
733
  logger.info(`[assemblyai] uploading ${filePath}...`);
643
- const uploadUrl = await this.client.files.upload(filePath);
734
+ const uploadUrl = await withRetry(
735
+ "assemblyai upload",
736
+ () => this.client.files.upload(filePath)
737
+ );
644
738
  logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
645
739
  const params = {
646
740
  audio: uploadUrl,
@@ -648,7 +742,10 @@ var AssemblyAIProvider = class {
648
742
  speech_model: this.speechModel
649
743
  };
650
744
  if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
651
- const transcript = await this.client.transcripts.transcribe(params);
745
+ const transcript = await withRetry(
746
+ "assemblyai transcribe",
747
+ () => this.client.transcripts.transcribe(params)
748
+ );
652
749
  if (transcript.status === "error") {
653
750
  throw new Error(`AssemblyAI error: ${transcript.error}`);
654
751
  }
@@ -752,9 +849,308 @@ var WhisperGroqClient = class {
752
849
  }
753
850
  };
754
851
 
852
+ // src/providers/elevenlabs.ts
853
+ var MAX_UTTERANCE_GAP_SEC = 1.5;
854
+ var ElevenLabsClient = class {
855
+ constructor(apiKey, baseUrl = "https://api.elevenlabs.io/v1") {
856
+ this.apiKey = apiKey;
857
+ this.baseUrl = baseUrl;
858
+ }
859
+ apiKey;
860
+ baseUrl;
861
+ async transcribe(audio, opts = {}) {
862
+ const model = opts.model ?? "scribe_v2";
863
+ const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
864
+ const form = new FormData();
865
+ form.append("file", blob, "audio.mp3");
866
+ form.append("model_id", model);
867
+ form.append("timestamps_granularity", "word");
868
+ form.append("diarize", "true");
869
+ form.append("tag_audio_events", "false");
870
+ if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
871
+ for (const term of opts.keyterms ?? []) form.append("keyterms", term);
872
+ const data = await withRetry("elevenlabs", async () => {
873
+ const res = await fetch(`${this.baseUrl}/speech-to-text`, {
874
+ method: "POST",
875
+ headers: { "xi-api-key": this.apiKey },
876
+ body: form
877
+ });
878
+ if (!res.ok) {
879
+ const txt = await res.text();
880
+ throw new Error(`ElevenLabs Scribe ${res.status}: ${txt.slice(0, 300)}`);
881
+ }
882
+ return await res.json();
883
+ });
884
+ const words = [];
885
+ for (const w of data.words ?? []) {
886
+ if (w.type !== "word") continue;
887
+ if (w.start === void 0 || w.end === void 0) continue;
888
+ words.push({
889
+ text: w.text.trim(),
890
+ start: w.start,
891
+ end: w.end,
892
+ speaker: w.speaker_id ?? "speaker_0"
893
+ });
894
+ }
895
+ const utterances = [];
896
+ let cur = [];
897
+ const flush = () => {
898
+ if (cur.length === 0) return;
899
+ utterances.push({
900
+ speaker: cur[0].speaker,
901
+ start: cur[0].start,
902
+ end: cur[cur.length - 1].end,
903
+ text: cur.map((w) => w.text).join(" "),
904
+ words: cur.map(({ text, start, end }) => ({ text, start, end }))
905
+ });
906
+ cur = [];
907
+ };
908
+ for (const w of words) {
909
+ const prev = cur[cur.length - 1];
910
+ if (prev && (w.speaker !== prev.speaker || w.start - prev.end > MAX_UTTERANCE_GAP_SEC)) {
911
+ flush();
912
+ }
913
+ cur.push(w);
914
+ }
915
+ flush();
916
+ const speakers = [...new Set(words.map((w) => w.speaker))];
917
+ return {
918
+ utterances,
919
+ words: words.map(({ text, start, end }) => ({ text, start, end })),
920
+ durationSec: data.audio_duration_secs ?? (words.length ? words[words.length - 1].end : 0),
921
+ speakers,
922
+ hasDiarization: true,
923
+ transcriptId: data.transcription_id ?? `elevenlabs-${model}`
924
+ };
925
+ }
926
+ };
927
+
928
+ // src/core/pricing.ts
929
+ var PRICES_AS_OF = "2026-07";
930
+ var MODEL_PRICES = {
931
+ // Gemini (ai.google.dev/gemini-api/docs/pricing, standard tier, <=200k prompts)
932
+ "gemini-3.1-pro-preview": { textIn: 2, out: 12 },
933
+ "gemini-3-pro-preview": { textIn: 2, out: 12 },
934
+ "gemini-3.5-flash": { textIn: 1.5, out: 9 },
935
+ "gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
936
+ "gemini-2.5-pro": { textIn: 1.25, out: 10 },
937
+ "gemini-2.5-flash": { textIn: 0.3, audioIn: 1, out: 2.5 },
938
+ "gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
939
+ // Moving aliases — priced as their current targets.
940
+ "gemini-pro-latest": { textIn: 2, out: 12 },
941
+ "gemini-flash-latest": { textIn: 1.5, out: 9 },
942
+ "gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
943
+ // Text reasoners
944
+ "deepseek-chat": { textIn: 0.28, out: 0.42 },
945
+ "deepseek-reasoner": { textIn: 0.28, out: 0.42 },
946
+ "gpt-4o-mini": { textIn: 0.15, out: 0.6 },
947
+ "glm-4.7": { textIn: 0.6, out: 2.2 }
948
+ };
949
+ var ASR_HOURLY = {
950
+ assemblyai: 0.15,
951
+ // universal-2, diarization included
952
+ elevenlabs: 0.4,
953
+ // scribe v2 (standard tier; business tier is lower)
954
+ "whisper-groq": 0.04,
955
+ // whisper-large-v3-turbo
956
+ none: 0
957
+ };
958
+ var AUDIO_TOKENS_PER_SEC = 32;
959
+ function priceFor(model) {
960
+ if (MODEL_PRICES[model]) return MODEL_PRICES[model];
961
+ const hit = Object.keys(MODEL_PRICES).find((k) => model.startsWith(k));
962
+ return hit ? MODEL_PRICES[hit] : null;
963
+ }
964
+ function asrCost(provider, durationSec) {
965
+ const hourly = ASR_HOURLY[provider];
966
+ if (hourly === void 0) return null;
967
+ return durationSec / 3600 * hourly;
968
+ }
969
+ function estimateRunCost(opts) {
970
+ const lines = [];
971
+ let total = 0;
972
+ let incomplete = false;
973
+ const p = priceFor(opts.model);
974
+ const chunks = Math.max(
975
+ 1,
976
+ Math.ceil((opts.durationSec - opts.overlapSec) / (opts.chunkSec - opts.overlapSec))
977
+ );
978
+ const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
979
+ if (p) {
980
+ const audioTok = billedAudioSec * AUDIO_TOKENS_PER_SEC;
981
+ const promptTok = chunks * 1500;
982
+ const outTok = opts.durationSec / 60 * 150 + 1500;
983
+ const inRate = p.audioIn ?? p.textIn;
984
+ const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
985
+ total += llmUsd;
986
+ lines.push(
987
+ `${opts.model}: ${chunks} chunk${chunks > 1 ? "s" : ""} + describe \u2248 $${llmUsd.toFixed(2)}`
988
+ );
989
+ } else {
990
+ incomplete = true;
991
+ lines.push(`${opts.model}: unpriced`);
992
+ }
993
+ const asr = asrCost(opts.tsProvider, opts.durationSec);
994
+ if (asr !== null && opts.tsProvider !== "none") {
995
+ total += asr;
996
+ lines.push(
997
+ `${opts.tsProvider}: ${(opts.durationSec / 60).toFixed(0)}min \u2248 $${asr.toFixed(2)}`
998
+ );
999
+ }
1000
+ if (opts.identify && opts.reasoner) {
1001
+ const rp = priceFor(opts.reasoner);
1002
+ if (rp) {
1003
+ const idUsd = (8e3 * rp.textIn + 1e3 * rp.out) / 1e6;
1004
+ total += idUsd;
1005
+ lines.push(`${opts.reasoner} (identify) \u2248 $${idUsd.toFixed(3)}`);
1006
+ }
1007
+ }
1008
+ return { totalUsd: total, lines, incomplete };
1009
+ }
1010
+ function computeReceipt(usage, tsProvider, durationSec) {
1011
+ let llmUsd = 0;
1012
+ let incomplete = false;
1013
+ const lines = [];
1014
+ const perModel = {};
1015
+ const totals = { calls: 0, inputTokens: 0, outputTokens: 0 };
1016
+ const byModel = /* @__PURE__ */ new Map();
1017
+ for (const r of usage) {
1018
+ totals.calls += r.calls;
1019
+ totals.inputTokens += r.inputTokens;
1020
+ totals.outputTokens += r.outputTokens;
1021
+ const m = byModel.get(r.model) ?? { in: 0, out: 0, calls: 0 };
1022
+ m.in += r.inputTokens;
1023
+ m.out += r.outputTokens;
1024
+ m.calls += r.calls;
1025
+ byModel.set(r.model, m);
1026
+ }
1027
+ for (const [model, m] of byModel) {
1028
+ const p = priceFor(model);
1029
+ if (!p) {
1030
+ incomplete = true;
1031
+ lines.push(
1032
+ `${model}: ${m.calls} calls \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 unpriced`
1033
+ );
1034
+ continue;
1035
+ }
1036
+ const usd = (m.in * (p.audioIn ?? p.textIn) + m.out * p.out) / 1e6;
1037
+ llmUsd += usd;
1038
+ perModel[model] = usd;
1039
+ lines.push(
1040
+ `${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
1041
+ );
1042
+ }
1043
+ const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
1044
+ if (asrUsd !== null && tsProvider !== "none") {
1045
+ perModel[tsProvider] = asrUsd;
1046
+ lines.push(
1047
+ `${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 $${asrUsd.toFixed(2)}`
1048
+ );
1049
+ }
1050
+ return {
1051
+ totalUsd: llmUsd + (asrUsd ?? 0),
1052
+ llmUsd,
1053
+ asrUsd,
1054
+ lines,
1055
+ totals,
1056
+ perModel,
1057
+ incomplete
1058
+ };
1059
+ }
1060
+ function fmtTok(n) {
1061
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
1062
+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
1063
+ return String(n);
1064
+ }
1065
+
1066
+ // src/core/stats.ts
1067
+ var import_node_fs4 = require("fs");
1068
+ var import_node_os2 = require("os");
1069
+ var import_node_path5 = require("path");
1070
+ function statsDir() {
1071
+ return process.env.OFFMUTE_HOME || (0, import_node_path5.join)((0, import_node_os2.homedir)(), ".offmute");
1072
+ }
1073
+ function statsEnabled() {
1074
+ return !process.env.OFFMUTE_NO_STATS;
1075
+ }
1076
+ var EMPTY = {
1077
+ runs: 0,
1078
+ mediaSeconds: 0,
1079
+ characters: 0,
1080
+ llmCalls: 0,
1081
+ inputTokens: 0,
1082
+ outputTokens: 0,
1083
+ costUsd: 0,
1084
+ costByModel: {},
1085
+ runsByModel: {}
1086
+ };
1087
+ function readStats() {
1088
+ try {
1089
+ const p = (0, import_node_path5.join)(statsDir(), "stats.json");
1090
+ if (!(0, import_node_fs4.existsSync)(p)) return { ...EMPTY };
1091
+ return { ...EMPTY, ...JSON.parse((0, import_node_fs4.readFileSync)(p, "utf-8")) };
1092
+ } catch {
1093
+ return { ...EMPTY };
1094
+ }
1095
+ }
1096
+ function withStatsLock(dir, fn) {
1097
+ const lock = (0, import_node_path5.join)(dir, ".stats.lock");
1098
+ const deadline = Date.now() + 2e3;
1099
+ for (; ; ) {
1100
+ try {
1101
+ (0, import_node_fs4.mkdirSync)(lock);
1102
+ break;
1103
+ } catch {
1104
+ if (Date.now() > deadline) break;
1105
+ const until = Date.now() + 25;
1106
+ while (Date.now() < until) {
1107
+ }
1108
+ }
1109
+ }
1110
+ try {
1111
+ fn();
1112
+ } finally {
1113
+ try {
1114
+ (0, import_node_fs4.rmdirSync)(lock);
1115
+ } catch {
1116
+ }
1117
+ }
1118
+ }
1119
+ function recordRun(rec, perModelCost) {
1120
+ if (!statsEnabled()) return;
1121
+ try {
1122
+ const dir = statsDir();
1123
+ (0, import_node_fs4.mkdirSync)(dir, { recursive: true });
1124
+ (0, import_node_fs4.appendFileSync)((0, import_node_path5.join)(dir, "history.jsonl"), JSON.stringify(rec) + "\n");
1125
+ withStatsLock(dir, () => {
1126
+ foldIntoAggregates(rec, perModelCost, dir);
1127
+ });
1128
+ } catch {
1129
+ }
1130
+ }
1131
+ function foldIntoAggregates(rec, perModelCost, dir) {
1132
+ const s = readStats();
1133
+ s.runs += 1;
1134
+ s.mediaSeconds += rec.durationSec;
1135
+ s.characters += rec.characters;
1136
+ s.llmCalls += rec.llmCalls;
1137
+ s.inputTokens += rec.inputTokens;
1138
+ s.outputTokens += rec.outputTokens;
1139
+ if (rec.costUsd !== null) s.costUsd += rec.costUsd;
1140
+ for (const [model, usd] of Object.entries(perModelCost)) {
1141
+ s.costByModel[model] = (s.costByModel[model] ?? 0) + usd;
1142
+ }
1143
+ const tModel = rec.models.transcribe;
1144
+ if (tModel) s.runsByModel[tModel] = (s.runsByModel[tModel] ?? 0) + 1;
1145
+ s.firstRun ??= rec.ts;
1146
+ s.lastRun = rec.ts;
1147
+ (0, import_node_fs4.writeFileSync)((0, import_node_path5.join)(dir, "stats.json"), JSON.stringify(s, null, 2));
1148
+ }
1149
+
755
1150
  // src/transcribe/describe.ts
756
- function descriptionPrompt(fileName, instructions) {
757
- return `You are listening to a recording to prepare a transcription engine. Describe what you hear${instructions ? ` (note: ${instructions})` : ""}.
1151
+ function descriptionPrompt(fileName, instructions, sampleCount = 1) {
1152
+ 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.`;
1153
+ return `${sampleNote} Your job is to prepare context for a transcription engine. Describe what you hear${instructions ? ` (note: ${instructions})` : ""}.
758
1154
 
759
1155
  Respond in TWO sections, clearly separated by a line containing only "---":
760
1156
 
@@ -764,17 +1160,24 @@ A short paragraph: what kind of recording this is, the setting, the main topics,
764
1160
  ROSTER
765
1161
  A bulleted speaker roster. For each distinct speaker you can identify, give:
766
1162
  - A short label to use consistently (a name/role if you can infer it, e.g. "Presenter (Hrishi)", else "Speaker A").
767
- - A one-line description (voice, role, accent if notable).
1163
+ - A one-line description anchored to the VOICE itself (pitch, pace, accent, audio quality/mic distance) plus role if evident.
768
1164
  List the people you can distinguish. Do not invent names you didn't hear. If only one person speaks, say so.
769
1165
 
1166
+ 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.
1167
+
770
1168
  File: ${fileName}`;
771
1169
  }
772
- async function describeMeeting(client, model, files, fileName, instructions) {
773
- const res = await client.generate(model, descriptionPrompt(fileName, instructions), files, {
774
- temperature: 0.2,
775
- maxRetries: 3,
776
- logKind: "describe"
777
- });
1170
+ async function describeMeeting(client, model, files, fileName, instructions, audioSampleCount = 1) {
1171
+ const res = await client.generate(
1172
+ model,
1173
+ descriptionPrompt(fileName, instructions, audioSampleCount),
1174
+ files,
1175
+ {
1176
+ temperature: 0.2,
1177
+ maxRetries: 3,
1178
+ logKind: "describe"
1179
+ }
1180
+ );
778
1181
  const text = res.text || "";
779
1182
  const parts = text.split(/\n---\n|\n\s*---\s*\n/);
780
1183
  const description = parts[0]?.trim() || text.trim();
@@ -791,14 +1194,23 @@ var TRANSCRIPT_SCHEMA = {
791
1194
  items: {
792
1195
  type: "OBJECT",
793
1196
  properties: {
794
- speaker: { type: "STRING", description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc." },
795
- start: { type: "STRING", description: "Relative start time as mm:ss (00:00 = start of this audio chunk)" },
1197
+ speaker: {
1198
+ type: "STRING",
1199
+ description: "Speaker label. Use an identified name from the roster if confident, else 'Speaker A', 'Speaker B', etc."
1200
+ },
1201
+ start: {
1202
+ type: "STRING",
1203
+ description: "Relative start time as mm:ss (00:00 = start of this audio chunk)"
1204
+ },
796
1205
  end: { type: "STRING", description: "Relative end time as mm:ss" },
797
- text: { type: "STRING", description: "Verbatim transcribed words, including fillers and false starts" },
1206
+ text: {
1207
+ type: "STRING",
1208
+ description: "Verbatim transcribed words, including fillers and false starts"
1209
+ },
798
1210
  tone: {
799
1211
  type: "ARRAY",
800
1212
  items: { type: "STRING" },
801
- description: "Tone/behavior tags e.g. hesitant, laughing, contemplating, urgent, sarcastic. Empty array if neutral."
1213
+ description: "Tone tags ONLY when something clearly stands out (laughing, sarcastic, agitated, whispering). Empty array for normal speech \u2014 most segments."
802
1214
  }
803
1215
  },
804
1216
  required: ["speaker", "start", "end", "text"]
@@ -813,19 +1225,40 @@ function transcriptionPrompt(ctx) {
813
1225
  `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.`
814
1226
  );
815
1227
  parts.push("");
816
- parts.push("Output one segment per speaker turn (a new segment whenever the speaker changes, or after a long pause, or at an interruption).");
1228
+ parts.push(
1229
+ `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.`
1230
+ );
817
1231
  parts.push("");
818
1232
  parts.push("For each segment provide:");
819
- 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.");
820
- 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.");
821
- parts.push("- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase.");
822
- 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.");
1233
+ parts.push(
1234
+ "- 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."
1235
+ );
1236
+ parts.push(
1237
+ "- 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."
1238
+ );
1239
+ parts.push(
1240
+ "- text: the verbatim words, including fillers (um, uh), false starts, and corrections. Do not paraphrase."
1241
+ );
1242
+ parts.push(
1243
+ '- 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".'
1244
+ );
823
1245
  parts.push("");
824
1246
  parts.push("Rules:");
825
- parts.push("- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing.");
826
- parts.push("- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap.");
827
- parts.push("- Do not invent content not present in the audio. If inaudible, write [inaudible].");
828
- parts.push("- Keep speaker labels consistent within this chunk; the same voice = same label.");
1247
+ parts.push(
1248
+ "- Cover the ENTIRE audio with no gaps. Timestamps must be monotonic non-decreasing."
1249
+ );
1250
+ parts.push(
1251
+ "- Capture interruptions and overlapping talk as separate, adjacent segments even if times overlap."
1252
+ );
1253
+ parts.push(
1254
+ "- Listen for voice characteristics (pitch, accent, mic distance), not just content. Two people agreeing with each other are still two segments."
1255
+ );
1256
+ parts.push(
1257
+ "- Do not invent content not present in the audio. If inaudible, write [inaudible]."
1258
+ );
1259
+ parts.push(
1260
+ "- Keep speaker labels consistent within this chunk; the same voice = same label."
1261
+ );
829
1262
  if (ctx.description) {
830
1263
  parts.push("");
831
1264
  parts.push("MEETING CONTEXT:");
@@ -833,12 +1266,20 @@ function transcriptionPrompt(ctx) {
833
1266
  }
834
1267
  if (ctx.roster) {
835
1268
  parts.push("");
836
- parts.push("SPEAKER ROSTER (prefer these labels/names when you can identify the voice):");
1269
+ parts.push(
1270
+ "SPEAKER ROSTER (context about who is present \u2014 but its name-to-voice binding may be wrong):"
1271
+ );
837
1272
  parts.push(ctx.roster);
1273
+ parts.push("");
1274
+ parts.push(
1275
+ "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."
1276
+ );
838
1277
  }
839
1278
  if (ctx.previousTail) {
840
1279
  parts.push("");
841
- parts.push("TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):");
1280
+ parts.push(
1281
+ "TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
1282
+ );
842
1283
  parts.push(ctx.previousTail);
843
1284
  }
844
1285
  if (ctx.instructions) {
@@ -847,7 +1288,9 @@ function transcriptionPrompt(ctx) {
847
1288
  parts.push(ctx.instructions);
848
1289
  }
849
1290
  parts.push("");
850
- parts.push("Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }");
1291
+ parts.push(
1292
+ "Return JSON matching the schema: { segments: [ {speaker, start, end, text, tone} ] }"
1293
+ );
851
1294
  return parts.join("\n");
852
1295
  }
853
1296
 
@@ -873,7 +1316,10 @@ function timestampToSeconds(timestamp) {
873
1316
  function parseSrtTiming(timingString) {
874
1317
  const parts = timingString.split("-->");
875
1318
  if (parts.length !== 2) return null;
876
- return { start: timestampToSeconds(parts[0].trim()), end: timestampToSeconds(parts[1].trim()) };
1319
+ return {
1320
+ start: timestampToSeconds(parts[0].trim()),
1321
+ end: timestampToSeconds(parts[1].trim())
1322
+ };
877
1323
  }
878
1324
  function formatSrtTiming(startSeconds, endSeconds) {
879
1325
  return `${secondsToTimestamp(startSeconds)} --> ${secondsToTimestamp(endSeconds)}`;
@@ -887,6 +1333,16 @@ function parseMmSs(timeStr) {
887
1333
  if (seconds < 0 || seconds >= 60) return null;
888
1334
  return minutes * 60 + seconds;
889
1335
  }
1336
+ function formatDuration(seconds) {
1337
+ const hours = Math.floor(seconds / 3600);
1338
+ const minutes = Math.floor(seconds % 3600 / 60);
1339
+ const remaining = Math.floor(seconds % 60);
1340
+ const parts = [];
1341
+ if (hours > 0) parts.push(`${hours}h`);
1342
+ if (minutes > 0) parts.push(`${minutes}m`);
1343
+ parts.push(`${remaining}s`);
1344
+ return parts.join(" ");
1345
+ }
890
1346
 
891
1347
  // src/transcribe/llm-transcribe.ts
892
1348
  var MIN_SEGMENTS = 3;
@@ -910,7 +1366,9 @@ function parseLlmSegments(data, chunkOffsetSec) {
910
1366
  const end = toAbsolute(seg.end, chunkOffsetSec);
911
1367
  if (start === null || end === null || end < start) {
912
1368
  dropped++;
913
- logger.debug(`[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`);
1369
+ logger.debug(
1370
+ `[llm] dropping segment (bad time ${seg.start}-${seg.end}): "${(seg.text || "").slice(0, 40)}"`
1371
+ );
914
1372
  continue;
915
1373
  }
916
1374
  out.push({
@@ -927,16 +1385,31 @@ function parseLlmSegments(data, chunkOffsetSec) {
927
1385
  }
928
1386
  function validate(segments, chunkDuration) {
929
1387
  if (segments.length < MIN_SEGMENTS) {
930
- return { isValid: false, spanSec: 0, segmentCount: segments.length, message: `only ${segments.length} segments (min ${MIN_SEGMENTS})` };
1388
+ return {
1389
+ isValid: false,
1390
+ spanSec: 0,
1391
+ segmentCount: segments.length,
1392
+ message: `only ${segments.length} segments (min ${MIN_SEGMENTS})`
1393
+ };
931
1394
  }
932
1395
  const first = segments[0].startSec;
933
1396
  const last = segments[segments.length - 1].endSec;
934
1397
  const span = last - first;
935
1398
  const minSpan = chunkDuration * MIN_SPAN_RATIO;
936
1399
  if (span < minSpan) {
937
- 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)` };
1400
+ return {
1401
+ isValid: false,
1402
+ spanSec: span,
1403
+ segmentCount: segments.length,
1404
+ message: `span ${span.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)`
1405
+ };
938
1406
  }
939
- return { isValid: true, spanSec: span, segmentCount: segments.length, message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)` };
1407
+ return {
1408
+ isValid: true,
1409
+ spanSec: span,
1410
+ segmentCount: segments.length,
1411
+ message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)`
1412
+ };
940
1413
  }
941
1414
  async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
942
1415
  const validationRetries = opts.validationRetries ?? 1;
@@ -960,22 +1433,35 @@ async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opt
960
1433
  segments: [],
961
1434
  raw: gen.raw,
962
1435
  usage: gen.usage,
963
- validation: { isValid: false, spanSec: 0, segmentCount: 0, message: gen.error || "no data" },
1436
+ validation: {
1437
+ isValid: false,
1438
+ spanSec: 0,
1439
+ segmentCount: 0,
1440
+ message: gen.error || "no data"
1441
+ },
964
1442
  error: gen.error
965
1443
  };
966
- logger.warn(`[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`);
1444
+ logger.warn(
1445
+ `[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
1446
+ );
967
1447
  continue;
968
1448
  }
969
1449
  const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
970
1450
  const v = validate(segments, opts.chunkDurationSec);
971
1451
  lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
972
1452
  if (v.isValid) {
973
- logger.info(`[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`);
1453
+ logger.info(
1454
+ `[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
1455
+ );
974
1456
  return lastResult;
975
1457
  }
976
- logger.warn(`[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`);
1458
+ logger.warn(
1459
+ `[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
1460
+ );
977
1461
  }
978
- logger.error(`[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`);
1462
+ logger.error(
1463
+ `[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
1464
+ );
979
1465
  return lastResult;
980
1466
  }
981
1467
 
@@ -987,8 +1473,8 @@ function tokenize(text) {
987
1473
  const out = [];
988
1474
  for (const raw of text.split(/\s+/)) {
989
1475
  if (!raw) continue;
990
- const norm = normalize(raw);
991
- if (norm) out.push({ original: raw, norm });
1476
+ const norm2 = normalize(raw);
1477
+ if (norm2) out.push({ original: raw, norm: norm2 });
992
1478
  }
993
1479
  return out;
994
1480
  }
@@ -1112,7 +1598,11 @@ function transferTiming(llm, asr, ops) {
1112
1598
  for (const op of ops) {
1113
1599
  if (op.type === "match" || op.type === "substitute") {
1114
1600
  const a = asr[op.asr];
1115
- times[op.llm] = { start: a.start, end: a.end, matched: op.type === "match" && !op.fuzzy };
1601
+ times[op.llm] = {
1602
+ start: a.start,
1603
+ end: a.end,
1604
+ matched: op.type === "match" && !op.fuzzy
1605
+ };
1116
1606
  }
1117
1607
  }
1118
1608
  for (let k = 0; k < times.length; k++) {
@@ -1281,7 +1771,12 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
1281
1771
  tone: [],
1282
1772
  confidence: 0,
1283
1773
  timingSource: "timestamped",
1284
- words: words.map((w) => ({ text: w.text, start: w.start, end: w.end, matched: true })),
1774
+ words: words.map((w) => ({
1775
+ text: w.text,
1776
+ start: w.start,
1777
+ end: w.end,
1778
+ matched: true
1779
+ })),
1285
1780
  sourceIndex: -1
1286
1781
  });
1287
1782
  }
@@ -1294,8 +1789,19 @@ function overlap(s1, e1, s2, e2) {
1294
1789
  return Math.max(0, Math.min(e1, e2) - Math.max(s1, s2));
1295
1790
  }
1296
1791
  function isGenericLabel(label) {
1297
- return /^(speaker\s+[a-z0-9]+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(label.trim());
1792
+ return /^(speaker\s+[a-z0-9]+|voice\s+\S+|unknown|audience(\s+member)?(\s+\d+)?)$/i.test(
1793
+ label.trim()
1794
+ );
1795
+ }
1796
+ function countTurnTransitions(utterances, a, b) {
1797
+ const seq = [...utterances].sort((x, y) => x.start - y.start).map((u) => u.speaker).filter((s) => s === a || s === b);
1798
+ let transitions = 0;
1799
+ for (let i = 1; i < seq.length; i++) {
1800
+ if (seq[i] !== seq[i - 1]) transitions++;
1801
+ }
1802
+ return transitions;
1298
1803
  }
1804
+ var MAX_MERGE_TRANSITIONS = 3;
1299
1805
  function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
1300
1806
  const hasDiarization = opts.hasDiarization ?? true;
1301
1807
  const out = segments.map((seg) => ({ seg, asrSpeaker: "" }));
@@ -1347,7 +1853,18 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
1347
1853
  const label = dominantLabel[asrSp] ?? asrSp;
1348
1854
  let groupId;
1349
1855
  if (!isGenericLabel(label)) {
1350
- groupId = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
1856
+ const candidate = Object.keys(groupLabel).find((g) => groupLabel[g] === label);
1857
+ if (candidate && hasDiarization) {
1858
+ const partners = groupAsrVoices[candidate] ?? [];
1859
+ const maxTransitions = Math.max(
1860
+ ...partners.map((p) => countTurnTransitions(asrUtterances, p, asrSp))
1861
+ );
1862
+ if (maxTransitions <= MAX_MERGE_TRANSITIONS) {
1863
+ groupId = candidate;
1864
+ }
1865
+ } else if (candidate) {
1866
+ groupId = candidate;
1867
+ }
1351
1868
  }
1352
1869
  if (!groupId) {
1353
1870
  groupId = asrSp;
@@ -1357,15 +1874,24 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
1357
1874
  groupTalk[groupId] = (groupTalk[groupId] ?? 0) + (asrDuration[asrSp] ?? 0);
1358
1875
  (groupAsrVoices[groupId] ??= []).push(asrSp);
1359
1876
  }
1360
- const groupsByTalk = Object.keys(groupTalk).sort((a, b) => groupTalk[b] - groupTalk[a]);
1877
+ const groupsByTalk = Object.keys(groupTalk).sort(
1878
+ (a, b) => groupTalk[b] - groupTalk[a]
1879
+ );
1361
1880
  const groupToGlobal = {};
1362
1881
  groupsByTalk.forEach((g, i) => {
1363
1882
  groupToGlobal[g] = `Speaker ${String.fromCharCode(65 + i)}`;
1364
1883
  });
1884
+ const labelGroupCount = {};
1885
+ for (const g of groupsByTalk) {
1886
+ const label = groupLabel[g];
1887
+ if (!isGenericLabel(label))
1888
+ labelGroupCount[label] = (labelGroupCount[label] ?? 0) + 1;
1889
+ }
1365
1890
  const displayNames = {};
1366
1891
  for (const g of groupsByTalk) {
1367
1892
  const label = groupLabel[g];
1368
- displayNames[groupToGlobal[g]] = isGenericLabel(label) ? groupToGlobal[g] : label;
1893
+ const contested = (labelGroupCount[label] ?? 0) > 1;
1894
+ displayNames[groupToGlobal[g]] = isGenericLabel(label) || contested ? groupToGlobal[g] : label;
1369
1895
  }
1370
1896
  const llmLabelToAsr = {};
1371
1897
  for (const o of out) {
@@ -1399,6 +1925,111 @@ function assignGlobalSpeakers(segments, asrUtterances, opts = {}) {
1399
1925
  return { segments: updated, speakers, displayNames, llmLabelToAsr };
1400
1926
  }
1401
1927
 
1928
+ // src/diarize/split-mixed.ts
1929
+ var MIN_RUN_WORDS = 5;
1930
+ var MIN_RUN_SEC = 2;
1931
+ function clusterAt(utterances, t) {
1932
+ let best = "";
1933
+ let bestDist = Infinity;
1934
+ for (const u of utterances) {
1935
+ if (t >= u.start && t <= u.end) return u.speaker;
1936
+ const d = t < u.start ? u.start - t : t - u.end;
1937
+ if (d < bestDist) {
1938
+ bestDist = d;
1939
+ best = u.speaker;
1940
+ }
1941
+ }
1942
+ return best;
1943
+ }
1944
+ function buildRuns(words, utterances) {
1945
+ const clusters = words.map(
1946
+ (w) => w.matched ? clusterAt(utterances, (w.start + w.end) / 2) : null
1947
+ );
1948
+ for (let i = 1; i < clusters.length; i++) {
1949
+ if (clusters[i] === null) clusters[i] = clusters[i - 1] ?? null;
1950
+ }
1951
+ for (let i = clusters.length - 2; i >= 0; i--) {
1952
+ if (clusters[i] === null) clusters[i] = clusters[i + 1] ?? null;
1953
+ }
1954
+ const runs = [];
1955
+ for (let i = 0; i < clusters.length; i++) {
1956
+ const c = clusters[i] ?? "";
1957
+ const last = runs[runs.length - 1];
1958
+ if (last && last.cluster === c) last.endIdx = i + 1;
1959
+ else runs.push({ cluster: c, startIdx: i, endIdx: i + 1 });
1960
+ }
1961
+ return runs;
1962
+ }
1963
+ function runSec(run2, words) {
1964
+ return words[run2.endIdx - 1].end - words[run2.startIdx].start;
1965
+ }
1966
+ function foldShortRuns(runs, words) {
1967
+ let out = runs;
1968
+ let changed = true;
1969
+ while (changed && out.length > 1) {
1970
+ changed = false;
1971
+ for (let i = 0; i < out.length; i++) {
1972
+ const r = out[i];
1973
+ const nWords = r.endIdx - r.startIdx;
1974
+ if (nWords >= MIN_RUN_WORDS || runSec(r, words) >= MIN_RUN_SEC) continue;
1975
+ const prev = out[i - 1];
1976
+ const next = out[i + 1];
1977
+ const target = prev && next ? prev.endIdx - prev.startIdx >= next.endIdx - next.startIdx ? prev : next : prev ?? next;
1978
+ if (!target) continue;
1979
+ if (target === prev) prev.endIdx = r.endIdx;
1980
+ else next.startIdx = r.startIdx;
1981
+ out = out.filter((_, j) => j !== i);
1982
+ changed = true;
1983
+ break;
1984
+ }
1985
+ const merged = [];
1986
+ for (const r of out) {
1987
+ const last = merged[merged.length - 1];
1988
+ if (last && last.cluster === r.cluster) last.endIdx = r.endIdx;
1989
+ else merged.push({ ...r });
1990
+ }
1991
+ out = merged;
1992
+ }
1993
+ return out;
1994
+ }
1995
+ function splitMixedVoiceSegments(segments, utterances) {
1996
+ if (utterances.length === 0) return segments;
1997
+ const out = [];
1998
+ let splits = 0;
1999
+ for (const seg of segments) {
2000
+ const matched = seg.words.filter((w) => w.matched).length;
2001
+ if (seg.words.length < MIN_RUN_WORDS * 2 || matched < seg.words.length * 0.4) {
2002
+ out.push(seg);
2003
+ continue;
2004
+ }
2005
+ const runs = foldShortRuns(buildRuns(seg.words, utterances), seg.words);
2006
+ if (runs.length <= 1) {
2007
+ out.push(seg);
2008
+ continue;
2009
+ }
2010
+ splits += runs.length - 1;
2011
+ const lens = runs.map((r) => r.endIdx - r.startIdx);
2012
+ const dominantIdx = lens.indexOf(Math.max(...lens));
2013
+ runs.forEach((run2, ri) => {
2014
+ const words = seg.words.slice(run2.startIdx, run2.endIdx);
2015
+ out.push({
2016
+ ...seg,
2017
+ start: words[0].start,
2018
+ end: words[words.length - 1].end,
2019
+ text: words.map((w) => w.text).join(" "),
2020
+ words,
2021
+ speaker: ri === dominantIdx ? seg.speaker : `Voice ${run2.cluster}`
2022
+ });
2023
+ });
2024
+ }
2025
+ if (splits > 0) {
2026
+ logger.info(
2027
+ `split ${splits} mixed-voice boundary(ies) across ${segments.length} segments`
2028
+ );
2029
+ }
2030
+ return out.sort((a, b) => a.start - b.start);
2031
+ }
2032
+
1402
2033
  // src/providers/openai-compat.ts
1403
2034
  var PROVIDER_BASE = {
1404
2035
  deepseek: "https://api.deepseek.com/v1",
@@ -1422,7 +2053,7 @@ var OpenAICompatClient = class _OpenAICompatClient {
1422
2053
  }
1423
2054
  async chat(model, messages, opts = {}) {
1424
2055
  const m = model ?? this.defaultModel;
1425
- const maxRetries = opts.maxRetries ?? 2;
2056
+ const maxRetries = opts.maxRetries ?? 5;
1426
2057
  const body = {
1427
2058
  model: m,
1428
2059
  messages,
@@ -1432,6 +2063,9 @@ var OpenAICompatClient = class _OpenAICompatClient {
1432
2063
  if (opts.responseJson) {
1433
2064
  body.response_format = { type: "json_object" };
1434
2065
  }
2066
+ if (this.providerName === "gemini") {
2067
+ body.reasoning_effort = "low";
2068
+ }
1435
2069
  let lastError;
1436
2070
  const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
1437
2071
  for (let attempt = 0; attempt < maxRetries; attempt++) {
@@ -1469,6 +2103,14 @@ var OpenAICompatClient = class _OpenAICompatClient {
1469
2103
  return { text, usage };
1470
2104
  } catch (err) {
1471
2105
  lastError = err instanceof Error ? err.message : String(err);
2106
+ if (body.response_format && /response_format/i.test(lastError)) {
2107
+ delete body.response_format;
2108
+ continue;
2109
+ }
2110
+ if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
2111
+ delete body.reasoning_effort;
2112
+ continue;
2113
+ }
1472
2114
  logLlmCall({
1473
2115
  ts: new Date(t0).toISOString(),
1474
2116
  provider: this.providerName,
@@ -1480,61 +2122,109 @@ var OpenAICompatClient = class _OpenAICompatClient {
1480
2122
  attempt: attempt + 1,
1481
2123
  error: lastError
1482
2124
  });
1483
- if (attempt < maxRetries - 1) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
2125
+ if (attempt < maxRetries - 1)
2126
+ await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
1484
2127
  }
1485
2128
  }
1486
2129
  return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
1487
2130
  }
1488
2131
  async chatJson(model, messages, opts = {}) {
1489
- const res = await this.chat(model, messages, { ...opts, responseJson: true });
1490
- if (res.error || !res.text) return { data: null, raw: res.text, error: res.error };
1491
- try {
1492
- let txt = res.text.trim();
1493
- const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
1494
- if (fence && fence[1]) txt = fence[1];
1495
- return { data: JSON.parse(txt), raw: res.text };
1496
- } catch (err) {
1497
- return { data: null, raw: res.text, error: `JSON parse: ${err instanceof Error ? err.message : String(err)}` };
2132
+ let lastRaw = "";
2133
+ let lastError;
2134
+ for (let attempt = 0; attempt < 2; attempt++) {
2135
+ const res = await this.chat(model, messages, { ...opts, responseJson: true });
2136
+ lastRaw = res.text;
2137
+ lastError = res.error;
2138
+ if (res.error || !res.text) continue;
2139
+ try {
2140
+ let txt = res.text.trim();
2141
+ const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
2142
+ if (fence && fence[1]) txt = fence[1];
2143
+ return { data: JSON.parse(txt), raw: res.text };
2144
+ } catch (err) {
2145
+ lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
2146
+ }
1498
2147
  }
2148
+ return { data: null, raw: lastRaw, error: lastError };
1499
2149
  }
1500
2150
  };
1501
2151
 
1502
2152
  // src/diarize/identify.ts
2153
+ var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
1503
2154
  function buildTranscriptExcerpt(segments, speakers) {
2155
+ const speakerHeader = (sp) => {
2156
+ const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
2157
+ return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
2158
+ };
2159
+ const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
2160
+ if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
2161
+ const parts2 = [
2162
+ "SPEAKERS:",
2163
+ ...speakers.map((sp) => `- ${speakerHeader(sp)}`),
2164
+ "",
2165
+ "FULL TRANSCRIPT (in order):"
2166
+ ];
2167
+ for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
2168
+ return parts2.join("\n");
2169
+ }
1504
2170
  const bySpeaker = {};
1505
2171
  for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
1506
2172
  const parts = [];
1507
2173
  for (const sp of speakers) {
1508
2174
  const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
1509
- const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
1510
- parts.push(
1511
- `### ${sp.id} (${sp.name || "unknown"}, ${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s${voices})`
1512
- );
2175
+ parts.push(`### ${speakerHeader(sp)}`);
1513
2176
  for (const s of segs) parts.push(` ${s.text}`);
1514
2177
  }
1515
2178
  return parts.join("\n");
1516
2179
  }
1517
- function identifyPrompt(transcriptExcerpt, roster, knownSpeakers) {
1518
- 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.
2180
+ function identifyPrompt(transcriptExcerpt, roster, knownSpeakers, nameHints, sourceFileName) {
2181
+ const hintBlock = nameHints && Object.keys(nameHints).length ? `
2182
+ 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):
2183
+ ${Object.entries(
2184
+ nameHints
2185
+ ).map(([id, n]) => ` ${id} was tentatively called "${n}"`).join("\n")}
2186
+ ` : "";
2187
+ 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.
1519
2188
 
1520
2189
  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 ("").
1521
2190
 
2191
+ 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.
2192
+
2193
+ 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.
2194
+
2195
+ 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).
2196
+
1522
2197
  ${knownSpeakers && knownSpeakers.length ? `Known possible speakers: ${knownSpeakers.join(", ")}
2198
+ ` : ""}${sourceFileName ? `RECORDING FILENAME (often names participants): ${sourceFileName}
1523
2199
  ` : ""}ROSTER:
1524
2200
  ${roster}
1525
-
1526
- TRANSCRIPT EXCERPTS BY SPEAKER:
2201
+ ${hintBlock}
2202
+ TRANSCRIPT:
1527
2203
  ${transcriptExcerpt}
1528
2204
 
1529
- 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" }
1530
- Use the EXACT speaker id strings from the headers above (e.g. "Speaker A").`;
2205
+ 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" }
2206
+ 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.`;
1531
2207
  }
1532
- async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers) {
2208
+ async function identifySpeakers(client, model, segments, speakers, roster, knownSpeakers, nameHints, sourceFileName) {
1533
2209
  const excerpt = buildTranscriptExcerpt(segments, speakers);
1534
2210
  const { data, error } = await client.chatJson(
1535
2211
  model,
1536
- [{ role: "user", content: identifyPrompt(excerpt, roster, knownSpeakers) }],
1537
- { temperature: 0.1, maxTokens: 2e3, logKind: "identify" }
2212
+ [
2213
+ {
2214
+ role: "user",
2215
+ content: identifyPrompt(
2216
+ excerpt,
2217
+ roster,
2218
+ knownSpeakers,
2219
+ nameHints,
2220
+ sourceFileName
2221
+ )
2222
+ }
2223
+ ],
2224
+ // 8000 tokens: verbose models quote long verbatim evidence, and Gemini's compat
2225
+ // endpoint spends part of the budget on thinking — tighter caps truncated
2226
+ // mid-JSON and silently emptied whole identify passes (observed live, twice).
2227
+ { temperature: 0.1, maxTokens: 8e3, logKind: "identify" }
1538
2228
  );
1539
2229
  if (error || !data) {
1540
2230
  return { nameMap: {}, speakers: [], reasoning: error || "no response" };
@@ -1546,6 +2236,368 @@ async function identifySpeakers(client, model, segments, speakers, roster, known
1546
2236
  return { nameMap, speakers: data.speakers || [], reasoning: data.reasoning || "" };
1547
2237
  }
1548
2238
 
2239
+ // src/diarize/identify2.ts
2240
+ var norm = (s) => s.toLowerCase().replace(/['’]/g, "").replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
2241
+ function withinOneEdit(a, b) {
2242
+ if (a === b) return true;
2243
+ if (Math.abs(a.length - b.length) > 1) return false;
2244
+ const [s, l] = a.length <= b.length ? [a, b] : [b, a];
2245
+ let i = 0;
2246
+ let j = 0;
2247
+ let edits = 0;
2248
+ while (i < s.length && j < l.length) {
2249
+ if (s[i] === l[j]) {
2250
+ i++;
2251
+ j++;
2252
+ continue;
2253
+ }
2254
+ if (++edits > 1) return false;
2255
+ if (s.length === l.length) i++;
2256
+ j++;
2257
+ }
2258
+ return edits + (l.length - j) <= 1;
2259
+ }
2260
+ function tokensMatch(a, b) {
2261
+ if (a === b) return true;
2262
+ return a.length >= 5 && b.length >= 5 && withinOneEdit(a, b);
2263
+ }
2264
+ function namesMatch(a, b) {
2265
+ const na = norm(a);
2266
+ const nb = norm(b);
2267
+ if (!na || !nb) return false;
2268
+ if (na === nb) return true;
2269
+ const ta = na.split(" ");
2270
+ const tb = nb.split(" ");
2271
+ const [small, big] = ta.length <= tb.length ? [ta, tb] : [tb, ta];
2272
+ return small.every((t) => big.some((u) => tokensMatch(t, u)));
2273
+ }
2274
+ function evidenceInTranscript(evidence, transcript) {
2275
+ if (!evidence) return false;
2276
+ const ne = norm(evidence);
2277
+ if (ne.length < 8) return false;
2278
+ return transcript.includes(ne);
2279
+ }
2280
+ var INTRO_RE = /\b(?:[Mm]y name is|I am|I'm)[,\s]+([A-Z][\p{L}'’-]+(?:\s+[A-Z][\p{L}'’-]+)?)/gu;
2281
+ var INTRO_STOPWORDS = /* @__PURE__ */ new Set([
2282
+ "i",
2283
+ "im",
2284
+ "ive",
2285
+ "id",
2286
+ "ill",
2287
+ "you",
2288
+ "we",
2289
+ "they",
2290
+ "he",
2291
+ "she",
2292
+ "it",
2293
+ "so",
2294
+ "not",
2295
+ "just",
2296
+ "here",
2297
+ "there",
2298
+ "going",
2299
+ "gonna",
2300
+ "really",
2301
+ "very",
2302
+ "also",
2303
+ "still",
2304
+ "sure",
2305
+ "sorry",
2306
+ "happy",
2307
+ "glad",
2308
+ "excited",
2309
+ "curious",
2310
+ "the",
2311
+ "a",
2312
+ "an",
2313
+ "okay",
2314
+ "ok",
2315
+ "now",
2316
+ "like",
2317
+ "actually",
2318
+ "basically",
2319
+ "kind",
2320
+ "sort",
2321
+ "definitely"
2322
+ ]);
2323
+ function findSelfIntroductions(segments) {
2324
+ const out = [];
2325
+ for (const seg of segments) {
2326
+ for (const m of seg.text.matchAll(INTRO_RE)) {
2327
+ const name = m[1].trim();
2328
+ const tokens = name.split(/\s+/).map((t) => t.toLowerCase().replace(/['’]/g, ""));
2329
+ if (tokens.some((t) => INTRO_STOPWORDS.has(t))) continue;
2330
+ if (name.replace(/[^\p{L}]/gu, "").length < 3) continue;
2331
+ out.push({
2332
+ speakerId: seg.speaker,
2333
+ introducedName: name,
2334
+ segmentText: seg.text.slice(0, 160)
2335
+ });
2336
+ }
2337
+ }
2338
+ return out;
2339
+ }
2340
+ function pickCompleteName(a, b) {
2341
+ if (!a) return b ?? "";
2342
+ if (!b) return a;
2343
+ return b.trim().split(/\s+/).length > a.trim().split(/\s+/).length ? b.trim() : a.trim();
2344
+ }
2345
+ function adjudicate(speakerId, a, b, transcriptNorm, intro, introCorroborated = false) {
2346
+ const base = {
2347
+ speakerId,
2348
+ nameA: a.name,
2349
+ nameB: b?.name,
2350
+ outcome: "kept-generic"
2351
+ };
2352
+ const aName = a.name?.trim() || void 0;
2353
+ const bName = b?.name?.trim() || void 0;
2354
+ if (b === void 0) {
2355
+ if (!aName) return base;
2356
+ return { ...base, outcome: "a-only", finalName: aName };
2357
+ }
2358
+ if (aName && bName && namesMatch(aName, bName)) {
2359
+ return { ...base, outcome: "agreed", finalName: pickCompleteName(aName, bName) };
2360
+ }
2361
+ if (intro) {
2362
+ if (aName && namesMatch(aName, intro))
2363
+ return { ...base, outcome: "tripwire", finalName: aName, note: `intro "${intro}"` };
2364
+ if (bName && namesMatch(bName, intro))
2365
+ return { ...base, outcome: "tripwire", finalName: bName, note: `intro "${intro}"` };
2366
+ if (introCorroborated) {
2367
+ return {
2368
+ ...base,
2369
+ outcome: "tripwire",
2370
+ finalName: intro,
2371
+ note: `intro "${intro}" corroborated by roster/known speakers`
2372
+ };
2373
+ }
2374
+ }
2375
+ if (aName && !bName) return { ...base, outcome: "a-only", finalName: aName };
2376
+ if (bName && !aName) return { ...base, outcome: "b-only", finalName: bName };
2377
+ const aOk = evidenceInTranscript(a.evidence, transcriptNorm);
2378
+ const bOk = evidenceInTranscript(b.evidence, transcriptNorm);
2379
+ if (aOk && !bOk)
2380
+ return {
2381
+ ...base,
2382
+ outcome: "evidence-break",
2383
+ finalName: aName,
2384
+ note: "B evidence not in transcript"
2385
+ };
2386
+ if (bOk && !aOk)
2387
+ return {
2388
+ ...base,
2389
+ outcome: "evidence-break",
2390
+ finalName: bName,
2391
+ note: "A evidence not in transcript"
2392
+ };
2393
+ return {
2394
+ ...base,
2395
+ outcome: "kept-generic",
2396
+ note: "disagreement unresolved \u2014 not inventing a name"
2397
+ };
2398
+ }
2399
+ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts) {
2400
+ const mode = opts.mode ?? "dual";
2401
+ const runPass = (r) => identifySpeakers(
2402
+ r.client,
2403
+ r.model,
2404
+ segments,
2405
+ speakers,
2406
+ opts.roster,
2407
+ opts.knownSpeakers,
2408
+ opts.nameHints,
2409
+ opts.sourceFileName
2410
+ );
2411
+ const wantB = mode === "dual" && reasonerB !== null;
2412
+ const [resA, resB] = await Promise.all([
2413
+ runPass(reasonerA),
2414
+ wantB ? runPass(reasonerB) : Promise.resolve(void 0)
2415
+ ]);
2416
+ const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
2417
+ if (passFailed(resA) && (!wantB || passFailed(resB))) {
2418
+ logger.warn(
2419
+ `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).`
2420
+ );
2421
+ }
2422
+ const transcriptNorm = norm(segments.map((s) => s.text).join(" "));
2423
+ const tripwires = findSelfIntroductions(segments);
2424
+ const introBySpeaker = /* @__PURE__ */ new Map();
2425
+ const conflicted = /* @__PURE__ */ new Set();
2426
+ for (const t of tripwires) {
2427
+ const prev = introBySpeaker.get(t.speakerId);
2428
+ if (prev && !namesMatch(prev, t.introducedName)) conflicted.add(t.speakerId);
2429
+ else introBySpeaker.set(t.speakerId, t.introducedName);
2430
+ }
2431
+ for (const id of conflicted) introBySpeaker.delete(id);
2432
+ const byIdA = new Map(resA.speakers.map((s) => [s.id, s]));
2433
+ const byIdB = resB ? new Map(resB.speakers.map((s) => [s.id, s])) : void 0;
2434
+ const decisions = [];
2435
+ const corroborationText = norm(
2436
+ `${opts.roster ?? ""} ${(opts.knownSpeakers ?? []).join(" ")}`
2437
+ );
2438
+ const isCorroborated = (name) => {
2439
+ if (!name) return false;
2440
+ const n = norm(name);
2441
+ return n.length >= 3 && corroborationText.includes(n);
2442
+ };
2443
+ const nameMap = {};
2444
+ for (const sp of speakers) {
2445
+ const a = byIdA.get(sp.id) ?? { name: resA.nameMap[sp.id] };
2446
+ const b = byIdB ? byIdB.get(sp.id) ?? { name: resB.nameMap[sp.id] } : void 0;
2447
+ const intro = introBySpeaker.get(sp.id);
2448
+ const d = adjudicate(
2449
+ sp.id,
2450
+ a ?? {},
2451
+ wantB ? b ?? {} : void 0,
2452
+ transcriptNorm,
2453
+ intro,
2454
+ isCorroborated(intro)
2455
+ );
2456
+ decisions.push(d);
2457
+ if (d.finalName) nameMap[sp.id] = d.finalName;
2458
+ }
2459
+ const STRENGTH = {
2460
+ agreed: 4,
2461
+ tripwire: 3,
2462
+ "evidence-break": 2,
2463
+ "a-only": 1,
2464
+ "b-only": 1,
2465
+ elimination: 1,
2466
+ "conflict-fallback": 0,
2467
+ "kept-generic": 0
2468
+ };
2469
+ const named = decisions.filter((d) => d.finalName);
2470
+ for (let i = 0; i < named.length; i++) {
2471
+ for (let j = i + 1; j < named.length; j++) {
2472
+ const di = named[i];
2473
+ const dj = named[j];
2474
+ if (!di.finalName || !dj.finalName) continue;
2475
+ if (!namesMatch(di.finalName, dj.finalName)) continue;
2476
+ const si = STRENGTH[di.outcome];
2477
+ const sj = STRENGTH[dj.outcome];
2478
+ const losers = si === sj ? [di, dj] : si < sj ? [di] : [dj];
2479
+ for (const loser of losers) {
2480
+ loser.note = `demoted: "${loser.finalName}" also claimed by another speaker with ${si === sj ? "equal" : "stronger"} evidence`;
2481
+ loser.finalName = void 0;
2482
+ loser.outcome = "conflict-fallback";
2483
+ delete nameMap[loser.speakerId];
2484
+ }
2485
+ }
2486
+ }
2487
+ if (opts.knownSpeakers?.length) {
2488
+ const unusedNames = opts.knownSpeakers.filter(
2489
+ (n) => !decisions.some((d) => d.finalName && namesMatch(d.finalName, n))
2490
+ );
2491
+ const unnamed = decisions.filter((d) => !d.finalName);
2492
+ if (unusedNames.length === 1 && unnamed.length === 1) {
2493
+ const d = unnamed[0];
2494
+ d.finalName = unusedNames[0];
2495
+ d.outcome = "elimination";
2496
+ d.note = `only remaining known speaker`;
2497
+ nameMap[d.speakerId] = d.finalName;
2498
+ logger.info(
2499
+ `identify: "${d.speakerId}" \u2192 ${d.finalName} (by elimination from --speakers)`
2500
+ );
2501
+ }
2502
+ }
2503
+ for (const d of decisions) {
2504
+ if (d.outcome === "conflict-fallback") {
2505
+ logger.info(`identify: "${d.speakerId}" kept generic \u2014 ${d.note}`);
2506
+ }
2507
+ if (d.outcome === "kept-generic" && (d.nameA || d.nameB)) {
2508
+ logger.info(
2509
+ `identify: kept "${d.speakerId}" generic \u2014 passes disagreed (${d.nameA ?? "\u2014"} vs ${d.nameB ?? "\u2014"})`
2510
+ );
2511
+ } else if (d.outcome === "tripwire") {
2512
+ logger.info(
2513
+ `identify: "${d.speakerId}" \u2192 ${d.finalName} (self-introduction tripwire)`
2514
+ );
2515
+ }
2516
+ }
2517
+ return {
2518
+ nameMap,
2519
+ decisions,
2520
+ tripwires,
2521
+ passA: { ...resA, model: reasonerA.model },
2522
+ passB: resB ? { ...resB, model: reasonerB.model } : void 0
2523
+ };
2524
+ }
2525
+
2526
+ // src/providers/reasoner.ts
2527
+ var PROVIDERS = {
2528
+ deepseek: { baseUrl: "https://api.deepseek.com/v1", keyName: "deepseek" },
2529
+ openai: { baseUrl: "https://api.openai.com/v1", keyName: "openai" },
2530
+ groq: { baseUrl: "https://api.groq.com/openai/v1", keyName: "groq" },
2531
+ gemini: {
2532
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
2533
+ keyName: "gemini"
2534
+ },
2535
+ zai: { baseUrl: "https://api.z.ai/api/paas/v4", keyName: "zai" },
2536
+ kimi: { baseUrl: "https://api.moonshot.ai/v1", keyName: "kimi" },
2537
+ anthropic: { baseUrl: "https://api.anthropic.com/v1", keyName: "anthropic" }
2538
+ };
2539
+ function inferProvider(model) {
2540
+ const m = model.toLowerCase();
2541
+ if (m.startsWith("deepseek")) return "deepseek";
2542
+ if (m.startsWith("gemini") || m.startsWith("gemma")) return "gemini";
2543
+ if (m.startsWith("glm")) return "zai";
2544
+ if (m.startsWith("kimi") || m.startsWith("moonshot")) return "kimi";
2545
+ if (m.startsWith("claude")) return "anthropic";
2546
+ if (m.startsWith("gpt") || m.startsWith("o1") || m.startsWith("o3") || m.startsWith("o4"))
2547
+ return "openai";
2548
+ if (m.includes("llama") || m.includes("mixtral")) return "groq";
2549
+ return "openai";
2550
+ }
2551
+ function resolveReasonerInfo(spec) {
2552
+ let provider;
2553
+ let model;
2554
+ const colon = spec.indexOf(":");
2555
+ if (colon > 0 && PROVIDERS[spec.slice(0, colon)]) {
2556
+ provider = spec.slice(0, colon);
2557
+ model = spec.slice(colon + 1);
2558
+ } else {
2559
+ model = spec;
2560
+ provider = inferProvider(spec);
2561
+ }
2562
+ const p = PROVIDERS[provider] ?? PROVIDERS.openai;
2563
+ return { provider, model, keyName: p.keyName, baseUrl: p.baseUrl };
2564
+ }
2565
+ function reasonerKey(info, keys) {
2566
+ if (info.keyName === "gemini") return keys.gemini || keys.google;
2567
+ return keys[info.keyName];
2568
+ }
2569
+ function resolveReasoner(spec, keys) {
2570
+ const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
2571
+ (s) => !!s
2572
+ );
2573
+ for (const c of candidates) {
2574
+ const info = resolveReasonerInfo(c);
2575
+ const key = reasonerKey(info, keys);
2576
+ if (key) {
2577
+ return {
2578
+ client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2579
+ info
2580
+ };
2581
+ }
2582
+ }
2583
+ return null;
2584
+ }
2585
+ function resolveSecondReasoner(first, keys) {
2586
+ const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
2587
+ for (const c of candidates) {
2588
+ const info = resolveReasonerInfo(c);
2589
+ if (info.provider === first.provider) continue;
2590
+ const key = reasonerKey(info, keys);
2591
+ if (key) {
2592
+ return {
2593
+ client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2594
+ info
2595
+ };
2596
+ }
2597
+ }
2598
+ return null;
2599
+ }
2600
+
1549
2601
  // src/finalize/finalize.ts
1550
2602
  var MIN_DUR = 0.5;
1551
2603
  var MAX_DUR = 7;
@@ -1564,6 +2616,87 @@ function timeOverlapFrac(a, b) {
1564
2616
  const shorter = Math.min(a.end - a.start, b.end - b.start);
1565
2617
  return shorter > 0 ? ov / shorter : 0;
1566
2618
  }
2619
+ var SEAM_WINDOW = 250;
2620
+ var SEAM_MIN_TOKENS = 6;
2621
+ var SEAM_MIN_SCORE_RATIO = 0.5;
2622
+ function suffixPrefixOverlap(a, b) {
2623
+ const n = a.length;
2624
+ const m = b.length;
2625
+ if (n === 0 || m === 0) return null;
2626
+ const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
2627
+ const origin = Array.from(
2628
+ { length: n + 1 },
2629
+ () => new Array(m + 1).fill(0)
2630
+ );
2631
+ for (let i = 0; i <= n; i++) {
2632
+ dp[i][0] = 0;
2633
+ origin[i][0] = i;
2634
+ }
2635
+ for (let j = 1; j <= m; j++) {
2636
+ dp[0][j] = -j;
2637
+ origin[0][j] = 0;
2638
+ }
2639
+ for (let i = 1; i <= n; i++) {
2640
+ for (let j = 1; j <= m; j++) {
2641
+ const diag = dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 1 : -1);
2642
+ const up = dp[i - 1][j] - 1;
2643
+ const left = dp[i][j - 1] - 1;
2644
+ if (diag >= up && diag >= left) {
2645
+ dp[i][j] = diag;
2646
+ origin[i][j] = origin[i - 1][j - 1];
2647
+ } else if (up >= left) {
2648
+ dp[i][j] = up;
2649
+ origin[i][j] = origin[i - 1][j];
2650
+ } else {
2651
+ dp[i][j] = left;
2652
+ origin[i][j] = origin[i][j - 1];
2653
+ }
2654
+ }
2655
+ }
2656
+ let bestJ = 0;
2657
+ let bestScore = -Infinity;
2658
+ for (let j = 1; j <= m; j++) {
2659
+ if (dp[n][j] > bestScore) {
2660
+ bestScore = dp[n][j];
2661
+ bestJ = j;
2662
+ }
2663
+ }
2664
+ if (bestJ < SEAM_MIN_TOKENS) return null;
2665
+ if (bestScore < bestJ * SEAM_MIN_SCORE_RATIO) return null;
2666
+ return { aStart: origin[n][bestJ], bLen: bestJ };
2667
+ }
2668
+ function trimSeamOverlaps(segments) {
2669
+ const sorted = [...segments].sort((a, b) => a.start - b.start);
2670
+ const lastIdxBySpeaker = /* @__PURE__ */ new Map();
2671
+ const out = [];
2672
+ for (const seg of sorted) {
2673
+ const prevIdx = lastIdxBySpeaker.get(seg.speaker);
2674
+ const prev = prevIdx !== void 0 ? out[prevIdx] : void 0;
2675
+ if (prev && prev.words?.length && seg.words?.length) {
2676
+ const prevWin = Math.min(SEAM_WINDOW, prev.words.length);
2677
+ const prevToks = prev.words.slice(-prevWin).map((w) => tokenize(w.text)[0]?.norm ?? "");
2678
+ const segToks = seg.words.slice(0, SEAM_WINDOW).map((w) => tokenize(w.text)[0]?.norm ?? "");
2679
+ const hit = suffixPrefixOverlap(prevToks, segToks);
2680
+ if (hit) {
2681
+ const trimFrom = prev.words.length - prevWin + hit.aStart;
2682
+ const kept = prev.words.slice(0, trimFrom);
2683
+ if (kept.length === 0) {
2684
+ out[prevIdx] = null;
2685
+ } else {
2686
+ out[prevIdx] = {
2687
+ ...prev,
2688
+ words: kept,
2689
+ end: kept[kept.length - 1].end,
2690
+ text: kept.map((w) => w.text).join(" ")
2691
+ };
2692
+ }
2693
+ }
2694
+ }
2695
+ out.push(seg);
2696
+ lastIdxBySpeaker.set(seg.speaker, out.length - 1);
2697
+ }
2698
+ return out.filter((s) => s !== null);
2699
+ }
1567
2700
  function dedupSegments(segments) {
1568
2701
  const sorted = [...segments].sort((a, b) => a.start - b.start);
1569
2702
  const kept = [];
@@ -1619,7 +2752,7 @@ function clampAndFix(segments) {
1619
2752
  }
1620
2753
  function finalizeSegments(segments, opts = {}) {
1621
2754
  const minSeg = opts.minSegmentSec ?? 0.2;
1622
- let deduped = dedupSegments(segments);
2755
+ let deduped = dedupSegments(trimSeamOverlaps(segments));
1623
2756
  deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
1624
2757
  const out = deduped.map((s, i) => ({
1625
2758
  id: i + 1,
@@ -1641,11 +2774,17 @@ function finalizeSegments(segments, opts = {}) {
1641
2774
  // src/finalize/format.ts
1642
2775
  var MAX_CHARS = 84;
1643
2776
  var MAX_BLOCK_SEC = 7;
1644
- function splitIntoBlocks(seg) {
1645
- const words = seg.words && seg.words.length > 0 ? seg.words : null;
1646
- if (!words) {
1647
- return [{ start: seg.start, end: seg.end, text: seg.text }];
1648
- }
2777
+ function compactTime(sec) {
2778
+ const s = Math.max(0, Math.floor(sec));
2779
+ const h = Math.floor(s / 3600);
2780
+ const m = Math.floor(s % 3600 / 60);
2781
+ const r = s % 60;
2782
+ const mm = m.toString().padStart(2, "0");
2783
+ const rr = r.toString().padStart(2, "0");
2784
+ return h > 0 ? `${h}:${mm}:${rr}` : `${mm}:${rr}`;
2785
+ }
2786
+ function splitByWords(seg) {
2787
+ const words = seg.words;
1649
2788
  const blocks = [];
1650
2789
  let curWords = [];
1651
2790
  let curLen = 0;
@@ -1672,6 +2811,36 @@ function splitIntoBlocks(seg) {
1672
2811
  curLen += addLen;
1673
2812
  }
1674
2813
  flush();
2814
+ return blocks;
2815
+ }
2816
+ function splitByChars(seg) {
2817
+ const text = seg.text.trim();
2818
+ if (text.length <= MAX_CHARS) return [{ start: seg.start, end: seg.end, text }];
2819
+ const words = text.split(/\s+/);
2820
+ const lines = [];
2821
+ let cur = "";
2822
+ for (const w of words) {
2823
+ if (cur && cur.length + 1 + w.length > MAX_CHARS) {
2824
+ lines.push(cur);
2825
+ cur = w;
2826
+ } else {
2827
+ cur = cur ? `${cur} ${w}` : w;
2828
+ }
2829
+ }
2830
+ if (cur) lines.push(cur);
2831
+ const total = lines.reduce((n, l) => n + l.length, 0) || 1;
2832
+ const dur = Math.max(0, seg.end - seg.start);
2833
+ const blocks = [];
2834
+ let t = seg.start;
2835
+ for (const line of lines) {
2836
+ const span = line.length / total * dur;
2837
+ blocks.push({ start: t, end: Math.min(seg.end, t + span), text: line });
2838
+ t += span;
2839
+ }
2840
+ return blocks;
2841
+ }
2842
+ function splitIntoBlocks(seg) {
2843
+ const blocks = seg.words && seg.words.length > 0 ? splitByWords(seg) : splitByChars(seg);
1675
2844
  return blocks.length ? blocks : [{ start: seg.start, end: seg.end, text: seg.text }];
1676
2845
  }
1677
2846
  function formatSrt(result, opts = {}) {
@@ -1682,54 +2851,247 @@ function formatSrt(result, opts = {}) {
1682
2851
  for (const seg of result.segments) {
1683
2852
  const tone = showTone && seg.tone && seg.tone.length ? ` (${seg.tone.join(", ")})` : "";
1684
2853
  const speaker = labelSpeakers ? `${seg.speakerName || seg.speaker}: ` : "";
1685
- for (const b of splitIntoBlocks(seg)) {
1686
- blocks.push(`${idx}
2854
+ const segBlocks = splitIntoBlocks(seg);
2855
+ for (let i = 0; i < segBlocks.length; i++) {
2856
+ const b = segBlocks[i];
2857
+ const t = i === 0 ? tone : "";
2858
+ blocks.push(
2859
+ `${idx}
1687
2860
  ${formatSrtTiming(b.start, b.end)}
1688
- ${speaker}${b.text}${tone}
1689
- `);
2861
+ ${speaker}${b.text}${t}
2862
+ `
2863
+ );
1690
2864
  idx++;
1691
2865
  }
1692
2866
  }
1693
2867
  return blocks.join("\n");
1694
2868
  }
1695
- function formatMarkdown(result, opts = {}) {
2869
+ function groupBySpeaker(segments) {
2870
+ const groups = [];
2871
+ for (const seg of segments) {
2872
+ const last = groups[groups.length - 1];
2873
+ const key = (s) => s.speakerName || s.speaker;
2874
+ if (last && key(last[0]) === key(seg)) last.push(seg);
2875
+ else groups.push([seg]);
2876
+ }
2877
+ return groups;
2878
+ }
2879
+ function groupText(group, showTone) {
2880
+ const parts = [];
2881
+ let lastTone = "";
2882
+ for (const s of group) {
2883
+ const toneStr = s.tone && s.tone.length ? s.tone.join(", ") : "";
2884
+ if (showTone && toneStr && toneStr !== lastTone) {
2885
+ parts.push(`*(${toneStr})* ${s.text}`);
2886
+ } else {
2887
+ parts.push(s.text);
2888
+ }
2889
+ lastTone = toneStr;
2890
+ }
2891
+ return parts.join(" ");
2892
+ }
2893
+ function mdHeader(result, opts) {
1696
2894
  const parts = [];
1697
2895
  parts.push(`# ${opts.title || "Transcript"}
1698
2896
  `);
1699
- parts.push(`*Duration: ${Math.round(result.metadata.duration)}s \xB7 Speakers: ${result.speakers.length}*
1700
- `);
2897
+ parts.push(
2898
+ `*Duration: ${formatDuration(result.metadata.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns*
2899
+ `
2900
+ );
1701
2901
  parts.push("\n## Speakers\n");
1702
2902
  for (const s of result.speakers) {
1703
- const talk = s.talkTime ? ` (${Math.round(s.talkTime)}s)` : "";
1704
- parts.push(`- **${s.name || s.id}**${talk}`);
2903
+ const talk = s.talkTime ? ` \u2014 ${formatDuration(Math.round(s.talkTime))}` : "";
2904
+ const desc = s.description ? ` \xB7 ${s.description}` : "";
2905
+ parts.push(`- **${s.name || s.id}**${talk}${desc}`);
1705
2906
  }
1706
2907
  parts.push("\n## Transcript\n");
1707
- for (const seg of result.segments) {
1708
- const mm = Math.floor(seg.start / 60).toString().padStart(2, "0");
1709
- const ss = Math.floor(seg.start % 60).toString().padStart(2, "0");
1710
- const tone = seg.tone && seg.tone.length ? ` *(${seg.tone.join(", ")})*` : "";
1711
- parts.push(`[${mm}:${ss}] **${seg.speakerName || seg.speaker}**${tone}: ${seg.text}
2908
+ return parts;
2909
+ }
2910
+ function formatMarkdown(result, opts = {}) {
2911
+ const showTone = opts.showTone ?? true;
2912
+ const timestamps = opts.timestamps ?? true;
2913
+ const style = opts.mdStyle ?? "merged";
2914
+ const parts = mdHeader(result, opts);
2915
+ const groups = style === "merged" ? groupBySpeaker(result.segments) : result.segments.map((s) => [s]);
2916
+ for (const group of groups) {
2917
+ const first = group[0];
2918
+ const ts = timestamps ? `\`[${compactTime(first.start)}]\` ` : "";
2919
+ const name = first.speakerName || first.speaker;
2920
+ parts.push(`${ts}**${name}:** ${groupText(group, showTone)}
1712
2921
  `);
1713
2922
  }
1714
2923
  return parts.join("\n");
1715
2924
  }
2925
+ function formatText(result, opts = {}) {
2926
+ const timestamps = opts.timestamps ?? true;
2927
+ const showTone = opts.showTone ?? false;
2928
+ const lines = [];
2929
+ for (const group of groupBySpeaker(result.segments)) {
2930
+ const first = group[0];
2931
+ const ts = timestamps ? `[${compactTime(first.start)}] ` : "";
2932
+ const name = first.speakerName || first.speaker;
2933
+ const text = group.map(
2934
+ (s) => showTone && s.tone?.length ? `(${s.tone.join(", ")}) ${s.text}` : s.text
2935
+ ).join(" ");
2936
+ lines.push(`${ts}${name}: ${text}`);
2937
+ }
2938
+ return lines.join("\n\n") + "\n";
2939
+ }
1716
2940
  function formatJson(result) {
1717
2941
  return JSON.stringify(result, null, 2);
1718
2942
  }
1719
2943
 
2944
+ // src/finalize/html.ts
2945
+ var PALETTE = [
2946
+ "#2563eb",
2947
+ "#059669",
2948
+ "#d97706",
2949
+ "#dc2626",
2950
+ "#7c3aed",
2951
+ "#0891b2",
2952
+ "#be185d",
2953
+ "#4d7c0f",
2954
+ "#b45309",
2955
+ "#6d28d9"
2956
+ ];
2957
+ var esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2958
+ function groupBySpeaker2(segments) {
2959
+ const groups = [];
2960
+ for (const seg of segments) {
2961
+ const last = groups[groups.length - 1];
2962
+ const key = (s) => s.speakerName || s.speaker;
2963
+ if (last && key(last[0]) === key(seg)) last.push(seg);
2964
+ else groups.push([seg]);
2965
+ }
2966
+ return groups;
2967
+ }
2968
+ function formatHtml(result, opts = {}) {
2969
+ const title = opts.title || "Transcript";
2970
+ const colorOf = /* @__PURE__ */ new Map();
2971
+ result.speakers.forEach((sp, i) => {
2972
+ colorOf.set(sp.name || sp.id, PALETTE[i % PALETTE.length]);
2973
+ });
2974
+ const color = (name) => colorOf.get(name) ?? "#64748b";
2975
+ const legend = result.speakers.map((sp) => {
2976
+ const name = sp.name || sp.id;
2977
+ const talk = sp.talkTime ? ` \xB7 ${formatDuration(Math.round(sp.talkTime))}` : "";
2978
+ return `<span class="who"><i style="background:${color(name)}"></i>${esc(name)}<small>${talk}</small></span>`;
2979
+ }).join("");
2980
+ const paragraphs = groupBySpeaker2(result.segments).map((group) => {
2981
+ const first = group[0];
2982
+ const name = first.speakerName || first.speaker;
2983
+ let lastTone = "";
2984
+ const body = group.map((s) => {
2985
+ const toneStr = s.tone?.length ? s.tone.join(", ") : "";
2986
+ const badge = toneStr && toneStr !== lastTone ? `<em class="tone">${esc(toneStr)}</em> ` : "";
2987
+ lastTone = toneStr;
2988
+ return `${badge}${esc(s.text)}`;
2989
+ }).join(" ");
2990
+ return `<div class="turn" style="border-color:${color(name)}">
2991
+ <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>
2992
+ <p>${body}</p>
2993
+ </div>`;
2994
+ }).join("\n");
2995
+ const m = result.metadata;
2996
+ const cost = m.cost ? ` \xB7 ~$${m.cost.actualUsd.toFixed(2)}` : "";
2997
+ const footer = `${esc(m.models.transcribe ?? "")} + ${esc(m.models.timestamped ?? "")}${cost} \xB7 ${new Date(m.processedAt).toLocaleDateString()}`;
2998
+ return `<!doctype html>
2999
+ <html lang="en">
3000
+ <meta charset="utf-8">
3001
+ <meta name="viewport" content="width=device-width,initial-scale=1">
3002
+ <title>${esc(title)}</title>
3003
+ <style>
3004
+ :root{--bg:#ffffff;--fg:#1e293b;--muted:#64748b;--line:#e2e8f0;--chip:#f1f5f9}
3005
+ @media(prefers-color-scheme:dark){:root{--bg:#0f172a;--fg:#e2e8f0;--muted:#94a3b8;--line:#1e293b;--chip:#1e293b}}
3006
+ *{box-sizing:border-box}
3007
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
3008
+ main{max-width:760px;margin:0 auto;padding:2rem 1.25rem 4rem}
3009
+ h1{font-size:1.5rem;margin:0 0 .25rem}
3010
+ .sub{color:var(--muted);font-size:.9rem;margin-bottom:1rem}
3011
+ 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}
3012
+ .who{display:inline-flex;align-items:center;gap:.4rem;font-size:.85rem}
3013
+ .who i{width:.65rem;height:.65rem;border-radius:50%;display:inline-block}
3014
+ .who small{color:var(--muted)}
3015
+ .turn{border-left:3px solid;padding:.15rem 0 .15rem 1rem;margin:1.1rem 0}
3016
+ .turn .meta{display:flex;align-items:baseline;gap:.6rem;font-size:.85rem}
3017
+ .turn time{color:var(--muted);font-family:ui-monospace,Menlo,monospace;font-size:.78rem;cursor:pointer}
3018
+ .turn time:hover{text-decoration:underline}
3019
+ .turn p{margin:.25rem 0 0}
3020
+ .tone{background:var(--chip);color:var(--muted);border-radius:.5rem;padding:0 .45rem;font-size:.75rem;font-style:italic;white-space:nowrap}
3021
+ footer{margin-top:3rem;color:var(--muted);font-size:.8rem;border-top:1px solid var(--line);padding-top:1rem}
3022
+ </style>
3023
+ <main>
3024
+ <h1>${esc(title)}</h1>
3025
+ <div class="sub">${formatDuration(m.duration)} \xB7 ${result.speakers.length} speakers \xB7 ${result.segments.length} turns</div>
3026
+ <header class="legend">${legend}</header>
3027
+ ${paragraphs}
3028
+ <footer>${footer}</footer>
3029
+ </main>
3030
+ <script>
3031
+ document.querySelectorAll("time").forEach(t=>t.addEventListener("click",()=>{
3032
+ navigator.clipboard&&navigator.clipboard.writeText(t.dataset.t);
3033
+ const o=t.textContent;t.textContent="copied";setTimeout(()=>t.textContent=o,700);
3034
+ }));
3035
+ </script>
3036
+ </html>
3037
+ `;
3038
+ }
3039
+
3040
+ // src/finalize/summary.ts
3041
+ function summaryPrompt(result, instructions) {
3042
+ const lines = result.segments.map((s) => {
3043
+ const name = s.speakerName || s.speaker;
3044
+ return `[${compactTime(s.start)}] ${name}: ${s.text}`;
3045
+ });
3046
+ 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):
3047
+
3048
+ ## TL;DR
3049
+ 2-4 sentences. What was this, what mattered.
3050
+
3051
+ ## Decisions
3052
+ Bullet list of decisions actually made (not topics discussed). Attribute who decided when clear.
3053
+
3054
+ ## Action items
3055
+ Bullet list, "**Owner** \u2014 action" format. Only real commitments, with the timestamp in [mm:ss].
3056
+
3057
+ ## By speaker
3058
+ One short paragraph per speaker: their main points and positions.
3059
+
3060
+ ## Open questions
3061
+ Things raised but not resolved.
3062
+
3063
+ Be specific and quote sparingly. Do not invent content.${instructions ? `
3064
+
3065
+ Additional instructions: ${instructions}` : ""}
3066
+
3067
+ TRANSCRIPT:
3068
+ ${lines.join("\n")}`;
3069
+ }
3070
+ async function summarizeTranscript(client, model, result, instructions) {
3071
+ const res = await client.chat(
3072
+ model,
3073
+ [{ role: "user", content: summaryPrompt(result, instructions) }],
3074
+ { temperature: 0.3, maxTokens: 4e3, logKind: "summary" }
3075
+ );
3076
+ if (res.error || !res.text) {
3077
+ throw new Error(`summary failed: ${res.error || "empty response"}`);
3078
+ }
3079
+ return res.text.trim() + "\n";
3080
+ }
3081
+
1720
3082
  // src/core/pipeline.ts
1721
- var import_node_path5 = require("path");
3083
+ var import_node_path6 = require("path");
1722
3084
  var JSON_OPTS = { encoding: "utf-8" };
1723
3085
  function readJson(p) {
1724
- if (!(0, import_node_fs4.existsSync)(p)) return null;
3086
+ if (!(0, import_node_fs5.existsSync)(p)) return null;
1725
3087
  try {
1726
- return JSON.parse((0, import_node_fs4.readFileSync)(p, JSON_OPTS));
3088
+ return JSON.parse((0, import_node_fs5.readFileSync)(p, JSON_OPTS));
1727
3089
  } catch {
1728
3090
  return null;
1729
3091
  }
1730
3092
  }
1731
3093
  function writeJson(p, data) {
1732
- (0, import_node_fs4.writeFileSync)(p, JSON.stringify(data, null, 2), JSON_OPTS);
3094
+ (0, import_node_fs5.writeFileSync)(p, JSON.stringify(data, null, 2), JSON_OPTS);
1733
3095
  }
1734
3096
  async function mapPool(items, limit, fn) {
1735
3097
  const results = new Array(items.length);
@@ -1747,27 +3109,41 @@ async function mapPool(items, limit, fn) {
1747
3109
  function has(passes, p) {
1748
3110
  return passes.includes(p);
1749
3111
  }
3112
+ function stageTag(name) {
3113
+ return (err) => {
3114
+ const msg = err instanceof Error ? err.message : String(err);
3115
+ if (msg.startsWith(`[${name}]`)) throw err;
3116
+ const e = new Error(`[${name}] ${msg}`);
3117
+ if (err instanceof Error && err.stack) e.stack = err.stack;
3118
+ throw e;
3119
+ };
3120
+ }
1750
3121
  async function transcribe(opts) {
1751
3122
  if (!opts || typeof opts.input !== "string" || opts.input.length === 0) {
1752
- throw new Error("transcribe(options): 'input' (path to the audio/video file) is required");
1753
- }
1754
- if (typeof opts.outputDir !== "string" || opts.outputDir.length === 0) {
1755
- throw new Error("transcribe(options): 'outputDir' (directory for outputs) is required");
3123
+ throw new Error(
3124
+ "transcribe(options): 'input' (path to the audio/video file) is required"
3125
+ );
1756
3126
  }
1757
3127
  const options = resolveOptions(opts);
1758
3128
  const keys = resolveKeys(options.apiKeys);
1759
3129
  logger.setLevel(options.logLevel);
1760
- if (!(0, import_node_fs4.existsSync)(options.input)) {
3130
+ if (!(0, import_node_fs5.existsSync)(options.input)) {
1761
3131
  throw new Error(`Input file not found: ${options.input}`);
1762
3132
  }
1763
- (0, import_node_fs4.mkdirSync)(options.intermediatesDir, { recursive: true });
1764
- (0, import_node_fs4.mkdirSync)(options.outputDir, { recursive: true });
1765
- logger.info(`intermediates: ${(0, import_node_path5.resolve)(options.intermediatesDir)} (file://${(0, import_node_path5.resolve)(options.intermediatesDir)})`);
3133
+ (0, import_node_fs5.mkdirSync)(options.intermediatesDir, { recursive: true });
3134
+ (0, import_node_fs5.mkdirSync)(options.outputDir, { recursive: true });
3135
+ logger.info(
3136
+ `intermediates: ${(0, import_node_path6.resolve)(options.intermediatesDir)} (file://${(0, import_node_path6.resolve)(options.intermediatesDir)})`
3137
+ );
1766
3138
  setLlmLogPath(options.llmLog ? `${options.intermediatesDir}/llm-calls.jsonl` : null);
3139
+ resetLlmUsage();
3140
+ const runStartedAt = Date.now();
1767
3141
  const sourcePath = `${options.intermediatesDir}/source.json`;
1768
3142
  const sig = inputSignature(options.input);
1769
3143
  const cfgSig = configSignature(opts);
1770
- const prevSig = readJson(sourcePath);
3144
+ const prevSig = readJson(
3145
+ sourcePath
3146
+ );
1771
3147
  const inputChanged = !prevSig || prevSig.signature !== sig;
1772
3148
  const configChanged = !prevSig || prevSig.config !== cfgSig;
1773
3149
  if (inputChanged && prevSig) {
@@ -1791,6 +3167,9 @@ async function transcribe(opts) {
1791
3167
  transcribe: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
1792
3168
  reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL
1793
3169
  };
3170
+ const checkAbort = () => {
3171
+ options.signal?.throwIfAborted();
3172
+ };
1794
3173
  if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
1795
3174
  if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
1796
3175
  const tsProvider = options.timestampedProvider ?? "assemblyai";
@@ -1798,33 +3177,45 @@ async function transcribe(opts) {
1798
3177
  if (willTimestamp) {
1799
3178
  if (tsProvider === "assemblyai" && !keys.assemblyai) {
1800
3179
  throw new Error(
1801
- "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
3180
+ "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
1802
3181
  );
1803
3182
  }
1804
3183
  if (tsProvider === "whisper-groq" && !keys.groq) {
1805
3184
  throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
1806
3185
  }
3186
+ if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
3187
+ throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3188
+ }
1807
3189
  }
1808
3190
  let probeInfo = null;
1809
3191
  const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
1810
3192
  const audioPath = `${options.intermediatesDir}/audio.mp3`;
1811
3193
  const probePath = `${options.intermediatesDir}/probe.json`;
1812
3194
  if (has(passes, "preprocess")) {
3195
+ checkAbort();
1813
3196
  logger.info("=== preprocess ===");
1814
3197
  probeInfo = forceAll ? null : readJson(probePath);
1815
3198
  if (!probeInfo) {
1816
- probeInfo = await probe(options.input);
3199
+ probeInfo = await probe(options.input).catch(stageTag("preprocess"));
1817
3200
  writeJson(probePath, probeInfo);
1818
3201
  }
1819
- if (!(0, import_node_fs4.existsSync)(audioPath) || forceAll) {
3202
+ if (!(0, import_node_fs5.existsSync)(audioPath) || forceAll) {
1820
3203
  logger.info("extracting audio (mono 16kHz mp3)...");
1821
- await extractAudio(options.input, audioPath, AUDIO_OPTS);
3204
+ await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
3205
+ stageTag("preprocess")
3206
+ );
1822
3207
  }
1823
3208
  if (probeInfo.hasVideo) {
1824
3209
  const kfDir = `${options.intermediatesDir}/keyframes`;
1825
- if (!(0, import_node_fs4.existsSync)(kfDir) || forceAll) {
3210
+ if (!(0, import_node_fs5.existsSync)(kfDir) || forceAll) {
1826
3211
  logger.info("extracting keyframes...");
1827
- await extractKeyframes(options.input, kfDir, options.screenshotCount);
3212
+ await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
3213
+ (err) => {
3214
+ logger.warn(
3215
+ `keyframe extraction failed (continuing audio-only): ${err instanceof Error ? err.message : err}`
3216
+ );
3217
+ }
3218
+ );
1828
3219
  }
1829
3220
  }
1830
3221
  } else {
@@ -1832,26 +3223,56 @@ async function transcribe(opts) {
1832
3223
  }
1833
3224
  if (!probeInfo) throw new Error("probe info missing (run preprocess)");
1834
3225
  const duration = probeInfo.duration;
3226
+ const estimate = estimateRunCost({
3227
+ durationSec: duration,
3228
+ model: models.transcribe,
3229
+ reasoner: models.reasoner,
3230
+ tsProvider,
3231
+ chunkSec: options.chunkDurationSec,
3232
+ overlapSec: options.chunkOverlapSec,
3233
+ identify: options.diarizationLevel >= 3 && has(passes, "identify")
3234
+ });
3235
+ logger.info(
3236
+ `estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
3237
+ );
1835
3238
  let description = null;
1836
3239
  if (has(passes, "describe")) {
1837
3240
  const descPath = `${options.intermediatesDir}/description.json`;
1838
3241
  description = forceAll ? null : readJson(descPath);
1839
3242
  if (!description) {
3243
+ checkAbort();
1840
3244
  logger.info("=== describe ===");
1841
3245
  const client = new GeminiClient(keys.gemini);
1842
- const samplePath = `${options.intermediatesDir}/sample.mp3`;
1843
- if (!(0, import_node_fs4.existsSync)(samplePath) || forceAll) {
1844
- await extractChunk(audioPath, samplePath, 0, Math.min(300, duration), AUDIO_OPTS);
3246
+ const sampleSpans = duration <= 360 ? [[0, duration]] : [
3247
+ [0, 150],
3248
+ [Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
3249
+ [Math.max(0, duration - 120), duration]
3250
+ ];
3251
+ const files = [];
3252
+ for (let i = 0; i < sampleSpans.length; i++) {
3253
+ const [s, e] = sampleSpans[i];
3254
+ const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
3255
+ if (!(0, import_node_fs5.existsSync)(samplePath) || forceAll) {
3256
+ await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
3257
+ }
3258
+ files.push({ path: samplePath });
1845
3259
  }
1846
- const files = [{ path: samplePath }];
3260
+ const audioSampleCount = files.length;
1847
3261
  const kfDir = `${options.intermediatesDir}/keyframes`;
1848
- if ((0, import_node_fs4.existsSync)(kfDir)) {
3262
+ if ((0, import_node_fs5.existsSync)(kfDir)) {
1849
3263
  for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
1850
3264
  const p = `${kfDir}/${f}`;
1851
- if ((0, import_node_fs4.existsSync)(p)) files.push({ path: p });
3265
+ if ((0, import_node_fs5.existsSync)(p)) files.push({ path: p });
1852
3266
  }
1853
3267
  }
1854
- description = await describeMeeting(client, models.transcribe, files, (0, import_node_path5.basename)(options.input), options.instructions);
3268
+ description = await describeMeeting(
3269
+ client,
3270
+ models.transcribe,
3271
+ files,
3272
+ (0, import_node_path6.basename)(options.input),
3273
+ options.instructions,
3274
+ audioSampleCount
3275
+ ).catch(stageTag("describe"));
1855
3276
  writeJson(descPath, description);
1856
3277
  logger.info(`description: ${description.description.slice(0, 120)}...`);
1857
3278
  }
@@ -1864,39 +3285,74 @@ async function transcribe(opts) {
1864
3285
  let silences = [];
1865
3286
  try {
1866
3287
  silences = await detectSilence(audioPath, { noiseDb: -15, minDuration: 0.3 });
1867
- if (silences.length < 3) silences = await detectSilence(audioPath, { noiseDb: -12, minDuration: 0.25 });
3288
+ if (silences.length < 3)
3289
+ silences = await detectSilence(audioPath, { noiseDb: -12, minDuration: 0.25 });
1868
3290
  } catch {
1869
3291
  }
1870
3292
  chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
1871
3293
  if (silences.length > 3) {
1872
3294
  chunks = chunks.map((c) => {
1873
- const snapped = snapToSilence(c.start, silences, Math.min(10, options.chunkOverlapSec / 2));
3295
+ const snapped = snapToSilence(
3296
+ c.start,
3297
+ silences,
3298
+ Math.min(10, options.chunkOverlapSec / 2)
3299
+ );
1874
3300
  return { ...c, start: snapped, trustedStart: snapped + c.overlapWithPrevious };
1875
3301
  });
1876
3302
  }
1877
3303
  }
1878
3304
  const tagWith = (r, chunk) => ({
1879
3305
  ...r,
1880
- segments: r.segments.map((s) => ({ ...s, chunkIndex: chunk.index, trustedStart: chunk.trustedStart }))
3306
+ segments: r.segments.map((s) => ({
3307
+ ...s,
3308
+ chunkIndex: chunk.index,
3309
+ trustedStart: chunk.trustedStart
3310
+ }))
1881
3311
  });
1882
3312
  let llmChunkResults = [];
1883
3313
  if (has(passes, "llm-transcribe")) {
1884
3314
  logger.info("=== llm-transcribe ===");
1885
3315
  let runChunks = chunks;
1886
- if (options.onlyChunk !== void 0) runChunks = chunks.filter((c) => c.index === options.onlyChunk);
1887
- logger.info(`${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`);
3316
+ if (options.onlyChunk !== void 0)
3317
+ runChunks = chunks.filter((c) => c.index === options.onlyChunk);
3318
+ logger.info(
3319
+ `${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`
3320
+ );
1888
3321
  const client = new GeminiClient(keys.gemini);
1889
3322
  const llmDir = `${options.intermediatesDir}/llm`;
1890
- (0, import_node_fs4.mkdirSync)(llmDir, { recursive: true });
3323
+ (0, import_node_fs5.mkdirSync)(llmDir, { recursive: true });
3324
+ const partialPath = `${options.outputDir}/${(0, import_node_path6.basename)(options.input, ext(options.input))}.partial.md`;
3325
+ const completed = [];
3326
+ const writePartial = () => {
3327
+ try {
3328
+ const segs = completed.flatMap((r) => r.segments).sort((a, b) => a.startSec - b.startSec);
3329
+ if (segs.length === 0) return;
3330
+ const lines = segs.map((s) => {
3331
+ const mm = Math.floor(s.startSec / 60).toString().padStart(2, "0");
3332
+ const ss = Math.floor(s.startSec % 60).toString().padStart(2, "0");
3333
+ return `[${mm}:${ss}] **${s.speaker}**: ${s.text}`;
3334
+ });
3335
+ (0, import_node_fs5.writeFileSync)(
3336
+ partialPath,
3337
+ `> Partial transcript (run in progress \u2014 coarse LLM timings, speakers not yet unified)
3338
+
3339
+ ${lines.join("\n\n")}
3340
+ `
3341
+ );
3342
+ } catch {
3343
+ }
3344
+ };
1891
3345
  llmChunkResults = await mapPool(runChunks, options.concurrency, async (chunk) => {
3346
+ checkAbort();
1892
3347
  const parsedPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_parsed.json`;
1893
3348
  const cached = forceAll ? null : readJson(parsedPath);
1894
3349
  if (cached && cached.segments.length > 0) {
1895
3350
  logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
3351
+ completed.push(cached);
1896
3352
  return tagWith(cached, chunk);
1897
3353
  }
1898
3354
  const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
1899
- if (!(0, import_node_fs4.existsSync)(chunkPath) || forceAll) {
3355
+ if (!(0, import_node_fs5.existsSync)(chunkPath) || forceAll) {
1900
3356
  await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
1901
3357
  }
1902
3358
  let previousTail;
@@ -1908,7 +3364,9 @@ async function transcribe(opts) {
1908
3364
  previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
1909
3365
  }
1910
3366
  }
1911
- logger.info(`chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`);
3367
+ logger.info(
3368
+ `chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`
3369
+ );
1912
3370
  const result2 = await transcribeChunk(
1913
3371
  client,
1914
3372
  models.transcribe,
@@ -1925,7 +3383,12 @@ async function transcribe(opts) {
1925
3383
  { chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
1926
3384
  );
1927
3385
  writeJson(parsedPath, result2);
1928
- (0, import_node_fs4.writeFileSync)(`${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`, result2.raw);
3386
+ (0, import_node_fs5.writeFileSync)(
3387
+ `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
3388
+ result2.raw
3389
+ );
3390
+ completed.push(result2);
3391
+ writePartial();
1929
3392
  return tagWith(result2, chunk);
1930
3393
  });
1931
3394
  const errored = llmChunkResults.filter((r) => r.error);
@@ -1937,7 +3400,7 @@ async function transcribe(opts) {
1937
3400
  }
1938
3401
  } else {
1939
3402
  const llmDir = `${options.intermediatesDir}/llm`;
1940
- if (!forceAll && (0, import_node_fs4.existsSync)(llmDir)) {
3403
+ if (!forceAll && (0, import_node_fs5.existsSync)(llmDir)) {
1941
3404
  const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
1942
3405
  llmChunkResults = files.map((f, i) => {
1943
3406
  const r = readJson(`${llmDir}/${f}`);
@@ -1956,23 +3419,49 @@ async function transcribe(opts) {
1956
3419
  logger.info(`total LLM segments: ${allLlmSegments.length}`);
1957
3420
  let asrResult = null;
1958
3421
  if (has(passes, "timestamped") || has(passes, "align")) {
3422
+ checkAbort();
1959
3423
  const provider = options.timestampedProvider ?? "assemblyai";
1960
3424
  if (provider === "whisper-groq") {
1961
3425
  logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
1962
3426
  if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
1963
- if (!(0, import_node_fs4.existsSync)(audioPath) || forceAll) {
3427
+ if (!(0, import_node_fs5.existsSync)(audioPath) || forceAll) {
1964
3428
  await extractAudio(options.input, audioPath, AUDIO_OPTS);
1965
3429
  }
1966
3430
  const { readFile: readFile2 } = await import("fs/promises");
1967
3431
  const buf = await readFile2(audioPath);
1968
3432
  const groq = new WhisperGroqClient(keys.groq);
1969
- asrResult = await groq.transcribe(buf);
3433
+ asrResult = await groq.transcribe(buf).catch(stageTag("asr"));
3434
+ writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3435
+ } else if (provider === "elevenlabs") {
3436
+ logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
3437
+ if (!keys.elevenlabs)
3438
+ throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3439
+ const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs.json`;
3440
+ asrResult = forceAll ? null : readJson(cachePath);
3441
+ if (!asrResult) {
3442
+ const { readFile: readFile2 } = await import("fs/promises");
3443
+ const buf = await readFile2(audioPath);
3444
+ const el = new ElevenLabsClient(keys.elevenlabs);
3445
+ asrResult = await el.transcribe(buf).catch(stageTag("asr"));
3446
+ writeJson(cachePath, asrResult);
3447
+ } else {
3448
+ logger.info("[elevenlabs] cache hit");
3449
+ }
1970
3450
  writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3451
+ logger.info(
3452
+ `[elevenlabs] ${asrResult.utterances.length} utterances, ${asrResult.words.length} words, ${asrResult.speakers?.length ?? "?"} speakers`
3453
+ );
1971
3454
  } else {
1972
3455
  logger.info("=== timestamped (AssemblyAI) ===");
1973
- if (!keys.assemblyai) throw new Error("ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)");
1974
- const aai = new AssemblyAIProvider({ apiKey: keys.assemblyai, cacheDir: `${options.intermediatesDir}/assemblyai` });
1975
- asrResult = await aai.transcribe(audioPath);
3456
+ if (!keys.assemblyai)
3457
+ throw new Error(
3458
+ "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
3459
+ );
3460
+ const aai = new AssemblyAIProvider({
3461
+ apiKey: keys.assemblyai,
3462
+ cacheDir: `${options.intermediatesDir}/assemblyai`
3463
+ });
3464
+ asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
1976
3465
  writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
1977
3466
  }
1978
3467
  } else {
@@ -1994,6 +3483,9 @@ async function transcribe(opts) {
1994
3483
  const added = aligned.length - before;
1995
3484
  if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
1996
3485
  }
3486
+ if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
3487
+ aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
3488
+ }
1997
3489
  let segments = aligned;
1998
3490
  let speakers = [];
1999
3491
  if (has(passes, "consistency") && asrResult) {
@@ -2013,25 +3505,75 @@ async function transcribe(opts) {
2013
3505
  speakers = c.speakers;
2014
3506
  }
2015
3507
  }
2016
- if (options.diarizationLevel >= 3 && has(passes, "identify") && keys.deepseek && description) {
2017
- logger.info("=== identify (DeepSeek) ===");
2018
- const dsClient = OpenAICompatClient.fromProvider("deepseek", keys.deepseek, models.reasoner);
2019
- const id = await identifySpeakers(
2020
- dsClient,
2021
- models.reasoner,
2022
- segments.map((s) => ({ speaker: s.speaker, text: s.text })),
2023
- speakers,
2024
- description.roster,
2025
- options.knownSpeakers
2026
- );
2027
- logger.info(`identified ${Object.keys(id.nameMap).length} speakers: ${JSON.stringify(id.nameMap)}`);
2028
- writeJson(`${options.intermediatesDir}/identified.json`, id);
2029
- segments = segments.map(
2030
- (s) => id.nameMap[s.speaker] ? { ...s, speakerName: id.nameMap[s.speaker] } : s
2031
- );
2032
- speakers = speakers.map(
2033
- (sp) => id.nameMap[sp.id] ? { ...sp, name: id.nameMap[sp.id] } : sp
2034
- );
3508
+ const nameHints = {};
3509
+ for (const sp of speakers) {
3510
+ if (sp.name && sp.name !== sp.id) nameHints[sp.id] = sp.name;
3511
+ }
3512
+ segments = segments.map(
3513
+ (s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
3514
+ );
3515
+ speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
3516
+ if (options.diarizationLevel >= 3 && has(passes, "identify")) {
3517
+ const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
3518
+ if (!reasonerA) {
3519
+ logger.warn(
3520
+ "identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
3521
+ );
3522
+ } else {
3523
+ const mode = options.identifyMode;
3524
+ const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
3525
+ const idConfig = {
3526
+ mode,
3527
+ reasonerA: reasonerA.info.model,
3528
+ reasonerB: reasonerB?.info.model ?? null
3529
+ };
3530
+ const idCachePath = `${options.intermediatesDir}/identified.json`;
3531
+ const cachedId = forceAll ? null : readJson(
3532
+ idCachePath
3533
+ );
3534
+ const idConfigMatches = cachedId?.config && JSON.stringify(cachedId.config) === JSON.stringify(idConfig);
3535
+ let nameMap = null;
3536
+ if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
3537
+ logger.info("=== identify (cached) ===");
3538
+ nameMap = cachedId.nameMap;
3539
+ } else {
3540
+ logger.info(
3541
+ `=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
3542
+ );
3543
+ checkAbort();
3544
+ const id = await identifySpeakersV2(
3545
+ {
3546
+ client: reasonerA.client,
3547
+ model: reasonerA.info.model,
3548
+ provider: reasonerA.info.provider
3549
+ },
3550
+ reasonerB ? {
3551
+ client: reasonerB.client,
3552
+ model: reasonerB.info.model,
3553
+ provider: reasonerB.info.provider
3554
+ } : null,
3555
+ segments.map((s) => ({ speaker: s.speaker, text: s.text })),
3556
+ speakers,
3557
+ {
3558
+ roster: description?.roster ?? "(no roster available \u2014 infer from the transcript alone)",
3559
+ knownSpeakers: options.knownSpeakers,
3560
+ mode,
3561
+ nameHints,
3562
+ sourceFileName: (0, import_node_path6.basename)(options.input)
3563
+ }
3564
+ ).catch(stageTag("identify"));
3565
+ writeJson(idCachePath, { ...id, config: idConfig });
3566
+ nameMap = id.nameMap;
3567
+ }
3568
+ logger.info(
3569
+ `identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
3570
+ );
3571
+ const nm = nameMap;
3572
+ segments = segments.map(
3573
+ (s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
3574
+ );
3575
+ speakers = speakers.map((sp) => nm[sp.id] ? { ...sp, name: nm[sp.id] } : sp);
3576
+ }
2035
3577
  }
2036
3578
  let finalSegments = [];
2037
3579
  if (has(passes, "finalize")) {
@@ -2042,24 +3584,106 @@ async function transcribe(opts) {
2042
3584
  finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
2043
3585
  }
2044
3586
  logger.info(`final segments: ${finalSegments.length}`);
3587
+ const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
3588
+ const wallMs = Date.now() - runStartedAt;
2045
3589
  const metadata = {
2046
3590
  sourceFile: options.input,
2047
3591
  duration,
2048
3592
  processedAt: (/* @__PURE__ */ new Date()).toISOString(),
2049
3593
  models: {
2050
3594
  transcribe: models.transcribe,
2051
- timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
3595
+ timestamped: tsProvider === "whisper-groq" ? "whisper-large-v3 (groq)" : tsProvider === "elevenlabs" ? "scribe-v2 (elevenlabs)" : tsProvider === "none" ? "none" : "assemblyai-universal-2"
2052
3596
  },
2053
- passes
3597
+ passes,
3598
+ wallMs,
3599
+ cost: {
3600
+ estimatedUsd: estimate.totalUsd,
3601
+ actualUsd: receipt.totalUsd,
3602
+ pricesAsOf: PRICES_AS_OF,
3603
+ lines: receipt.lines,
3604
+ llmCalls: receipt.totals.calls,
3605
+ inputTokens: receipt.totals.inputTokens,
3606
+ outputTokens: receipt.totals.outputTokens
3607
+ }
2054
3608
  };
2055
3609
  const result = { segments: finalSegments, speakers, metadata };
3610
+ writeJson(`${options.intermediatesDir}/result.json`, result);
2056
3611
  for (const fmt of options.formats) {
2057
- const base = (0, import_node_path5.basename)(options.input, ext(options.input));
2058
- if (fmt === "srt") (0, import_node_fs4.writeFileSync)(`${options.outputDir}/${base}.srt`, formatSrt(result, { title: base }));
2059
- if (fmt === "md") (0, import_node_fs4.writeFileSync)(`${options.outputDir}/${base}.md`, formatMarkdown(result, { title: base }));
2060
- if (fmt === "json") (0, import_node_fs4.writeFileSync)(`${options.outputDir}/${base}.json`, formatJson(result));
3612
+ const base = (0, import_node_path6.basename)(options.input, ext(options.input));
3613
+ if (fmt === "srt")
3614
+ (0, import_node_fs5.writeFileSync)(
3615
+ `${options.outputDir}/${base}.srt`,
3616
+ formatSrt(result, { title: base })
3617
+ );
3618
+ if (fmt === "md")
3619
+ (0, import_node_fs5.writeFileSync)(
3620
+ `${options.outputDir}/${base}.md`,
3621
+ formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
3622
+ );
3623
+ if (fmt === "txt")
3624
+ (0, import_node_fs5.writeFileSync)(
3625
+ `${options.outputDir}/${base}.txt`,
3626
+ formatText(result, { title: base })
3627
+ );
3628
+ if (fmt === "html")
3629
+ (0, import_node_fs5.writeFileSync)(
3630
+ `${options.outputDir}/${base}.html`,
3631
+ formatHtml(result, { title: base })
3632
+ );
3633
+ if (fmt === "json")
3634
+ (0, import_node_fs5.writeFileSync)(`${options.outputDir}/${base}.json`, formatJson(result));
3635
+ }
3636
+ if (options.summary && finalSegments.length > 0) {
3637
+ const reasoner = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
3638
+ if (!reasoner) {
3639
+ logger.warn("summary: no reasoner-capable key \u2014 skipping");
3640
+ } else {
3641
+ logger.info(`=== summary (${reasoner.info.model}) ===`);
3642
+ try {
3643
+ const summary = await summarizeTranscript(
3644
+ reasoner.client,
3645
+ reasoner.info.model,
3646
+ result,
3647
+ options.instructions
3648
+ );
3649
+ const base = (0, import_node_path6.basename)(options.input, ext(options.input));
3650
+ (0, import_node_fs5.writeFileSync)(`${options.outputDir}/${base}.summary.md`, summary);
3651
+ logger.info(`summary written to ${base}.summary.md`);
3652
+ } catch (err) {
3653
+ logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
3654
+ }
3655
+ }
3656
+ }
3657
+ try {
3658
+ const base = (0, import_node_path6.basename)(options.input, ext(options.input));
3659
+ const partial = `${options.outputDir}/${base}.partial.md`;
3660
+ if ((0, import_node_fs5.existsSync)(partial)) (await import("fs/promises")).unlink(partial);
3661
+ } catch {
2061
3662
  }
2062
3663
  logger.info(`outputs written to ${options.outputDir}`);
3664
+ const mins = Math.floor(wallMs / 6e4);
3665
+ const secs = Math.round(wallMs % 6e4 / 1e3);
3666
+ logger.info(
3667
+ `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`
3668
+ );
3669
+ for (const line of receipt.lines) logger.info(` ${line}`);
3670
+ recordRun(
3671
+ {
3672
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
3673
+ input: (0, import_node_path6.basename)(options.input),
3674
+ durationSec: duration,
3675
+ wallMs,
3676
+ models: metadata.models,
3677
+ segments: finalSegments.length,
3678
+ characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
3679
+ speakers: speakers.length,
3680
+ llmCalls: receipt.totals.calls,
3681
+ inputTokens: receipt.totals.inputTokens,
3682
+ outputTokens: receipt.totals.outputTokens,
3683
+ costUsd: receipt.totalUsd
3684
+ },
3685
+ receipt.perModel
3686
+ );
2063
3687
  return result;
2064
3688
  }
2065
3689
  function ext(p) {
@@ -2101,12 +3725,15 @@ function parseSrt(content) {
2101
3725
  alignSegments,
2102
3726
  assignGlobalSpeakers,
2103
3727
  finalizeSegments,
3728
+ formatHtml,
2104
3729
  formatJson,
2105
3730
  formatMarkdown,
2106
3731
  formatSrt,
3732
+ formatText,
2107
3733
  identifySpeakers,
2108
3734
  parseSrt,
2109
3735
  planChunks,
3736
+ summarizeTranscript,
2110
3737
  transcribe
2111
3738
  });
2112
3739
  //# sourceMappingURL=index.cjs.map