offmute-v2 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,11 @@
1
1
  // src/core/pipeline.ts
2
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
2
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
3
+ import { readFile as readFile2 } from "fs/promises";
4
+
5
+ // src/core/models.ts
6
+ var DEFAULT_TRANSCRIBE_MODEL = "gemini-4-hydrogen";
7
+ var PRO_TRANSCRIBE_MODEL = "gemini-4-argon";
8
+ var DEFAULT_REASONER_MODEL = "deepseek-chat";
3
9
 
4
10
  // src/core/config.ts
5
11
  import { createHash } from "crypto";
@@ -15,19 +21,6 @@ var DEFAULT_PASSES = [
15
21
  "consistency",
16
22
  "finalize"
17
23
  ];
18
- var MODELS = {
19
- gemini25Pro: "gemini-2.5-pro",
20
- gemini25Flash: "gemini-2.5-flash",
21
- gemini3Pro: "gemini-3-pro-preview",
22
- gemini31Pro: "gemini-3.1-pro-preview",
23
- geminiFlashLatest: "gemini-flash-latest",
24
- deepseek: "deepseek-chat",
25
- deepseekReasoner: "deepseek-reasoner",
26
- gpt4o: "gpt-4o",
27
- claudeSonnet: "claude-sonnet-4-5"
28
- };
29
- var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini31Pro;
30
- var DEFAULT_REASONER_MODEL = MODELS.deepseek;
31
24
  function resolveKeys(injected) {
32
25
  const env = process.env;
33
26
  return {
@@ -79,12 +72,15 @@ function resolveOptions(opts) {
79
72
  model: opts.model,
80
73
  reasoner: opts.reasoner,
81
74
  timestampedProvider: opts.timestampedProvider,
75
+ language: opts.language,
82
76
  force: opts.force ?? false,
83
77
  onlyChunk: opts.onlyChunk,
84
78
  showProgress: opts.showProgress ?? true,
85
79
  llmLog: opts.llmLog ?? true,
86
80
  logLevel: opts.logLevel ?? "info",
87
- signal: opts.signal
81
+ signal: opts.signal,
82
+ onProgress: opts.onProgress,
83
+ zeroStorage: opts.zeroStorage ?? true
88
84
  };
89
85
  }
90
86
  function deriveIntermediatesDir(input) {
@@ -111,9 +107,7 @@ function inputSignature(input) {
111
107
  function configSignature(o) {
112
108
  const relevant = {
113
109
  model: o.model ?? DEFAULT_TRANSCRIBE_MODEL,
114
- reasoner: o.reasoner ?? DEFAULT_REASONER_MODEL,
115
110
  instructions: o.instructions ?? "",
116
- knownSpeakers: o.knownSpeakers ?? [],
117
111
  chunkDurationSec: o.chunkDurationSec ?? 600,
118
112
  chunkOverlapSec: o.chunkOverlapSec ?? 60,
119
113
  screenshotCount: o.screenshotCount ?? 6,
@@ -149,6 +143,15 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
149
143
  return chunks;
150
144
  }
151
145
 
146
+ // src/core/progress.ts
147
+ function emitTo(listener, event) {
148
+ if (!listener) return;
149
+ try {
150
+ listener(event);
151
+ } catch {
152
+ }
153
+ }
154
+
152
155
  // src/utils/logger.ts
153
156
  var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
154
157
  var currentLevel = "info";
@@ -382,7 +385,9 @@ function snapToSilence(boundary, silences, tolerance) {
382
385
  }
383
386
 
384
387
  // src/providers/gemini.ts
385
- import { GoogleGenAI } from "@google/genai";
388
+ import {
389
+ GoogleGenAI
390
+ } from "@google/genai";
386
391
  import { basename as basename2 } from "path";
387
392
 
388
393
  // src/providers/llm-log.ts
@@ -450,6 +455,38 @@ async function withRetry(label, fn, opts = {}) {
450
455
  throw lastErr;
451
456
  }
452
457
 
458
+ // src/providers/gemini-usage.ts
459
+ function usageFromMetadata(meta) {
460
+ const thoughtTokens = meta?.thoughtsTokenCount ?? 0;
461
+ return {
462
+ inputTokens: meta?.promptTokenCount ?? 0,
463
+ outputTokens: (meta?.candidatesTokenCount ?? 0) + thoughtTokens,
464
+ thoughtTokens,
465
+ totalTokens: meta?.totalTokenCount ?? 0
466
+ };
467
+ }
468
+
469
+ // src/providers/gemini-models.ts
470
+ function resolveThinking(model) {
471
+ const m = model.toLowerCase();
472
+ if (m.includes("gemini-2.0")) return void 0;
473
+ if (m.includes("gemini-4")) return { thinkingLevel: "LOW" };
474
+ if (m.includes("gemini-2.5")) {
475
+ return { thinkingBudget: m.includes("pro") ? 128 : 0 };
476
+ }
477
+ if (m.includes("-latest")) return { thinkingLevel: "LOW" };
478
+ if (m.includes("gemini-3"))
479
+ return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
480
+ return void 0;
481
+ }
482
+ function fallbackThinking(rejected) {
483
+ return rejected.thinkingLevel === "MINIMAL" ? { thinkingLevel: "LOW" } : void 0;
484
+ }
485
+ function isThinkingConfigError(message) {
486
+ if (!message) return false;
487
+ return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
488
+ }
489
+
453
490
  // src/providers/gemini.ts
454
491
  var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
455
492
  var originalWarn = console.warn.bind(console);
@@ -478,25 +515,15 @@ function detectMime(path) {
478
515
  return MIME_BY_EXT[ext2] ?? "application/octet-stream";
479
516
  }
480
517
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
481
- function resolveThinking(model) {
482
- const m = model.toLowerCase();
483
- if (m.includes("gemini-2.0")) return void 0;
484
- if (m.includes("gemini-2.5")) {
485
- return { thinkingBudget: m.includes("pro") ? 128 : 0 };
486
- }
487
- if (m.includes("gemini-3") || m.includes("flash-latest") || m.includes("pro-latest")) {
488
- return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
489
- }
490
- return void 0;
491
- }
492
- function isThinkingConfigError(message) {
493
- if (!message) return false;
494
- return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
495
- }
496
518
  var GeminiClient = class {
497
519
  ai;
498
- constructor(apiKey) {
499
- this.ai = new GoogleGenAI({ apiKey });
520
+ zeroStorage;
521
+ constructor(apiKey, opts = {}) {
522
+ this.ai = new GoogleGenAI({
523
+ apiKey,
524
+ ...opts.baseUrl ? { httpOptions: { baseUrl: opts.baseUrl } } : {}
525
+ });
526
+ this.zeroStorage = opts.zeroStorage ?? true;
500
527
  }
501
528
  /** Upload a file and wait until it's done processing. Uploads ride one long HTTP
502
529
  * request each — the retry loop in generate() doesn't cover them, and transient
@@ -539,12 +566,15 @@ var GeminiClient = class {
539
566
  maxOutputTokens,
540
567
  temperature
541
568
  };
569
+ if (this.zeroStorage) config.store = false;
542
570
  if (responseSchema) {
543
571
  config.responseMimeType = "application/json";
544
572
  config.responseSchema = responseSchema;
573
+ } else if (opts.responseJson) {
574
+ config.responseMimeType = "application/json";
545
575
  }
546
576
  if (systemInstruction) config.systemInstruction = systemInstruction;
547
- const thinking = resolveThinking(model);
577
+ let thinking = resolveThinking(model);
548
578
  if (thinking) config.thinkingConfig = thinking;
549
579
  const parts = uploaded.map((f) => ({
550
580
  fileData: { fileUri: f.uri, mimeType: f.mimeType }
@@ -554,21 +584,31 @@ var GeminiClient = class {
554
584
  for (let attempt = 0; attempt < maxRetries; attempt++) {
555
585
  const t0 = Date.now();
556
586
  try {
557
- const response = await this.ai.models.generateContent({
587
+ const controller = new AbortController();
588
+ const stream = await this.ai.models.generateContentStream({
558
589
  model,
559
590
  contents: [{ role: "user", parts }],
560
- config
591
+ config: { ...config, abortSignal: controller.signal }
561
592
  });
562
- const usage = response.usageMetadata || {};
563
- const text = response.text ?? "";
564
- const result = {
565
- text,
566
- usage: {
567
- inputTokens: usage.promptTokenCount ?? 0,
568
- outputTokens: usage.candidatesTokenCount ?? 0,
569
- totalTokens: usage.totalTokenCount ?? 0
593
+ let text = "";
594
+ let usageMeta;
595
+ let abortReason = null;
596
+ for await (const chunk of stream) {
597
+ text += chunk.text ?? "";
598
+ if (chunk.usageMetadata) usageMeta = chunk.usageMetadata;
599
+ abortReason = opts.shouldAbort?.(text) ?? null;
600
+ if (abortReason) {
601
+ controller.abort();
602
+ break;
570
603
  }
571
- };
604
+ }
605
+ const usage = usageFromMetadata(usageMeta);
606
+ const error = abortReason ? `aborted: ${abortReason}` : void 0;
607
+ if (error) {
608
+ logger.warn(
609
+ `[gemini] ${opts.logKind ?? "call"}${opts.logChunk !== void 0 ? ` chunk ${opts.logChunk}` : ""} ${error} after ${text.length} chars`
610
+ );
611
+ }
572
612
  logLlmCall({
573
613
  ts: new Date(t0).toISOString(),
574
614
  provider: "gemini",
@@ -577,18 +617,22 @@ var GeminiClient = class {
577
617
  chunk: opts.logChunk,
578
618
  prompt,
579
619
  response: text,
580
- usage: result.usage,
620
+ usage,
581
621
  durationMs: Date.now() - t0,
582
- attempt: attempt + 1
622
+ attempt: attempt + 1,
623
+ ...error ? { error } : {}
583
624
  });
584
- return result;
625
+ return error ? { text, usage, error } : { text, usage };
585
626
  } catch (err) {
586
627
  lastError = err instanceof Error ? err.message : String(err);
587
- if (config.thinkingConfig && isThinkingConfigError(lastError)) {
588
- delete config.thinkingConfig;
628
+ if (thinking && isThinkingConfigError(lastError)) {
629
+ const next = fallbackThinking(thinking);
589
630
  logger.warn(
590
- `[gemini] model ${model} rejected thinking config \u2014 retrying without it`
631
+ `[gemini] model ${model} rejected thinking config ${JSON.stringify(thinking)} \u2014 retrying ${next ? `with ${JSON.stringify(next)}` : "without it"}`
591
632
  );
633
+ thinking = next;
634
+ if (thinking) config.thinkingConfig = thinking;
635
+ else delete config.thinkingConfig;
592
636
  continue;
593
637
  }
594
638
  logger.warn(
@@ -654,51 +698,93 @@ var GeminiClient = class {
654
698
  };
655
699
 
656
700
  // src/providers/assemblyai.ts
657
- import { AssemblyAI } from "assemblyai";
701
+ import {
702
+ AssemblyAI
703
+ } from "assemblyai";
658
704
  import { createHash as createHash2 } from "crypto";
659
- import { readFile, mkdir as mkdir2, writeFile } from "fs/promises";
705
+ import { readFile, mkdir as mkdir2, writeFile, rm } from "fs/promises";
660
706
  import { existsSync } from "fs";
661
707
  import { dirname as dirname3 } from "path";
662
708
  async function fileHash(path) {
663
709
  const buf = await readFile(path);
664
710
  return createHash2("sha256").update(buf).digest("hex").slice(0, 24);
665
711
  }
712
+ var DELETED_TEXT = "Deleted by user.";
713
+ async function readPendingId(pendingPath) {
714
+ if (!existsSync(pendingPath)) return void 0;
715
+ try {
716
+ return JSON.parse(await readFile(pendingPath, "utf-8")).id;
717
+ } catch {
718
+ return void 0;
719
+ }
720
+ }
666
721
  var AssemblyAIProvider = class {
667
722
  client;
668
723
  cacheDir;
669
724
  constructor(opts) {
670
- this.client = new AssemblyAI({ apiKey: opts.apiKey });
725
+ this.client = new AssemblyAI({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });
671
726
  this.cacheDir = opts.cacheDir;
672
727
  this.speechModel = opts.speechModel ?? "universal";
673
728
  this.speakersExpected = opts.speakersExpected;
729
+ this.language = opts.language;
730
+ this.zeroStorage = opts.zeroStorage ?? true;
674
731
  }
675
732
  speechModel;
676
733
  speakersExpected;
734
+ language;
735
+ zeroStorage;
736
+ /** Whether the last transcribe() was served from the content-hash cache (no paid call). */
737
+ lastFromCache = false;
677
738
  /** Transcribe a local audio file. Returns cached result if available. */
678
739
  async transcribe(filePath) {
679
740
  const hash = await fileHash(filePath);
680
- const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}.json` : void 0;
741
+ const variant = [
742
+ `lang-${this.language ?? "auto"}`,
743
+ this.speakersExpected && `spk-${this.speakersExpected}`,
744
+ this.speechModel !== "universal" && this.speechModel
745
+ ].filter(Boolean).join("_");
746
+ const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}_${variant}.json` : void 0;
747
+ const pendingPath = cachePath?.replace(/\.json$/, ".pending.json");
748
+ this.lastFromCache = false;
681
749
  if (cachePath && existsSync(cachePath)) {
682
750
  logger.info(`[assemblyai] cache hit ${hash}`);
751
+ this.lastFromCache = true;
752
+ if (pendingPath) await this.finish(pendingPath, await readPendingId(pendingPath));
683
753
  return JSON.parse(await readFile(cachePath, "utf-8"));
684
754
  }
685
- logger.info(`[assemblyai] uploading ${filePath}...`);
686
- const uploadUrl = await withRetry(
687
- "assemblyai upload",
688
- () => this.client.files.upload(filePath)
689
- );
690
- logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
691
- const params = {
692
- audio: uploadUrl,
693
- speaker_labels: true,
694
- speech_model: this.speechModel
695
- };
696
- if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
697
- const transcript = await withRetry(
698
- "assemblyai transcribe",
699
- () => this.client.transcripts.transcribe(params)
700
- );
755
+ let transcript = pendingPath ? await this.resume(pendingPath) : void 0;
756
+ if (!transcript) {
757
+ logger.info(`[assemblyai] uploading ${filePath}...`);
758
+ const uploadUrl = await withRetry(
759
+ "assemblyai upload",
760
+ () => this.client.files.upload(filePath)
761
+ );
762
+ logger.info(
763
+ `[assemblyai] transcribing (speech_model=${this.speechModel}, language=${this.language ?? "auto-detect"})...`
764
+ );
765
+ const params = {
766
+ audio: uploadUrl,
767
+ speaker_labels: true,
768
+ speech_model: this.speechModel
769
+ };
770
+ if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
771
+ if (this.language) params.language_code = this.language;
772
+ else params.language_detection = true;
773
+ const job = await withRetry(
774
+ "assemblyai submit",
775
+ () => this.client.transcripts.submit(params)
776
+ );
777
+ if (pendingPath) {
778
+ await mkdir2(dirname3(pendingPath), { recursive: true });
779
+ await writeFile(pendingPath, JSON.stringify({ id: job.id }));
780
+ }
781
+ transcript = await withRetry(
782
+ "assemblyai transcribe",
783
+ () => this.client.transcripts.waitUntilReady(job.id)
784
+ );
785
+ }
701
786
  if (transcript.status === "error") {
787
+ if (pendingPath) await rm(pendingPath, { force: true });
702
788
  throw new Error(`AssemblyAI error: ${transcript.error}`);
703
789
  }
704
790
  const result = this.mapTranscript(transcript, hash);
@@ -707,10 +793,53 @@ var AssemblyAIProvider = class {
707
793
  await writeFile(cachePath, JSON.stringify(result, null, 2));
708
794
  }
709
795
  logger.info(
710
- `[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers`
796
+ `[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers, language ${result.languageCode ?? "?"}`
711
797
  );
798
+ if (pendingPath) await this.finish(pendingPath, transcript.id);
799
+ else if (this.zeroStorage && transcript.id) await this.deleteRemote(transcript.id);
712
800
  return result;
713
801
  }
802
+ /** Delete job `id` from AssemblyAI (with zero storage), then forget it. */
803
+ async finish(pendingPath, id) {
804
+ if (this.zeroStorage && id) await this.deleteRemote(id);
805
+ await rm(pendingPath, { force: true });
806
+ }
807
+ async deleteRemote(id) {
808
+ await this.client.transcripts.delete(id).then(
809
+ () => logger.debug(`[assemblyai] deleted transcript ${id} from AssemblyAI`),
810
+ (err) => logger.warn(
811
+ `[assemblyai] couldn't delete transcript ${id} from AssemblyAI (it expires in 30 days): ${err instanceof Error ? err.message : String(err)}`
812
+ )
813
+ );
814
+ }
815
+ /** The finished job a stopped run left at `pendingPath`, or undefined to send the audio
816
+ * again: when there is none, or AssemblyAI says it's gone (not found, failed, deleted).
817
+ * Anything less certain (offline, an outage, a refused key) is thrown with the job kept,
818
+ * so the next run neither pays twice nor leaves the job behind undeleted. */
819
+ async resume(pendingPath) {
820
+ const id = await readPendingId(pendingPath);
821
+ if (id) {
822
+ logger.info(`[assemblyai] picking up transcript ${id}, left by a stopped run...`);
823
+ let gone;
824
+ try {
825
+ const t = await withRetry(
826
+ "assemblyai transcribe",
827
+ () => this.client.transcripts.waitUntilReady(id)
828
+ );
829
+ if (t.status === "completed" && t.text !== DELETED_TEXT) return t;
830
+ gone = t.status === "error" ? `it failed: ${t.error}` : "it was deleted";
831
+ } catch (err) {
832
+ const message = err instanceof Error ? err.message : String(err);
833
+ if (!/not found/i.test(message)) throw err;
834
+ gone = message;
835
+ }
836
+ logger.warn(
837
+ `[assemblyai] transcript ${id} is gone (${gone}) \u2014 sending the audio again`
838
+ );
839
+ }
840
+ await rm(pendingPath, { force: true });
841
+ return void 0;
842
+ }
714
843
  mapTranscript(t, id) {
715
844
  const toWord = (w) => ({
716
845
  text: w.text,
@@ -740,6 +869,7 @@ var AssemblyAIProvider = class {
740
869
  durationSec,
741
870
  audioDurationSec: t.audio_duration ?? void 0,
742
871
  // AssemblyAI returns seconds (not ms)
872
+ languageCode: t.language_code ?? void 0,
743
873
  speakers: [...speakers].sort(),
744
874
  transcriptId: t.id ?? id,
745
875
  speechModelUsed: t.speech_model_used ?? void 0,
@@ -758,7 +888,7 @@ var WhisperGroqClient = class {
758
888
  apiKey;
759
889
  model;
760
890
  baseUrl;
761
- async transcribe(audio) {
891
+ async transcribe(audio, opts = {}) {
762
892
  const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
763
893
  const form = new FormData();
764
894
  form.append("file", blob, "audio.mp3");
@@ -766,6 +896,7 @@ var WhisperGroqClient = class {
766
896
  form.append("response_format", "verbose_json");
767
897
  form.append("timestamp_granularities[]", "word");
768
898
  form.append("timestamp_granularities[]", "segment");
899
+ if (opts.language) form.append("language", opts.language);
769
900
  const res = await fetch(`${this.baseUrl}/audio/transcriptions`, {
770
901
  method: "POST",
771
902
  headers: { Authorization: `Bearer ${this.apiKey}` },
@@ -820,6 +951,7 @@ var ElevenLabsClient = class {
820
951
  form.append("diarize", "true");
821
952
  form.append("tag_audio_events", "false");
822
953
  if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
954
+ if (opts.languageCode) form.append("language_code", opts.languageCode);
823
955
  for (const term of opts.keyterms ?? []) form.append("keyterms", term);
824
956
  const data = await withRetry("elevenlabs", async () => {
825
957
  const res = await fetch(`${this.baseUrl}/speech-to-text`, {
@@ -878,17 +1010,53 @@ var ElevenLabsClient = class {
878
1010
  };
879
1011
 
880
1012
  // src/core/pricing.ts
881
- var PRICES_AS_OF = "2026-07";
1013
+ var PRICES_AS_OF = "2026-11-17";
882
1014
  var MODEL_PRICES = {
883
- // Gemini (ai.google.dev/gemini-api/docs/pricing, standard tier, <=200k prompts)
1015
+ "gemini-4-hydrogen": { textIn: 1.5, out: 7.5 },
1016
+ "gemini-4-argon": {
1017
+ until: "2026-11-30",
1018
+ price: { textIn: 2, out: 10 },
1019
+ then: { textIn: 4, out: 20 }
1020
+ },
1021
+ "gemini-4-carbon": {
1022
+ until: "2026-11-30",
1023
+ price: { textIn: 2, out: 10 },
1024
+ then: { textIn: 4, out: 20 }
1025
+ },
884
1026
  "gemini-3.1-pro-preview": { textIn: 2, out: 12 },
885
- "gemini-3-pro-preview": { textIn: 2, out: 12 },
886
- "gemini-3.5-flash": { textIn: 1.5, out: 9 },
1027
+ // ≤200k-token prompts
1028
+ "gemini-3.8-flash": {
1029
+ until: "2026-12-31",
1030
+ price: { textIn: 0.75, out: 3.75 },
1031
+ then: { textIn: 1.5, out: 7.5 }
1032
+ },
1033
+ "gemini-3.6-flash": {
1034
+ until: "2026-12-31",
1035
+ price: { textIn: 0.75, out: 3.75 },
1036
+ then: { textIn: 1.5, out: 7.5 }
1037
+ },
1038
+ // Deprecated 2026-10-08; requests are served by gemini-3.6-flash (priced as such).
1039
+ "gemini-3.5-flash": {
1040
+ until: "2026-12-31",
1041
+ price: { textIn: 0.75, out: 3.75 },
1042
+ then: { textIn: 1.5, out: 7.5 }
1043
+ },
1044
+ "gemini-3.5-flash-lite": { textIn: 0.3, out: 2.5 },
887
1045
  "gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
888
- "gemini-2.5-pro": { textIn: 1.25, out: 10 },
889
- "gemini-2.5-flash": { textIn: 0.3, audioIn: 1, out: 2.5 },
1046
+ // From 2026-12-01 Google serves (and bills) 2.5 Pro as 3.8 Flash and 2.5 Flash as 3.5 Flash-Lite.
1047
+ "gemini-2.5-pro": {
1048
+ until: "2026-11-30",
1049
+ price: { textIn: 1.25, out: 10 },
1050
+ then: { textIn: 1.5, out: 7.5 }
1051
+ },
1052
+ "gemini-2.5-flash": {
1053
+ until: "2026-11-30",
1054
+ price: { textIn: 0.3, audioIn: 1, out: 2.5 },
1055
+ then: { textIn: 0.3, out: 2.5 }
1056
+ },
890
1057
  "gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
891
- // Moving aliases — priced as their current targets.
1058
+ // Moving aliases. Google hasn't documented their targets since January 2026; these are
1059
+ // the last documented targets' prices, so treat them as estimates.
892
1060
  "gemini-pro-latest": { textIn: 2, out: 12 },
893
1061
  "gemini-flash-latest": { textIn: 1.5, out: 9 },
894
1062
  "gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
@@ -907,17 +1075,27 @@ var ASR_HOURLY = {
907
1075
  // whisper-large-v3-turbo
908
1076
  none: 0
909
1077
  };
910
- var AUDIO_TOKENS_PER_SEC = 32;
911
- function priceFor(model) {
912
- if (MODEL_PRICES[model]) return MODEL_PRICES[model];
913
- const hit = Object.keys(MODEL_PRICES).find((k) => model.startsWith(k));
914
- return hit ? MODEL_PRICES[hit] : null;
1078
+ function audioTokensPerSec(model) {
1079
+ return model.startsWith("gemini-4") ? 32 : 25;
1080
+ }
1081
+ function priceFor(model, at = /* @__PURE__ */ new Date()) {
1082
+ const key = model in MODEL_PRICES ? model : Object.keys(MODEL_PRICES).filter((k) => model.startsWith(k)).sort((a, b) => b.length - a.length)[0];
1083
+ if (!key) return null;
1084
+ const p = MODEL_PRICES[key];
1085
+ if (!("until" in p)) return p;
1086
+ return at.toISOString().slice(0, 10) <= p.until ? p.price : p.then;
915
1087
  }
916
1088
  function asrCost(provider, durationSec) {
917
1089
  const hourly = ASR_HOURLY[provider];
918
1090
  if (hourly === void 0) return null;
919
1091
  return durationSec / 3600 * hourly;
920
1092
  }
1093
+ var OUTPUT_TOK_PER_AUDIO_MIN = 700;
1094
+ function thinkingOverhead(model) {
1095
+ if (model.startsWith("gemini-4-hydrogen")) return 0.5;
1096
+ if (model.includes("pro")) return 0.15;
1097
+ return 0;
1098
+ }
921
1099
  function estimateRunCost(opts) {
922
1100
  const lines = [];
923
1101
  let total = 0;
@@ -929,9 +1107,9 @@ function estimateRunCost(opts) {
929
1107
  );
930
1108
  const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
931
1109
  if (p) {
932
- const audioTok = billedAudioSec * AUDIO_TOKENS_PER_SEC;
1110
+ const audioTok = billedAudioSec * audioTokensPerSec(opts.model);
933
1111
  const promptTok = chunks * 1500;
934
- const outTok = opts.durationSec / 60 * 150 + 1500;
1112
+ const outTok = opts.durationSec / 60 * OUTPUT_TOK_PER_AUDIO_MIN * (1 + thinkingOverhead(opts.model)) + 1500;
935
1113
  const inRate = p.audioIn ?? p.textIn;
936
1114
  const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
937
1115
  total += llmUsd;
@@ -959,7 +1137,7 @@ function estimateRunCost(opts) {
959
1137
  }
960
1138
  return { totalUsd: total, lines, incomplete };
961
1139
  }
962
- function computeReceipt(usage, tsProvider, durationSec) {
1140
+ function computeReceipt(usage, tsProvider, durationSec, asrBilled = true) {
963
1141
  let llmUsd = 0;
964
1142
  let incomplete = false;
965
1143
  const lines = [];
@@ -992,11 +1170,11 @@ function computeReceipt(usage, tsProvider, durationSec) {
992
1170
  `${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
993
1171
  );
994
1172
  }
995
- const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
1173
+ const asrUsd = tsProvider === "none" || !asrBilled ? 0 : asrCost(tsProvider, durationSec);
996
1174
  if (asrUsd !== null && tsProvider !== "none") {
997
1175
  perModel[tsProvider] = asrUsd;
998
1176
  lines.push(
999
- `${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 $${asrUsd.toFixed(2)}`
1177
+ `${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 ${asrBilled ? `$${asrUsd.toFixed(2)}` : "cached \xB7 $0.00"}`
1000
1178
  );
1001
1179
  }
1002
1180
  return {
@@ -1137,11 +1315,22 @@ async function describeMeeting(client, model, files, fileName, instructions, aud
1137
1315
  logKind: "describe"
1138
1316
  }
1139
1317
  );
1140
- const text = res.text || "";
1318
+ return { ...parseDescription(res.text || ""), raw: res.text || "" };
1319
+ }
1320
+ function parseDescription(text) {
1141
1321
  const parts = text.split(/\n---\n|\n\s*---\s*\n/);
1142
- const description = parts[0]?.trim() || text.trim();
1143
- const roster = parts.slice(1).join("\n---\n").trim() || "(no explicit roster)";
1144
- return { description, roster, raw: text };
1322
+ return {
1323
+ description: dropHeading(parts[0] ?? "", "DESCRIPTION") || text.trim(),
1324
+ roster: dropHeading(parts.slice(1).join("\n---\n"), "ROSTER") || "(no explicit roster)"
1325
+ };
1326
+ }
1327
+ function dropHeading(section, word) {
1328
+ const s = section.trim();
1329
+ const firstLine = s.split("\n", 1)[0] ?? "";
1330
+ if (new RegExp(`^[#*_\\s]*${word}[#*_:\\s]*$`, "i").test(firstLine)) {
1331
+ return s.slice(firstLine.length).trim();
1332
+ }
1333
+ return s.replace(new RegExp(`^[#*_\\s]*${word}[*_]*\\s*:[*_]*\\s*`, "i"), "");
1145
1334
  }
1146
1335
 
1147
1336
  // src/transcribe/prompts.ts
@@ -1234,13 +1423,6 @@ function transcriptionPrompt(ctx) {
1234
1423
  "Use a roster name ONLY when the voice itself tells you it's that person (they self-identify, are addressed by name, or the voice description clearly matches). If two speakers sound similar and you are not sure which name belongs to which voice, use 'Speaker A' / 'Speaker B' instead \u2014 a WRONG name is much worse than a generic label; a later pass verifies names."
1235
1424
  );
1236
1425
  }
1237
- if (ctx.previousTail) {
1238
- parts.push("");
1239
- parts.push(
1240
- "TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
1241
- );
1242
- parts.push(ctx.previousTail);
1243
- }
1244
1426
  if (ctx.instructions) {
1245
1427
  parts.push("");
1246
1428
  parts.push("ADDITIONAL INSTRUCTIONS:");
@@ -1303,6 +1485,51 @@ function formatDuration(seconds) {
1303
1485
  return parts.join(" ");
1304
1486
  }
1305
1487
 
1488
+ // src/transcribe/degeneration.ts
1489
+ var DEGENERATE_COMPRESSION_RATIO = 2.2;
1490
+ var WINDOW_CHARS = 400;
1491
+ var STEP_CHARS = 200;
1492
+ var MIN_MATCH = 4;
1493
+ var MAX_MATCH = 258;
1494
+ var REF_COST = 3;
1495
+ function ratio(s) {
1496
+ let cost = 0;
1497
+ for (let i = 0; i < s.length; ) {
1498
+ let best = 0;
1499
+ for (let j = Math.max(0, i - WINDOW_CHARS); j < i; j++) {
1500
+ let k = 0;
1501
+ while (i + k < s.length && k < MAX_MATCH && s[j + k] === s[i + k]) k++;
1502
+ if (k > best) best = k;
1503
+ }
1504
+ if (best >= MIN_MATCH) {
1505
+ cost += REF_COST;
1506
+ i += best;
1507
+ } else {
1508
+ cost += 1;
1509
+ i += 1;
1510
+ }
1511
+ }
1512
+ return s.length / cost;
1513
+ }
1514
+ function maxCompressionRatio(text) {
1515
+ if (text.length < WINDOW_CHARS) return 0;
1516
+ let max = 0;
1517
+ for (let i = 0; i + WINDOW_CHARS <= text.length; i += STEP_CHARS) {
1518
+ max = Math.max(max, ratio(text.slice(i, i + WINDOW_CHARS)));
1519
+ }
1520
+ return Math.max(max, ratio(text.slice(-WINDOW_CHARS)));
1521
+ }
1522
+ function tailIsDegenerate(text) {
1523
+ if (text.length < 2 * WINDOW_CHARS) return false;
1524
+ return ratio(text.slice(-WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO && ratio(text.slice(-2 * WINDOW_CHARS, -WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO;
1525
+ }
1526
+ function transcriptTextOf(partialJson) {
1527
+ const out = [];
1528
+ for (const m of partialJson.matchAll(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/g))
1529
+ out.push(m[1]);
1530
+ return out.join(" ");
1531
+ }
1532
+
1306
1533
  // src/transcribe/llm-transcribe.ts
1307
1534
  var MIN_SEGMENTS = 3;
1308
1535
  var MIN_SPAN_RATIO = 0.6;
@@ -1343,6 +1570,16 @@ function parseLlmSegments(data, chunkOffsetSec) {
1343
1570
  return { segments: out, dropped };
1344
1571
  }
1345
1572
  function validate(segments, chunkDuration) {
1573
+ const compression = maxCompressionRatio(segments.map((s) => s.text).join(" "));
1574
+ if (compression > DEGENERATE_COMPRESSION_RATIO) {
1575
+ return {
1576
+ isValid: false,
1577
+ degenerate: true,
1578
+ spanSec: segments.length ? segments[segments.length - 1].endSec - segments[0].startSec : 0,
1579
+ segmentCount: segments.length,
1580
+ message: `degenerate repetition (compression ratio ${compression.toFixed(1)} > ${DEGENERATE_COMPRESSION_RATIO})`
1581
+ };
1582
+ }
1346
1583
  if (segments.length < MIN_SEGMENTS) {
1347
1584
  return {
1348
1585
  isValid: false,
@@ -1373,72 +1610,135 @@ function validate(segments, chunkDuration) {
1373
1610
  async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
1374
1611
  const validationRetries = opts.validationRetries ?? 1;
1375
1612
  const prompt = transcriptionPrompt(ctx);
1376
- let lastResult;
1613
+ let temperature = opts.temperature ?? 0.2;
1614
+ let loopAborted = false;
1615
+ let checkedAt = 0;
1616
+ const shouldAbort = (raw) => {
1617
+ if (raw.length - checkedAt < 800) return null;
1618
+ checkedAt = raw.length;
1619
+ if (!tailIsDegenerate(transcriptTextOf(raw))) return null;
1620
+ loopAborted = true;
1621
+ return "degenerate repetition";
1622
+ };
1623
+ let best;
1624
+ const rank = (r) => r.validation.isValid ? 3 : r.error ? 0 : r.validation.degenerate ? 1 : 2;
1625
+ const keep = (r) => {
1626
+ if (!best || rank(r) > rank(best) || rank(r) === rank(best) && r.validation.spanSec > best.validation.spanSec)
1627
+ best = r;
1628
+ };
1377
1629
  for (let attempt = 0; attempt <= validationRetries; attempt++) {
1630
+ loopAborted = false;
1631
+ checkedAt = 0;
1378
1632
  const gen = await client.generateJson(
1379
1633
  model,
1380
1634
  prompt,
1381
1635
  [{ path: chunkPath }],
1382
1636
  TRANSCRIPT_SCHEMA,
1383
1637
  {
1384
- temperature: opts.temperature ?? 0.2,
1638
+ temperature,
1385
1639
  maxRetries: 3,
1386
1640
  logKind: "transcribe",
1387
- logChunk: ctx.index - 1
1641
+ logChunk: ctx.index - 1,
1642
+ shouldAbort
1388
1643
  }
1389
1644
  );
1390
1645
  if (gen.error || !gen.data) {
1391
- lastResult = {
1646
+ keep({
1392
1647
  segments: [],
1393
1648
  raw: gen.raw,
1394
1649
  usage: gen.usage,
1395
1650
  validation: {
1396
1651
  isValid: false,
1652
+ degenerate: loopAborted,
1397
1653
  spanSec: 0,
1398
1654
  segmentCount: 0,
1399
1655
  message: gen.error || "no data"
1400
1656
  },
1401
1657
  error: gen.error
1402
- };
1658
+ });
1403
1659
  logger.warn(
1404
1660
  `[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
1405
1661
  );
1662
+ if (loopAborted) temperature = Math.min(1, temperature + 0.3);
1406
1663
  continue;
1407
1664
  }
1408
1665
  const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
1409
1666
  const v = validate(segments, opts.chunkDurationSec);
1410
- lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
1667
+ const result = { segments, raw: gen.raw, usage: gen.usage, validation: v };
1668
+ keep(result);
1411
1669
  if (v.isValid) {
1412
1670
  logger.info(
1413
1671
  `[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
1414
1672
  );
1415
- return lastResult;
1673
+ return result;
1416
1674
  }
1417
1675
  logger.warn(
1418
1676
  `[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
1419
1677
  );
1678
+ if (v.degenerate) temperature = Math.min(1, temperature + 0.3);
1420
1679
  }
1421
1680
  logger.error(
1422
1681
  `[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
1423
1682
  );
1424
- return lastResult;
1683
+ return best;
1684
+ }
1685
+
1686
+ // src/transcribe/grounding.ts
1687
+ var MIN_GROUNDED_PRECISION = 0.3;
1688
+ var MIN_TOKENS = 30;
1689
+ var MAX_SCRIPT_SHARE_GAP = 0.2;
1690
+ var STOP_WORDS = Object.fromEntries(
1691
+ "the a an and or but so to of in on at for with is it's it i you we they he she that this be are was were do don't not yeah yes okay ok like uh um mm hmm mhm oh just i'm you're that's".split(" ").map((w) => [w, true])
1692
+ );
1693
+ var NON_LATIN = /[^\u0000-\u024F\u2000-\u206F]/u;
1694
+ function contentTokens(words) {
1695
+ const bag = /* @__PURE__ */ new Map();
1696
+ for (const w of words) {
1697
+ const t = w.toLowerCase().replace(/^[^\p{L}\p{N}']+|[^\p{L}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
1698
+ if (t && !STOP_WORDS[t]) bag.set(t, (bag.get(t) ?? 0) + 1);
1699
+ }
1700
+ return bag;
1701
+ }
1702
+ function chunkGrounding(segments, asrWords, start, end) {
1703
+ const asrInRange = asrWords.filter((w) => w.start >= start && w.start < end);
1704
+ const llmWords = segments.map((s) => s.text.replace(/\[[^\]]*\]/g, " ")).join(" ").split(/\s+/).filter(Boolean);
1705
+ const llm = contentTokens(llmWords);
1706
+ const asr = contentTokens(asrInRange.map((w) => w.text));
1707
+ let llmTokens = 0;
1708
+ let asrTokens = 0;
1709
+ let shared = 0;
1710
+ for (const n of llm.values()) llmTokens += n;
1711
+ for (const n of asr.values()) asrTokens += n;
1712
+ for (const [t, n] of llm) shared += Math.min(n, asr.get(t) ?? 0);
1713
+ const share = (ws) => ws.length ? ws.filter((w) => NON_LATIN.test(w)).length / ws.length : 0;
1714
+ const scriptsMatch = Math.abs(share(llmWords) - share(asrInRange.map((w) => w.text))) <= MAX_SCRIPT_SHARE_GAP;
1715
+ const judged = llmTokens >= MIN_TOKENS && asrTokens >= MIN_TOKENS && scriptsMatch;
1716
+ const precision = llmTokens ? shared / llmTokens : 1;
1717
+ return {
1718
+ llmTokens,
1719
+ asrTokens,
1720
+ precision,
1721
+ judged,
1722
+ grounded: !judged || precision >= MIN_GROUNDED_PRECISION
1723
+ };
1425
1724
  }
1426
1725
 
1427
1726
  // src/align/normalize.ts
1428
- function normalize(word) {
1429
- return word.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "").replace(/'+$/g, "").replace(/^'+/g, "");
1727
+ function normalizeWord(word) {
1728
+ return word.normalize("NFKC").toLowerCase().replace(/[’‘`]/g, "'").replace(/^[^\p{L}\p{M}\p{N}']+|[^\p{L}\p{M}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
1430
1729
  }
1431
1730
  function tokenize(text) {
1432
1731
  const out = [];
1433
1732
  for (const raw of text.split(/\s+/)) {
1434
1733
  if (!raw) continue;
1435
- const norm2 = normalize(raw);
1734
+ const norm2 = normalizeWord(raw);
1436
1735
  if (norm2) out.push({ original: raw, norm: norm2 });
1437
1736
  }
1438
1737
  return out;
1439
1738
  }
1440
1739
  function fuzzyEqual(a, b) {
1441
1740
  if (a === b) return true;
1741
+ if (!a || !b) return false;
1442
1742
  if (Math.abs(a.length - b.length) <= 1) {
1443
1743
  return editDistanceChars(a, b, 1) <= 1;
1444
1744
  }
@@ -1464,9 +1764,85 @@ function editDistanceChars(a, b, max) {
1464
1764
  return prev[n];
1465
1765
  }
1466
1766
 
1767
+ // src/transcribe/coverage.ts
1768
+ var MIN_COVERAGE_RATIO = 0.6;
1769
+ var MIN_ASR_WORDS = 200;
1770
+ function chunkCoverage(segments, asrWords, start, end) {
1771
+ const llmWords = segments.reduce(
1772
+ (n, s) => n + tokenize(s.text.replace(/\[[^\]]*\]/g, " ")).length,
1773
+ 0
1774
+ );
1775
+ const asrCount = asrWords.reduce(
1776
+ (n, w) => n + (w.start >= start && w.start < end ? tokenize(w.text).length : 0),
1777
+ 0
1778
+ );
1779
+ const ratio2 = asrCount ? llmWords / asrCount : Infinity;
1780
+ const judged = asrCount >= MIN_ASR_WORDS;
1781
+ return {
1782
+ llmWords,
1783
+ asrWords: asrCount,
1784
+ ratio: ratio2,
1785
+ judged,
1786
+ low: judged && ratio2 < MIN_COVERAGE_RATIO
1787
+ };
1788
+ }
1789
+
1790
+ // src/core/retranscribe.ts
1791
+ import { existsSync as existsSync3 } from "fs";
1792
+ var HALF_OVERLAP_SEC = 5;
1793
+ async function transcribeInHalves(opts) {
1794
+ const { chunk } = opts;
1795
+ const mid = (chunk.start + chunk.end) / 2;
1796
+ const halves = [
1797
+ { name: "a", from: chunk.start, to: Math.min(chunk.end, mid + HALF_OVERLAP_SEC) },
1798
+ { name: "b", from: Math.max(chunk.start, mid - HALF_OVERLAP_SEC), to: chunk.end }
1799
+ ];
1800
+ const results = [];
1801
+ for (const h of halves) {
1802
+ const path = `${opts.pathPrefix}_half_${h.name}.mp3`;
1803
+ if (!existsSync3(path))
1804
+ await extractChunk(opts.audioPath, path, h.from, h.to, opts.audioOpts);
1805
+ results.push(
1806
+ await transcribeChunk(opts.client, opts.model, path, h.from, opts.ctx, {
1807
+ chunkDurationSec: h.to - h.from,
1808
+ validationRetries: 0
1809
+ })
1810
+ );
1811
+ }
1812
+ const [a, b] = results;
1813
+ const center = (s) => (s.startSec + s.endSec) / 2;
1814
+ const segments = [
1815
+ ...a.segments.filter((s) => center(s) < mid),
1816
+ ...b.segments.filter((s) => center(s) >= mid)
1817
+ ];
1818
+ const first = segments[0];
1819
+ const last = segments[segments.length - 1];
1820
+ return {
1821
+ segments,
1822
+ raw: JSON.stringify({ halves: [a.raw, b.raw] }),
1823
+ usage: {
1824
+ inputTokens: a.usage.inputTokens + b.usage.inputTokens,
1825
+ outputTokens: a.usage.outputTokens + b.usage.outputTokens,
1826
+ thoughtTokens: (a.usage.thoughtTokens ?? 0) + (b.usage.thoughtTokens ?? 0),
1827
+ totalTokens: a.usage.totalTokens + b.usage.totalTokens
1828
+ },
1829
+ validation: {
1830
+ isValid: a.validation.isValid && b.validation.isValid,
1831
+ degenerate: Boolean(a.validation.degenerate || b.validation.degenerate),
1832
+ spanSec: first && last ? last.endSec - first.startSec : 0,
1833
+ segmentCount: segments.length,
1834
+ message: `halves: ${a.validation.message} | ${b.validation.message}`
1835
+ },
1836
+ ...a.error || b.error ? { error: [a.error, b.error].filter(Boolean).join(" | ") } : {}
1837
+ };
1838
+ }
1839
+
1467
1840
  // src/align/edit-distance.ts
1468
1841
  var INDEL = 2;
1842
+ var OUT_OF_WINDOW = { cost: 2 * INDEL + 1, fuzzy: false };
1469
1843
  function matchCost(a, b) {
1844
+ if (a.window && b.start !== void 0 && (b.start < a.window.lo || b.start > a.window.hi))
1845
+ return OUT_OF_WINDOW;
1470
1846
  if (a.norm === b.norm) return { cost: 0, fuzzy: false };
1471
1847
  if (fuzzyEqual(a.norm, b.norm)) return { cost: 1, fuzzy: true };
1472
1848
  return { cost: 2, fuzzy: false };
@@ -1544,12 +1920,19 @@ function alignWords(llm, asr) {
1544
1920
  }
1545
1921
 
1546
1922
  // src/align/aligner.ts
1923
+ var WINDOW_SLACK_SEC = 2;
1924
+ var UNANCHORED_MAX_DRIFT_SEC = 15;
1925
+ var STRETCH_MIN_SEC = 30;
1926
+ var STRETCH_SEC_PER_WORD = 3;
1927
+ var MAX_INNER_GAP_SEC = 8;
1928
+ var SPOKEN_SEC_PER_WORD = 0.5;
1929
+ var UNCONFIRMED_MAX_SEC = 5;
1547
1930
  function toAsrTokens(words) {
1548
1931
  return words.map((w) => ({
1549
1932
  text: w.text,
1550
1933
  start: w.start,
1551
1934
  end: w.end,
1552
- norm: w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
1935
+ norm: normalizeWord(w.text)
1553
1936
  }));
1554
1937
  }
1555
1938
  function transferTiming(llm, asr, ops) {
@@ -1608,7 +1991,9 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
1608
1991
  for (const { s, i } of sorted) {
1609
1992
  const toks = tokenize(s.text);
1610
1993
  const start = flat.length;
1611
- for (const t of toks) flat.push({ original: t.original, norm: t.norm, segIdx: i });
1994
+ const window = s.chunkStart !== void 0 && s.chunkEnd !== void 0 ? { lo: s.chunkStart - WINDOW_SLACK_SEC, hi: s.chunkEnd + WINDOW_SLACK_SEC } : void 0;
1995
+ for (const t of toks)
1996
+ flat.push({ original: t.original, norm: t.norm, segIdx: i, window });
1612
1997
  segRanges.push({ src: i, start, end: flat.length });
1613
1998
  }
1614
1999
  if (flat.length === 0 || asrWords.length === 0) {
@@ -1653,21 +2038,53 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
1653
2038
  let end;
1654
2039
  let timingSource;
1655
2040
  const confidence = tokenCount ? exact / tokenCount : 0;
1656
- if (firstTimed && lastTimed) {
2041
+ const unanchoredDrift = segOps.length === 0 && firstTimed ? Math.abs(firstTimed.start - s.startSec) : 0;
2042
+ if (firstTimed && lastTimed && unanchoredDrift <= UNANCHORED_MAX_DRIFT_SEC) {
1657
2043
  start = firstTimed.start;
1658
2044
  end = lastTimed.end;
1659
2045
  timingSource = confidence >= confThreshold ? "aligned" : "interpolated";
2046
+ if (end - start > Math.max(STRETCH_MIN_SEC, STRETCH_SEC_PER_WORD * tokenCount)) {
2047
+ const runs = [];
2048
+ for (const t of segTimes) {
2049
+ if (isNaN(t.start)) continue;
2050
+ const run2 = runs[runs.length - 1];
2051
+ if (run2 && t.start - run2.end <= MAX_INNER_GAP_SEC) {
2052
+ run2.end = Math.max(run2.end, t.end);
2053
+ if (t.matched) run2.matched++;
2054
+ } else {
2055
+ runs.push({ start: t.start, end: t.end, matched: t.matched ? 1 : 0 });
2056
+ }
2057
+ }
2058
+ const best = runs.reduce(
2059
+ (a, b) => b.matched > a.matched || b.matched === a.matched && Math.abs(b.start - s.startSec) < Math.abs(a.start - s.startSec) ? b : a
2060
+ );
2061
+ start = best.start;
2062
+ end = best.end;
2063
+ }
2064
+ const spoken = Math.max(1, SPOKEN_SEC_PER_WORD * tokenCount);
2065
+ if (exact === 0 && end - start > Math.max(UNCONFIRMED_MAX_SEC, 3 * spoken)) {
2066
+ end = start + spoken;
2067
+ }
1660
2068
  } else {
1661
2069
  start = s.startSec;
1662
2070
  end = s.endSec;
1663
2071
  timingSource = "coarse";
1664
2072
  }
1665
- const words = segTimes.map((t, idx) => ({
1666
- text: flat[range.start + idx].original,
1667
- start: isNaN(t.start) ? start : t.start,
1668
- end: isNaN(t.end) ? end : t.end,
1669
- matched: t.matched
1670
- }));
2073
+ const step = timingSource === "coarse" && tokenCount ? (end - start) / tokenCount : 0;
2074
+ const inside = (x) => Math.min(Math.max(x, start), end);
2075
+ const words = segTimes.map(
2076
+ (t, idx) => timingSource === "coarse" ? {
2077
+ text: flat[range.start + idx].original,
2078
+ start: start + step * idx,
2079
+ end: start + step * (idx + 1),
2080
+ matched: false
2081
+ } : {
2082
+ text: flat[range.start + idx].original,
2083
+ start: isNaN(t.start) ? start : inside(t.start),
2084
+ end: isNaN(t.end) ? end : inside(t.end),
2085
+ matched: t.matched
2086
+ }
2087
+ );
1671
2088
  out.push({
1672
2089
  speaker: s.speaker,
1673
2090
  start,
@@ -1682,23 +2099,90 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
1682
2099
  }
1683
2100
  return out;
1684
2101
  }
2102
+ var CLOCK_ANCHOR_MIN_WORDS = 3;
2103
+ var CLOCK_ANCHOR_MIN_SHARE = 0.6;
2104
+ function toAsrClock(segments, asrWords) {
2105
+ if (!asrWords.length) return segments;
2106
+ const chunks = /* @__PURE__ */ new Map();
2107
+ for (const s of segments) {
2108
+ if (s.chunkIndex === void 0) continue;
2109
+ const group = chunks.get(s.chunkIndex);
2110
+ if (group) group.push(s);
2111
+ else chunks.set(s.chunkIndex, [s]);
2112
+ }
2113
+ const moved = /* @__PURE__ */ new Map();
2114
+ for (const group of chunks.values()) {
2115
+ const lo = Math.min(...group.map((s) => s.chunkStart ?? s.startSec)) - WINDOW_SLACK_SEC;
2116
+ const hi = Math.max(...group.map((s) => s.chunkEnd ?? s.endSec)) + WINDOW_SLACK_SEC;
2117
+ const aligned = alignSegments(
2118
+ group,
2119
+ asrWords.filter((w) => w.end >= lo && w.start <= hi)
2120
+ );
2121
+ const shifts = aligned.map(
2122
+ (a) => a.confidence >= CLOCK_ANCHOR_MIN_SHARE && a.words.filter((w) => w.matched).length >= CLOCK_ANCHOR_MIN_WORDS ? a.start - group[a.sourceIndex].startSec : void 0
2123
+ );
2124
+ for (let k = 0; k < aligned.length; k++) {
2125
+ let shift = shifts[k];
2126
+ for (let r = 1; shift === void 0 && r < aligned.length; r++) {
2127
+ shift = shifts[k - r] ?? shifts[k + r];
2128
+ }
2129
+ const s = group[aligned[k].sourceIndex];
2130
+ moved.set(s, {
2131
+ ...s,
2132
+ startSec: s.startSec + (shift ?? 0),
2133
+ endSec: s.endSec + (shift ?? 0)
2134
+ });
2135
+ }
2136
+ }
2137
+ return segments.map((s) => moved.get(s) ?? s);
2138
+ }
1685
2139
 
1686
2140
  // src/align/fill-gaps.ts
1687
2141
  var MIN_GAP_SEC = 0.8;
1688
2142
  var MIN_WORDS = 1;
1689
- function normSet(text) {
1690
- return new Set(tokenize(text).map((t) => t.norm));
2143
+ var HEAD_SLACK_WORDS = 5;
2144
+ function utteranceAt(utts, t) {
2145
+ let lo = 0;
2146
+ let hi = utts.length - 1;
2147
+ let found = -1;
2148
+ while (lo <= hi) {
2149
+ const mid = lo + hi >> 1;
2150
+ if (utts[mid].start <= t) {
2151
+ found = mid;
2152
+ lo = mid + 1;
2153
+ } else {
2154
+ hi = mid - 1;
2155
+ }
2156
+ }
2157
+ return found >= 0 && t <= utts[found].end ? found : -1;
2158
+ }
2159
+ function dominantSpeaker(utts, start, end) {
2160
+ let best = utts[0]?.speaker || "speaker_?";
2161
+ let bestOv = 0;
2162
+ for (const u of utts) {
2163
+ const ov = Math.max(0, Math.min(end, u.end) - Math.max(start, u.start));
2164
+ if (ov > bestOv) {
2165
+ bestOv = ov;
2166
+ best = u.speaker;
2167
+ }
2168
+ }
2169
+ return best;
1691
2170
  }
1692
2171
  function fillAsrGaps(segments, asrWords, asrUtterances) {
1693
2172
  if (!asrWords.length) return segments;
1694
2173
  const sorted = [...segments].sort((a, b) => a.start - b.start);
2174
+ const utts = [...asrUtterances].sort((a, b) => a.start - b.start);
1695
2175
  const ranges = [];
1696
- const firstStart = sorted.length ? sorted[0].start : asrWords[asrWords.length - 1].end;
1697
- if (firstStart > 0) ranges.push([0, firstStart, sorted[0]]);
1698
- for (let i = 0; i < sorted.length - 1; i++) {
1699
- const cur = sorted[i];
1700
- const next = sorted[i + 1];
1701
- if (next.start > cur.end) ranges.push([cur.end, next.start, next]);
2176
+ if (!sorted.length) {
2177
+ ranges.push([0, Infinity, void 0]);
2178
+ } else {
2179
+ if (sorted[0].start > 0) ranges.push([0, sorted[0].start, sorted[0]]);
2180
+ let coveredTo = sorted[0].end;
2181
+ for (const next of sorted.slice(1)) {
2182
+ if (next.start > coveredTo) ranges.push([coveredTo, next.start, next]);
2183
+ coveredTo = Math.max(coveredTo, next.end);
2184
+ }
2185
+ ranges.push([coveredTo, Infinity, void 0]);
1702
2186
  }
1703
2187
  const filled = [];
1704
2188
  for (const [gs, ge, following] of ranges) {
@@ -1706,38 +2190,44 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
1706
2190
  const words = asrWords.filter((w) => w.start >= gs && w.start < ge);
1707
2191
  if (words.length < MIN_WORDS) continue;
1708
2192
  if (following) {
1709
- const followingWords = normSet(following.text);
1710
- const gapNorms = words.map(
1711
- (w) => w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
2193
+ const gapNorms = words.map((w) => normalizeWord(w.text)).filter(Boolean);
2194
+ const head = new Set(
2195
+ tokenize(following.text).slice(0, gapNorms.length + HEAD_SLACK_WORDS).map((t) => t.norm)
1712
2196
  );
1713
- const covered = gapNorms.filter((n) => n && followingWords.has(n)).length;
1714
- if (covered / gapNorms.filter(Boolean).length >= 0.6) continue;
1715
- }
1716
- let bestSp = asrUtterances[0]?.speaker || "speaker_?";
1717
- let bestOv = 0;
1718
- for (const u of asrUtterances) {
1719
- const ov = Math.max(0, Math.min(ge, u.end) - Math.max(gs, u.start));
1720
- if (ov > bestOv) {
1721
- bestOv = ov;
1722
- bestSp = u.speaker;
2197
+ const covered = gapNorms.filter((n) => head.has(n)).length;
2198
+ if (covered / gapNorms.length >= 0.6) continue;
2199
+ }
2200
+ const runs = [];
2201
+ for (const w of words) {
2202
+ const u = utteranceAt(utts, w.start);
2203
+ const cur = runs[runs.length - 1];
2204
+ if (cur && (u === -1 || u === cur.utt || cur.utt === -1)) {
2205
+ cur.words.push(w);
2206
+ if (cur.utt === -1) cur.utt = u;
2207
+ } else {
2208
+ runs.push({ words: [w], utt: u });
1723
2209
  }
1724
2210
  }
1725
- filled.push({
1726
- speaker: bestSp,
1727
- start: words[0].start,
1728
- end: words[words.length - 1].end,
1729
- text: words.map((w) => w.text).join(" "),
1730
- tone: [],
1731
- confidence: 0,
1732
- timingSource: "timestamped",
1733
- words: words.map((w) => ({
1734
- text: w.text,
1735
- start: w.start,
1736
- end: w.end,
1737
- matched: true
1738
- })),
1739
- sourceIndex: -1
1740
- });
2211
+ for (const run2 of runs) {
2212
+ const first = run2.words[0];
2213
+ const last = run2.words[run2.words.length - 1];
2214
+ filled.push({
2215
+ speaker: run2.utt >= 0 ? utts[run2.utt].speaker : dominantSpeaker(utts, first.start, last.end),
2216
+ start: first.start,
2217
+ end: last.end,
2218
+ text: run2.words.map((w) => w.text).join(" "),
2219
+ tone: [],
2220
+ confidence: 0,
2221
+ timingSource: "timestamped",
2222
+ words: run2.words.map((w) => ({
2223
+ text: w.text,
2224
+ start: w.start,
2225
+ end: w.end,
2226
+ matched: true
2227
+ })),
2228
+ sourceIndex: -1
2229
+ });
2230
+ }
1741
2231
  }
1742
2232
  if (!filled.length) return sorted;
1743
2233
  return [...sorted, ...filled].sort((a, b) => a.start - b.start);
@@ -1989,125 +2479,6 @@ function splitMixedVoiceSegments(segments, utterances) {
1989
2479
  return out.sort((a, b) => a.start - b.start);
1990
2480
  }
1991
2481
 
1992
- // src/providers/openai-compat.ts
1993
- var PROVIDER_BASE = {
1994
- deepseek: "https://api.deepseek.com/v1",
1995
- groq: "https://api.groq.com/openai/v1",
1996
- openai: "https://api.openai.com/v1"
1997
- };
1998
- var OpenAICompatClient = class _OpenAICompatClient {
1999
- constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
2000
- this.baseUrl = baseUrl;
2001
- this.apiKey = apiKey;
2002
- this.defaultModel = defaultModel;
2003
- this.providerName = providerName;
2004
- }
2005
- baseUrl;
2006
- apiKey;
2007
- defaultModel;
2008
- providerName;
2009
- static fromProvider(provider, apiKey, defaultModel) {
2010
- const base = PROVIDER_BASE[provider] ?? provider;
2011
- return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
2012
- }
2013
- async chat(model, messages, opts = {}) {
2014
- const m = model ?? this.defaultModel;
2015
- const maxRetries = opts.maxRetries ?? 5;
2016
- const body = {
2017
- model: m,
2018
- messages,
2019
- temperature: opts.temperature ?? 0.2
2020
- };
2021
- if (opts.maxTokens) body.max_tokens = opts.maxTokens;
2022
- if (opts.responseJson) {
2023
- body.response_format = { type: "json_object" };
2024
- }
2025
- if (this.providerName === "gemini") {
2026
- body.reasoning_effort = "low";
2027
- }
2028
- let lastError;
2029
- const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
2030
- for (let attempt = 0; attempt < maxRetries; attempt++) {
2031
- const t0 = Date.now();
2032
- try {
2033
- const res = await fetch(`${this.baseUrl}/chat/completions`, {
2034
- method: "POST",
2035
- headers: {
2036
- "Content-Type": "application/json",
2037
- Authorization: `Bearer ${this.apiKey}`
2038
- },
2039
- body: JSON.stringify(body)
2040
- });
2041
- if (!res.ok) {
2042
- const txt = await res.text();
2043
- throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
2044
- }
2045
- const data = await res.json();
2046
- const text = data.choices?.[0]?.message?.content ?? "";
2047
- const usage = {
2048
- inputTokens: data.usage?.prompt_tokens ?? 0,
2049
- outputTokens: data.usage?.completion_tokens ?? 0
2050
- };
2051
- logLlmCall({
2052
- ts: new Date(t0).toISOString(),
2053
- provider: this.providerName,
2054
- model: m,
2055
- kind: opts.logKind,
2056
- prompt: promptStr,
2057
- response: text,
2058
- usage,
2059
- durationMs: Date.now() - t0,
2060
- attempt: attempt + 1
2061
- });
2062
- return { text, usage };
2063
- } catch (err) {
2064
- lastError = err instanceof Error ? err.message : String(err);
2065
- if (body.response_format && /response_format/i.test(lastError)) {
2066
- delete body.response_format;
2067
- continue;
2068
- }
2069
- if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
2070
- delete body.reasoning_effort;
2071
- continue;
2072
- }
2073
- logLlmCall({
2074
- ts: new Date(t0).toISOString(),
2075
- provider: this.providerName,
2076
- model: m,
2077
- kind: opts.logKind,
2078
- prompt: promptStr,
2079
- response: "",
2080
- durationMs: Date.now() - t0,
2081
- attempt: attempt + 1,
2082
- error: lastError
2083
- });
2084
- if (attempt < maxRetries - 1)
2085
- await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
2086
- }
2087
- }
2088
- return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
2089
- }
2090
- async chatJson(model, messages, opts = {}) {
2091
- let lastRaw = "";
2092
- let lastError;
2093
- for (let attempt = 0; attempt < 2; attempt++) {
2094
- const res = await this.chat(model, messages, { ...opts, responseJson: true });
2095
- lastRaw = res.text;
2096
- lastError = res.error;
2097
- if (res.error || !res.text) continue;
2098
- try {
2099
- let txt = res.text.trim();
2100
- const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
2101
- if (fence && fence[1]) txt = fence[1];
2102
- return { data: JSON.parse(txt), raw: res.text };
2103
- } catch (err) {
2104
- lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
2105
- }
2106
- }
2107
- return { data: null, raw: lastRaw, error: lastError };
2108
- }
2109
- };
2110
-
2111
2482
  // src/diarize/identify.ts
2112
2483
  var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
2113
2484
  function buildTranscriptExcerpt(segments, speakers) {
@@ -2373,7 +2744,8 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
2373
2744
  wantB ? runPass(reasonerB) : Promise.resolve(void 0)
2374
2745
  ]);
2375
2746
  const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
2376
- if (passFailed(resA) && (!wantB || passFailed(resB))) {
2747
+ const allPassesFailed = passFailed(resA) && (!wantB || passFailed(resB));
2748
+ if (allPassesFailed) {
2377
2749
  logger.warn(
2378
2750
  `identify: ALL passes failed (${resA.reasoning.slice(0, 80)}) \u2014 speakers left as generic labels. Re-run to retry naming cheaply (everything else is cached).`
2379
2751
  );
@@ -2478,10 +2850,164 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
2478
2850
  decisions,
2479
2851
  tripwires,
2480
2852
  passA: { ...resA, model: reasonerA.model },
2481
- passB: resB ? { ...resB, model: reasonerB.model } : void 0
2853
+ passB: resB ? { ...resB, model: reasonerB.model } : void 0,
2854
+ allPassesFailed
2482
2855
  };
2483
2856
  }
2484
2857
 
2858
+ // src/providers/openai-compat.ts
2859
+ async function chatJsonWith(client, model, messages, opts) {
2860
+ let lastRaw = "";
2861
+ let lastError;
2862
+ for (let attempt = 0; attempt < 2; attempt++) {
2863
+ const res = await client.chat(model, messages, { ...opts, responseJson: true });
2864
+ lastRaw = res.text;
2865
+ lastError = res.error;
2866
+ if (res.error || !res.text) continue;
2867
+ try {
2868
+ let txt = res.text.trim();
2869
+ const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
2870
+ if (fence && fence[1]) txt = fence[1];
2871
+ return { data: JSON.parse(txt), raw: res.text };
2872
+ } catch (err) {
2873
+ lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
2874
+ }
2875
+ }
2876
+ return { data: null, raw: lastRaw, error: lastError };
2877
+ }
2878
+ var PROVIDER_BASE = {
2879
+ deepseek: "https://api.deepseek.com/v1",
2880
+ groq: "https://api.groq.com/openai/v1",
2881
+ openai: "https://api.openai.com/v1"
2882
+ };
2883
+ var OpenAICompatClient = class _OpenAICompatClient {
2884
+ constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
2885
+ this.baseUrl = baseUrl;
2886
+ this.apiKey = apiKey;
2887
+ this.defaultModel = defaultModel;
2888
+ this.providerName = providerName;
2889
+ }
2890
+ baseUrl;
2891
+ apiKey;
2892
+ defaultModel;
2893
+ providerName;
2894
+ static fromProvider(provider, apiKey, defaultModel) {
2895
+ const base = PROVIDER_BASE[provider] ?? provider;
2896
+ return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
2897
+ }
2898
+ async chat(model, messages, opts = {}) {
2899
+ const m = model ?? this.defaultModel;
2900
+ const maxRetries = opts.maxRetries ?? 5;
2901
+ const body = {
2902
+ model: m,
2903
+ messages,
2904
+ temperature: opts.temperature ?? 0.2
2905
+ };
2906
+ if (opts.maxTokens) body.max_tokens = opts.maxTokens;
2907
+ if (opts.responseJson) {
2908
+ body.response_format = { type: "json_object" };
2909
+ }
2910
+ if (this.providerName === "gemini") {
2911
+ body.reasoning_effort = "low";
2912
+ }
2913
+ let lastError;
2914
+ const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
2915
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
2916
+ const t0 = Date.now();
2917
+ try {
2918
+ const res = await fetch(`${this.baseUrl}/chat/completions`, {
2919
+ method: "POST",
2920
+ headers: {
2921
+ "Content-Type": "application/json",
2922
+ Authorization: `Bearer ${this.apiKey}`
2923
+ },
2924
+ body: JSON.stringify(body)
2925
+ });
2926
+ if (!res.ok) {
2927
+ const txt = await res.text();
2928
+ throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
2929
+ }
2930
+ const data = await res.json();
2931
+ const text = data.choices?.[0]?.message?.content ?? "";
2932
+ const usage = {
2933
+ inputTokens: data.usage?.prompt_tokens ?? 0,
2934
+ outputTokens: data.usage?.completion_tokens ?? 0
2935
+ };
2936
+ logLlmCall({
2937
+ ts: new Date(t0).toISOString(),
2938
+ provider: this.providerName,
2939
+ model: m,
2940
+ kind: opts.logKind,
2941
+ prompt: promptStr,
2942
+ response: text,
2943
+ usage,
2944
+ durationMs: Date.now() - t0,
2945
+ attempt: attempt + 1
2946
+ });
2947
+ return { text, usage };
2948
+ } catch (err) {
2949
+ lastError = err instanceof Error ? err.message : String(err);
2950
+ if (body.response_format && /response_format/i.test(lastError)) {
2951
+ delete body.response_format;
2952
+ continue;
2953
+ }
2954
+ if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
2955
+ delete body.reasoning_effort;
2956
+ continue;
2957
+ }
2958
+ logLlmCall({
2959
+ ts: new Date(t0).toISOString(),
2960
+ provider: this.providerName,
2961
+ model: m,
2962
+ kind: opts.logKind,
2963
+ prompt: promptStr,
2964
+ response: "",
2965
+ durationMs: Date.now() - t0,
2966
+ attempt: attempt + 1,
2967
+ error: lastError
2968
+ });
2969
+ if (attempt < maxRetries - 1)
2970
+ await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
2971
+ }
2972
+ }
2973
+ return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
2974
+ }
2975
+ chatJson(model, messages, opts = {}) {
2976
+ return chatJsonWith(this, model, messages, opts);
2977
+ }
2978
+ };
2979
+
2980
+ // src/providers/gemini-chat.ts
2981
+ var THINKING_HEADROOM_TOKENS = 4096;
2982
+ var GeminiChatClient = class {
2983
+ constructor(gemini, defaultModel) {
2984
+ this.gemini = gemini;
2985
+ this.defaultModel = defaultModel;
2986
+ }
2987
+ gemini;
2988
+ defaultModel;
2989
+ async chat(model, messages, opts = {}) {
2990
+ const system = messages.filter((m) => m.role === "system").map((m) => m.content);
2991
+ const prompt = messages.filter((m) => m.role !== "system").map((m) => m.content).join("\n\n");
2992
+ const r = await this.gemini.generate(model ?? this.defaultModel, prompt, [], {
2993
+ temperature: opts.temperature ?? 0.2,
2994
+ maxOutputTokens: opts.maxTokens ? opts.maxTokens + THINKING_HEADROOM_TOKENS : void 0,
2995
+ responseJson: opts.responseJson,
2996
+ systemInstruction: system.length ? system.join("\n\n") : void 0,
2997
+ maxRetries: opts.maxRetries ?? 5,
2998
+ logKind: opts.logKind
2999
+ });
3000
+ const usage = {
3001
+ inputTokens: r.usage.inputTokens,
3002
+ outputTokens: r.usage.outputTokens
3003
+ };
3004
+ return r.error ? { text: r.text, usage, error: r.error } : { text: r.text, usage };
3005
+ }
3006
+ chatJson(model, messages, opts = {}) {
3007
+ return chatJsonWith(this, model, messages, opts);
3008
+ }
3009
+ };
3010
+
2485
3011
  // src/providers/reasoner.ts
2486
3012
  var PROVIDERS = {
2487
3013
  deepseek: { baseUrl: "https://api.deepseek.com/v1", keyName: "deepseek" },
@@ -2525,41 +3051,36 @@ function reasonerKey(info, keys) {
2525
3051
  if (info.keyName === "gemini") return keys.gemini || keys.google;
2526
3052
  return keys[info.keyName];
2527
3053
  }
2528
- function resolveReasoner(spec, keys) {
3054
+ function clientFor(info, key, opts) {
3055
+ return info.provider === "gemini" ? new GeminiChatClient(
3056
+ new GeminiClient(key, { zeroStorage: opts.zeroStorage }),
3057
+ info.model
3058
+ ) : new OpenAICompatClient(info.baseUrl, key, info.model, info.provider);
3059
+ }
3060
+ function resolveReasoner(spec, keys, opts = {}) {
2529
3061
  const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
2530
3062
  (s) => !!s
2531
3063
  );
2532
3064
  for (const c of candidates) {
2533
3065
  const info = resolveReasonerInfo(c);
2534
3066
  const key = reasonerKey(info, keys);
2535
- if (key) {
2536
- return {
2537
- client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2538
- info
2539
- };
2540
- }
3067
+ if (key) return { client: clientFor(info, key, opts), info };
2541
3068
  }
2542
3069
  return null;
2543
3070
  }
2544
- function resolveSecondReasoner(first, keys) {
3071
+ function resolveSecondReasoner(first, keys, opts = {}) {
2545
3072
  const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
2546
3073
  for (const c of candidates) {
2547
3074
  const info = resolveReasonerInfo(c);
2548
3075
  if (info.provider === first.provider) continue;
2549
3076
  const key = reasonerKey(info, keys);
2550
- if (key) {
2551
- return {
2552
- client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2553
- info
2554
- };
2555
- }
3077
+ if (key) return { client: clientFor(info, key, opts), info };
2556
3078
  }
2557
3079
  return null;
2558
3080
  }
2559
3081
 
2560
3082
  // src/finalize/finalize.ts
2561
3083
  var MIN_DUR = 0.5;
2562
- var MAX_DUR = 7;
2563
3084
  var OVERLAP_GAP = 0.05;
2564
3085
  function textSimilarity(a, b) {
2565
3086
  const ta = new Set(tokenize(a).map((t) => t.norm));
@@ -2703,16 +3224,14 @@ function fixOverlaps(segments) {
2703
3224
  }
2704
3225
  function clampAndFix(segments) {
2705
3226
  for (const s of segments) {
2706
- const dur = s.end - s.start;
2707
- if (dur < MIN_DUR) s.end = s.start + MIN_DUR;
2708
- else if (dur > MAX_DUR) s.end = s.start + MAX_DUR;
3227
+ if (s.end - s.start < MIN_DUR) s.end = s.start + MIN_DUR;
2709
3228
  }
2710
3229
  return fixOverlaps(segments);
2711
3230
  }
2712
- function finalizeSegments(segments, opts = {}) {
2713
- const minSeg = opts.minSegmentSec ?? 0.2;
2714
- let deduped = dedupSegments(trimSeamOverlaps(segments));
2715
- deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
3231
+ function finalizeSegments(segments) {
3232
+ const deduped = dedupSegments(trimSeamOverlaps(segments)).filter(
3233
+ (s) => s.text.trim().length > 0
3234
+ );
2716
3235
  const out = deduped.map((s, i) => ({
2717
3236
  id: i + 1,
2718
3237
  start: s.start,
@@ -3040,9 +3559,10 @@ async function summarizeTranscript(client, model, result, instructions) {
3040
3559
 
3041
3560
  // src/core/pipeline.ts
3042
3561
  import { basename as basename3, resolve as resolve2 } from "path";
3562
+ import { createHash as createHash3 } from "crypto";
3043
3563
  var JSON_OPTS = { encoding: "utf-8" };
3044
3564
  function readJson(p) {
3045
- if (!existsSync3(p)) return null;
3565
+ if (!existsSync4(p)) return null;
3046
3566
  try {
3047
3567
  return JSON.parse(readFileSync2(p, JSON_OPTS));
3048
3568
  } catch {
@@ -3068,6 +3588,12 @@ async function mapPool(items, limit, fn) {
3068
3588
  function has(passes, p) {
3069
3589
  return passes.includes(p);
3070
3590
  }
3591
+ var ASR_NAMES = {
3592
+ assemblyai: "AssemblyAI",
3593
+ elevenlabs: "ElevenLabs Scribe",
3594
+ "whisper-groq": "Groq Whisper",
3595
+ none: "none"
3596
+ };
3071
3597
  function stageTag(name) {
3072
3598
  return (err) => {
3073
3599
  const msg = err instanceof Error ? err.message : String(err);
@@ -3086,7 +3612,7 @@ async function transcribe(opts) {
3086
3612
  const options = resolveOptions(opts);
3087
3613
  const keys = resolveKeys(options.apiKeys);
3088
3614
  logger.setLevel(options.logLevel);
3089
- if (!existsSync3(options.input)) {
3615
+ if (!existsSync4(options.input)) {
3090
3616
  throw new Error(`Input file not found: ${options.input}`);
3091
3617
  }
3092
3618
  mkdirSync2(options.intermediatesDir, { recursive: true });
@@ -3129,6 +3655,8 @@ async function transcribe(opts) {
3129
3655
  const checkAbort = () => {
3130
3656
  options.signal?.throwIfAborted();
3131
3657
  };
3658
+ const emit = (event) => emitTo(options.onProgress, event);
3659
+ const geminiOpts = { zeroStorage: options.zeroStorage };
3132
3660
  if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
3133
3661
  if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
3134
3662
  const tsProvider = options.timestampedProvider ?? "assemblyai";
@@ -3153,12 +3681,13 @@ async function transcribe(opts) {
3153
3681
  if (has(passes, "preprocess")) {
3154
3682
  checkAbort();
3155
3683
  logger.info("=== preprocess ===");
3684
+ emit({ type: "stage", stage: "preprocess", state: "start" });
3156
3685
  probeInfo = forceAll ? null : readJson(probePath);
3157
3686
  if (!probeInfo) {
3158
3687
  probeInfo = await probe(options.input).catch(stageTag("preprocess"));
3159
3688
  writeJson(probePath, probeInfo);
3160
3689
  }
3161
- if (!existsSync3(audioPath) || forceAll) {
3690
+ if (!existsSync4(audioPath) || forceAll) {
3162
3691
  logger.info("extracting audio (mono 16kHz mp3)...");
3163
3692
  await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
3164
3693
  stageTag("preprocess")
@@ -3166,7 +3695,7 @@ async function transcribe(opts) {
3166
3695
  }
3167
3696
  if (probeInfo.hasVideo) {
3168
3697
  const kfDir = `${options.intermediatesDir}/keyframes`;
3169
- if (!existsSync3(kfDir) || forceAll) {
3698
+ if (!existsSync4(kfDir) || forceAll) {
3170
3699
  logger.info("extracting keyframes...");
3171
3700
  await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
3172
3701
  (err) => {
@@ -3194,14 +3723,120 @@ async function transcribe(opts) {
3194
3723
  logger.info(
3195
3724
  `estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
3196
3725
  );
3726
+ const naming = options.diarizationLevel >= 3 && has(passes, "identify");
3727
+ const reasonerA = naming || options.summary ? resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys, geminiOpts) : null;
3728
+ const reasonerB = naming && reasonerA && options.identifyMode === "dual" ? resolveSecondReasoner(reasonerA.info, keys, geminiOpts) : null;
3729
+ const asksAssemblyAI = willTimestamp && tsProvider === "assemblyai";
3730
+ const notAsked = options.zeroStorage ? [
3731
+ ...willTimestamp && (tsProvider === "elevenlabs" || tsProvider === "whisper-groq") ? [{ name: ASR_NAMES[tsProvider], role: "timing" }] : [],
3732
+ ...[reasonerA, reasonerB].flatMap(
3733
+ (r) => r && r.info.provider !== "gemini" ? [{ name: r.info.model, role: "text" }] : []
3734
+ )
3735
+ ] : [];
3736
+ if (options.zeroStorage) {
3737
+ logger.info(
3738
+ `zero storage: ${asksAssemblyAI ? "Gemini and AssemblyAI are" : "Gemini is"} asked to keep nothing${notAsked.length ? `; ${notAsked.map((p) => p.name).join(", ")} can't be asked` : ""}`
3739
+ );
3740
+ }
3741
+ emit({
3742
+ type: "plan",
3743
+ durationSec: duration,
3744
+ model: models.transcribe,
3745
+ asr: ASR_NAMES[tsProvider],
3746
+ estimateUsd: estimate.totalUsd,
3747
+ zeroStorage: options.zeroStorage,
3748
+ notAsked
3749
+ });
3750
+ const runTimestamped = async () => {
3751
+ if (!has(passes, "timestamped") && !has(passes, "align")) {
3752
+ const cached = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
3753
+ return { result: cached, billed: false };
3754
+ }
3755
+ checkAbort();
3756
+ if (tsProvider === "none") {
3757
+ logger.info("=== timestamped: none (the LLM's own timestamps are used) ===");
3758
+ return { result: null, billed: false };
3759
+ }
3760
+ if (tsProvider === "whisper-groq") {
3761
+ logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
3762
+ if (!existsSync4(audioPath))
3763
+ await extractAudio(options.input, audioPath, AUDIO_OPTS);
3764
+ const groq = new WhisperGroqClient(keys.groq);
3765
+ const result3 = await groq.transcribe(await readFile2(audioPath), { language: options.language }).catch(stageTag("asr"));
3766
+ writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
3767
+ return { result: result3, billed: true };
3768
+ }
3769
+ if (tsProvider === "elevenlabs") {
3770
+ logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
3771
+ const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs${options.language ? `-${options.language}` : ""}.json`;
3772
+ let result3 = forceAll ? null : readJson(cachePath);
3773
+ let billed = false;
3774
+ if (!result3) {
3775
+ const el = new ElevenLabsClient(keys.elevenlabs);
3776
+ result3 = await el.transcribe(await readFile2(audioPath), { languageCode: options.language }).catch(stageTag("asr"));
3777
+ billed = true;
3778
+ writeJson(cachePath, result3);
3779
+ } else {
3780
+ logger.info("[elevenlabs] cache hit");
3781
+ }
3782
+ writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
3783
+ logger.info(
3784
+ `[elevenlabs] ${result3.utterances.length} utterances, ${result3.words.length} words`
3785
+ );
3786
+ return { result: result3, billed };
3787
+ }
3788
+ logger.info("=== timestamped (AssemblyAI) ===");
3789
+ const aai = new AssemblyAIProvider({
3790
+ apiKey: keys.assemblyai,
3791
+ cacheDir: `${options.intermediatesDir}/assemblyai`,
3792
+ language: options.language,
3793
+ zeroStorage: options.zeroStorage
3794
+ });
3795
+ const result2 = await aai.transcribe(audioPath).catch(stageTag("asr"));
3796
+ writeJson(`${options.intermediatesDir}/timestamped.json`, result2);
3797
+ return { result: result2, billed: !aai.lastFromCache };
3798
+ };
3799
+ const asrName = ASR_NAMES[tsProvider];
3800
+ if (willTimestamp && tsProvider !== "none") {
3801
+ emit({ type: "asr", provider: asrName, state: "start" });
3802
+ }
3803
+ const asrRun = runTimestamped().then(
3804
+ (r) => {
3805
+ if (willTimestamp && r.result) {
3806
+ const speakers2 = new Set(r.result.utterances.map((u) => u.speaker)).size;
3807
+ emit({
3808
+ type: "asr",
3809
+ provider: asrName,
3810
+ state: r.billed ? "done" : "cached",
3811
+ words: r.result.words.length,
3812
+ speakers: speakers2 || void 0,
3813
+ language: r.result.languageCode
3814
+ });
3815
+ }
3816
+ return r;
3817
+ },
3818
+ (err) => {
3819
+ emit({
3820
+ type: "asr",
3821
+ provider: asrName,
3822
+ state: "failed",
3823
+ error: err instanceof Error ? err.message : String(err)
3824
+ });
3825
+ throw err;
3826
+ }
3827
+ );
3828
+ asrRun.catch(() => void 0);
3197
3829
  let description = null;
3198
3830
  if (has(passes, "describe")) {
3199
3831
  const descPath = `${options.intermediatesDir}/description.json`;
3200
3832
  description = forceAll ? null : readJson(descPath);
3201
- if (!description) {
3833
+ if (description) {
3834
+ emit({ type: "stage", stage: "describe", state: "cached" });
3835
+ } else {
3202
3836
  checkAbort();
3203
3837
  logger.info("=== describe ===");
3204
- const client = new GeminiClient(keys.gemini);
3838
+ emit({ type: "stage", stage: "describe", state: "start" });
3839
+ const client = new GeminiClient(keys.gemini, geminiOpts);
3205
3840
  const sampleSpans = duration <= 360 ? [[0, duration]] : [
3206
3841
  [0, 150],
3207
3842
  [Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
@@ -3211,17 +3846,17 @@ async function transcribe(opts) {
3211
3846
  for (let i = 0; i < sampleSpans.length; i++) {
3212
3847
  const [s, e] = sampleSpans[i];
3213
3848
  const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
3214
- if (!existsSync3(samplePath) || forceAll) {
3849
+ if (!existsSync4(samplePath) || forceAll) {
3215
3850
  await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
3216
3851
  }
3217
3852
  files.push({ path: samplePath });
3218
3853
  }
3219
3854
  const audioSampleCount = files.length;
3220
3855
  const kfDir = `${options.intermediatesDir}/keyframes`;
3221
- if (existsSync3(kfDir)) {
3856
+ if (existsSync4(kfDir)) {
3222
3857
  for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
3223
3858
  const p = `${kfDir}/${f}`;
3224
- if (existsSync3(p)) files.push({ path: p });
3859
+ if (existsSync4(p)) files.push({ path: p });
3225
3860
  }
3226
3861
  }
3227
3862
  description = await describeMeeting(
@@ -3250,14 +3885,14 @@ async function transcribe(opts) {
3250
3885
  }
3251
3886
  chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
3252
3887
  if (silences.length > 3) {
3253
- chunks = chunks.map((c) => {
3254
- const snapped = snapToSilence(
3888
+ chunks = chunks.map((c) => ({
3889
+ ...c,
3890
+ start: snapToSilence(
3255
3891
  c.start,
3256
3892
  silences,
3257
3893
  Math.min(10, options.chunkOverlapSec / 2)
3258
- );
3259
- return { ...c, start: snapped, trustedStart: snapped + c.overlapWithPrevious };
3260
- });
3894
+ )
3895
+ }));
3261
3896
  }
3262
3897
  }
3263
3898
  const tagWith = (r, chunk) => ({
@@ -3265,20 +3900,25 @@ async function transcribe(opts) {
3265
3900
  segments: r.segments.map((s) => ({
3266
3901
  ...s,
3267
3902
  chunkIndex: chunk.index,
3268
- trustedStart: chunk.trustedStart
3903
+ trustedStart: chunk.trustedStart,
3904
+ chunkStart: chunk.start,
3905
+ chunkEnd: chunk.end
3269
3906
  }))
3270
3907
  });
3908
+ const llmDir = `${options.intermediatesDir}/llm`;
3271
3909
  let llmChunkResults = [];
3910
+ let llmChunkPlans = [];
3272
3911
  if (has(passes, "llm-transcribe")) {
3273
3912
  logger.info("=== llm-transcribe ===");
3913
+ emit({ type: "stage", stage: "transcribe", state: "start" });
3274
3914
  let runChunks = chunks;
3275
3915
  if (options.onlyChunk !== void 0)
3276
3916
  runChunks = chunks.filter((c) => c.index === options.onlyChunk);
3277
3917
  logger.info(
3278
3918
  `${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`
3279
3919
  );
3280
- const client = new GeminiClient(keys.gemini);
3281
- const llmDir = `${options.intermediatesDir}/llm`;
3920
+ emit({ type: "chunks", total: runChunks.length, chunkSec: options.chunkDurationSec });
3921
+ const client = new GeminiClient(keys.gemini, geminiOpts);
3282
3922
  mkdirSync2(llmDir, { recursive: true });
3283
3923
  const partialPath = `${options.outputDir}/${basename3(options.input, ext(options.input))}.partial.md`;
3284
3924
  const completed = [];
@@ -3307,25 +3947,23 @@ ${lines.join("\n\n")}
3307
3947
  const cached = forceAll ? null : readJson(parsedPath);
3308
3948
  if (cached && cached.segments.length > 0) {
3309
3949
  logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
3950
+ emit({
3951
+ type: "chunk",
3952
+ index: chunk.index,
3953
+ state: "cached",
3954
+ segments: cached.segments.length
3955
+ });
3310
3956
  completed.push(cached);
3311
3957
  return tagWith(cached, chunk);
3312
3958
  }
3313
3959
  const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
3314
- if (!existsSync3(chunkPath) || forceAll) {
3960
+ if (!existsSync4(chunkPath) || forceAll) {
3315
3961
  await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
3316
3962
  }
3317
- let previousTail;
3318
- if (chunk.index > 0) {
3319
- const prev = readJson(
3320
- `${llmDir}/chunk_${String(chunk.index - 1).padStart(2, "0")}_parsed.json`
3321
- );
3322
- if (prev && prev.segments.length) {
3323
- previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
3324
- }
3325
- }
3326
3963
  logger.info(
3327
3964
  `chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`
3328
3965
  );
3966
+ emit({ type: "chunk", index: chunk.index, state: "running" });
3329
3967
  const result2 = await transcribeChunk(
3330
3968
  client,
3331
3969
  models.transcribe,
@@ -3336,12 +3974,19 @@ ${lines.join("\n\n")}
3336
3974
  total: runChunks.length,
3337
3975
  description: description?.description,
3338
3976
  roster: description?.roster,
3339
- previousTail,
3340
3977
  instructions: options.instructions
3341
3978
  },
3342
3979
  { chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
3343
3980
  );
3344
3981
  writeJson(parsedPath, result2);
3982
+ emit(
3983
+ result2.error && result2.segments.length === 0 ? { type: "chunk", index: chunk.index, state: "failed", error: result2.error } : {
3984
+ type: "chunk",
3985
+ index: chunk.index,
3986
+ state: "done",
3987
+ segments: result2.segments.length
3988
+ }
3989
+ );
3345
3990
  writeFileSync2(
3346
3991
  `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
3347
3992
  result2.raw
@@ -3350,6 +3995,7 @@ ${lines.join("\n\n")}
3350
3995
  writePartial();
3351
3996
  return tagWith(result2, chunk);
3352
3997
  });
3998
+ llmChunkPlans = runChunks;
3353
3999
  const errored = llmChunkResults.filter((r) => r.error);
3354
4000
  const producedSegments = llmChunkResults.reduce((n, r) => n + r.segments.length, 0);
3355
4001
  if (llmChunkResults.length > 0 && producedSegments === 0 && errored.length === llmChunkResults.length) {
@@ -3358,16 +4004,118 @@ ${lines.join("\n\n")}
3358
4004
  );
3359
4005
  }
3360
4006
  } else {
3361
- const llmDir = `${options.intermediatesDir}/llm`;
3362
- if (!forceAll && existsSync3(llmDir)) {
3363
- const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
3364
- llmChunkResults = files.map((f, i) => {
3365
- const r = readJson(`${llmDir}/${f}`);
3366
- return r && chunks[i] ? tagWith(r, chunks[i]) : r;
3367
- }).filter(Boolean);
4007
+ if (!forceAll && existsSync4(llmDir)) {
4008
+ for (const f of readdirSync(llmDir).sort()) {
4009
+ const m = /^chunk_(\d+)_parsed\.json$/.exec(f);
4010
+ const plan = m ? chunks.find((c) => c.index === Number(m[1])) : void 0;
4011
+ const r = plan ? readJson(`${llmDir}/${f}`) : null;
4012
+ if (r && plan) {
4013
+ llmChunkResults.push(tagWith(r, plan));
4014
+ llmChunkPlans.push(plan);
4015
+ }
4016
+ }
4017
+ }
4018
+ }
4019
+ const { result: asrResult, billed: asrBilled } = await asrRun;
4020
+ const quality = [];
4021
+ if (asrResult?.words.length) {
4022
+ let client;
4023
+ for (let i = 0; i < llmChunkResults.length; i++) {
4024
+ const plan = llmChunkPlans[i];
4025
+ const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
4026
+ let cov = chunkCoverage(
4027
+ llmChunkResults[i].segments,
4028
+ asrResult.words,
4029
+ plan.start,
4030
+ plan.end
4031
+ );
4032
+ let status = cov.low ? "low-coverage" : "ok";
4033
+ if (cov.low) {
4034
+ const retryPath = `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}_retry_parsed.json`;
4035
+ let retry = forceAll ? null : readJson(retryPath);
4036
+ const span = { index: plan.index, startSec: plan.start, endSec: plan.end };
4037
+ if (!retry && has(passes, "llm-transcribe")) {
4038
+ checkAbort();
4039
+ logger.warn(
4040
+ `${where}: ${cov.llmWords} words transcribed where the ASR heard ${cov.asrWords} \u2014 transcribing it again in two halves`
4041
+ );
4042
+ emit({
4043
+ type: "guard",
4044
+ ...span,
4045
+ state: "retrying",
4046
+ llmWords: cov.llmWords,
4047
+ asrWords: cov.asrWords
4048
+ });
4049
+ client ??= new GeminiClient(keys.gemini, geminiOpts);
4050
+ retry = await transcribeInHalves({
4051
+ client,
4052
+ model: models.transcribe,
4053
+ audioPath,
4054
+ chunk: plan,
4055
+ pathPrefix: `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}`,
4056
+ ctx: {
4057
+ index: plan.index + 1,
4058
+ total: chunks.length,
4059
+ description: description?.description,
4060
+ roster: description?.roster,
4061
+ instructions: options.instructions
4062
+ },
4063
+ audioOpts: AUDIO_OPTS
4064
+ }).catch(stageTag("llm-transcribe"));
4065
+ writeJson(retryPath, retry);
4066
+ }
4067
+ if (retry) {
4068
+ const again = chunkCoverage(
4069
+ retry.segments,
4070
+ asrResult.words,
4071
+ plan.start,
4072
+ plan.end
4073
+ );
4074
+ logger.info(
4075
+ `${where}: the halves cover ${again.llmWords} words (${again.ratio.toFixed(2)} per ASR word, was ${cov.ratio.toFixed(2)})${again.ratio > cov.ratio ? " \u2014 kept" : " \u2014 first attempt kept"}`
4076
+ );
4077
+ const kept = again.ratio > cov.ratio;
4078
+ emit({
4079
+ type: "guard",
4080
+ ...span,
4081
+ state: kept ? "recovered" : "unchanged",
4082
+ llmWords: cov.llmWords,
4083
+ asrWords: cov.asrWords,
4084
+ retryWords: again.llmWords
4085
+ });
4086
+ if (kept) {
4087
+ llmChunkResults[i] = tagWith(retry, plan);
4088
+ cov = again;
4089
+ status = again.low ? "low-coverage" : "retried";
4090
+ }
4091
+ }
4092
+ }
4093
+ quality.push({
4094
+ chunk: plan.index,
4095
+ start: plan.start,
4096
+ end: plan.end,
4097
+ status,
4098
+ llmWords: cov.llmWords,
4099
+ asrWords: cov.asrWords,
4100
+ coverage: Number.isFinite(cov.ratio) ? Number(cov.ratio.toFixed(2)) : null
4101
+ });
3368
4102
  }
3369
4103
  }
4104
+ const whole = asrResult?.words.length ? chunkCoverage(
4105
+ llmChunkResults.flatMap((r) => r.segments),
4106
+ asrResult.words,
4107
+ 0,
4108
+ Infinity
4109
+ ) : null;
4110
+ const asrMissedSpeech = !!whole && whole.llmWords >= 200 && whole.ratio > 3;
4111
+ if (asrMissedSpeech) {
4112
+ logger.warn(
4113
+ `the ASR (${tsProvider}) heard ${whole.asrWords} words where the transcript has ${whole.llmWords} \u2014 the recording may be in a language it didn't expect, so timings come from the LLM; re-run with --language <code> (e.g. ko, ml, hi)`
4114
+ );
4115
+ }
3370
4116
  let allLlmSegments = llmChunkResults.flatMap((r) => r.segments);
4117
+ const timingWords = asrMissedSpeech ? [] : asrResult?.words ?? [];
4118
+ allLlmSegments = toAsrClock(allLlmSegments, timingWords);
3371
4119
  const beforePart = allLlmSegments.length;
3372
4120
  allLlmSegments = partitionByOwnership(allLlmSegments);
3373
4121
  if (beforePart !== allLlmSegments.length) {
@@ -3376,81 +4124,68 @@ ${lines.join("\n\n")}
3376
4124
  );
3377
4125
  }
3378
4126
  logger.info(`total LLM segments: ${allLlmSegments.length}`);
3379
- let asrResult = null;
3380
- if (has(passes, "timestamped") || has(passes, "align")) {
3381
- checkAbort();
3382
- const provider = options.timestampedProvider ?? "assemblyai";
3383
- if (provider === "whisper-groq") {
3384
- logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
3385
- if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
3386
- if (!existsSync3(audioPath) || forceAll) {
3387
- await extractAudio(options.input, audioPath, AUDIO_OPTS);
4127
+ if (asrResult?.words.length && (has(passes, "align") || has(passes, "consistency"))) {
4128
+ const dropped = /* @__PURE__ */ new Set();
4129
+ for (let i = 0; i < llmChunkResults.length; i++) {
4130
+ const r = llmChunkResults[i];
4131
+ const plan = llmChunkPlans[i];
4132
+ const q = quality.find((x) => x.chunk === plan.index);
4133
+ const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
4134
+ const compression = maxCompressionRatio(r.segments.map((s) => s.text).join(" "));
4135
+ if (compression > DEGENERATE_COMPRESSION_RATIO) {
4136
+ dropped.add(plan.index);
4137
+ if (q) q.status = "dropped-loop";
4138
+ logger.warn(
4139
+ `${where}: dropping repetition-loop text (compression ratio ${compression.toFixed(1)}) \u2014 ASR will fill this range`
4140
+ );
4141
+ continue;
3388
4142
  }
3389
- const { readFile: readFile2 } = await import("fs/promises");
3390
- const buf = await readFile2(audioPath);
3391
- const groq = new WhisperGroqClient(keys.groq);
3392
- asrResult = await groq.transcribe(buf).catch(stageTag("asr"));
3393
- writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3394
- } else if (provider === "elevenlabs") {
3395
- logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
3396
- if (!keys.elevenlabs)
3397
- throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3398
- const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs.json`;
3399
- asrResult = forceAll ? null : readJson(cachePath);
3400
- if (!asrResult) {
3401
- const { readFile: readFile2 } = await import("fs/promises");
3402
- const buf = await readFile2(audioPath);
3403
- const el = new ElevenLabsClient(keys.elevenlabs);
3404
- asrResult = await el.transcribe(buf).catch(stageTag("asr"));
3405
- writeJson(cachePath, asrResult);
3406
- } else {
3407
- logger.info("[elevenlabs] cache hit");
4143
+ const g = chunkGrounding(r.segments, asrResult.words, plan.start, plan.end);
4144
+ if (!g.grounded) {
4145
+ if (q) q.ungrounded = true;
4146
+ logger.warn(
4147
+ `${where}: only ${Math.round(g.precision * 100)}% of ${g.llmTokens} content words were also heard by the ASR \u2014 check this stretch (kept as transcribed)`
4148
+ );
3408
4149
  }
3409
- writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3410
- logger.info(
3411
- `[elevenlabs] ${asrResult.utterances.length} utterances, ${asrResult.words.length} words, ${asrResult.speakers?.length ?? "?"} speakers`
4150
+ }
4151
+ if (dropped.size) {
4152
+ allLlmSegments = allLlmSegments.filter(
4153
+ (s) => s.chunkIndex === void 0 || !dropped.has(s.chunkIndex)
3412
4154
  );
3413
- } else {
3414
- logger.info("=== timestamped (AssemblyAI) ===");
3415
- if (!keys.assemblyai)
3416
- throw new Error(
3417
- "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
3418
- );
3419
- const aai = new AssemblyAIProvider({
3420
- apiKey: keys.assemblyai,
3421
- cacheDir: `${options.intermediatesDir}/assemblyai`
3422
- });
3423
- asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
3424
- writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3425
4155
  }
3426
- } else {
3427
- asrResult = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
3428
4156
  }
3429
4157
  let aligned = [];
3430
- if (has(passes, "align") && asrResult) {
4158
+ if (has(passes, "align") && (asrResult || tsProvider === "none")) {
3431
4159
  logger.info("=== align ===");
3432
- aligned = alignSegments(allLlmSegments, asrResult.words, { timeMarginSec: 30 });
4160
+ emit({ type: "stage", stage: "align", state: "start" });
4161
+ aligned = alignSegments(allLlmSegments, timingWords, { timeMarginSec: 30 });
3433
4162
  writeJson(`${options.intermediatesDir}/aligned.json`, aligned);
3434
4163
  } else {
3435
4164
  aligned = (forceAll ? null : readJson(`${options.intermediatesDir}/aligned.json`)) ?? [];
3436
4165
  }
3437
4166
  const alignedOk = aligned.filter((a) => a.timingSource !== "coarse").length;
3438
4167
  logger.info(`aligned: ${alignedOk}/${aligned.length} with ASR timing`);
3439
- if (asrResult && (has(passes, "align") || has(passes, "consistency"))) {
3440
- const before = aligned.length;
4168
+ let gapFilledWords = 0;
4169
+ if (asrResult && !asrMissedSpeech && (has(passes, "align") || has(passes, "consistency"))) {
3441
4170
  aligned = fillAsrGaps(aligned, asrResult.words, asrResult.utterances);
3442
- const added = aligned.length - before;
3443
- if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
4171
+ const added = aligned.filter((a) => a.timingSource === "timestamped");
4172
+ gapFilledWords = added.reduce((n, a) => n + a.words.length, 0);
4173
+ if (added.length) {
4174
+ logger.info(
4175
+ `gap-filled ${added.length} ASR fallback segment(s) (${gapFilledWords} words)`
4176
+ );
4177
+ }
3444
4178
  }
3445
4179
  if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
3446
4180
  aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
3447
4181
  }
3448
4182
  let segments = aligned;
3449
4183
  let speakers = [];
3450
- if (has(passes, "consistency") && asrResult) {
4184
+ if (has(passes, "consistency") && (asrResult || tsProvider === "none")) {
3451
4185
  logger.info("=== consistency ===");
3452
- const cons = assignGlobalSpeakers(aligned, asrResult.utterances, {
3453
- hasDiarization: asrResult.hasDiarization ?? true
4186
+ emit({ type: "stage", stage: "speakers", state: "start" });
4187
+ const cons = assignGlobalSpeakers(aligned, asrResult?.utterances ?? [], {
4188
+ hasDiarization: asrResult ? asrResult.hasDiarization ?? true : false
3454
4189
  });
3455
4190
  segments = cons.segments;
3456
4191
  speakers = cons.speakers;
@@ -3472,19 +4207,22 @@ ${lines.join("\n\n")}
3472
4207
  (s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
3473
4208
  );
3474
4209
  speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
3475
- if (options.diarizationLevel >= 3 && has(passes, "identify")) {
3476
- const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
4210
+ if (naming) {
3477
4211
  if (!reasonerA) {
3478
4212
  logger.warn(
3479
4213
  "identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
3480
4214
  );
3481
4215
  } else {
3482
4216
  const mode = options.identifyMode;
3483
- const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
3484
4217
  const idConfig = {
3485
4218
  mode,
3486
4219
  reasonerA: reasonerA.info.model,
3487
- reasonerB: reasonerB?.info.model ?? null
4220
+ reasonerB: reasonerB?.info.model ?? null,
4221
+ knownSpeakers: options.knownSpeakers ?? [],
4222
+ // What the naming step reads. If a re-run changes the transcript (a re-transcribed
4223
+ // chunk can reorder speakers by talk time), "Speaker A" may now be the other voice,
4224
+ // and the cached names must not be applied to it.
4225
+ inputs: createHash3("sha1").update(JSON.stringify(segments.map((s) => [s.speaker, s.text]))).update(JSON.stringify(speakers.map((sp) => sp.id))).digest("hex")
3488
4226
  };
3489
4227
  const idCachePath = `${options.intermediatesDir}/identified.json`;
3490
4228
  const cachedId = forceAll ? null : readJson(
@@ -3494,11 +4232,18 @@ ${lines.join("\n\n")}
3494
4232
  let nameMap = null;
3495
4233
  if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
3496
4234
  logger.info("=== identify (cached) ===");
4235
+ emit({ type: "stage", stage: "identify", state: "cached" });
3497
4236
  nameMap = cachedId.nameMap;
3498
4237
  } else {
3499
4238
  logger.info(
3500
4239
  `=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
3501
4240
  );
4241
+ emit({
4242
+ type: "stage",
4243
+ stage: "identify",
4244
+ state: "start",
4245
+ detail: reasonerB ? `${reasonerA.info.model} + ${reasonerB.info.model}` : reasonerA.info.model
4246
+ });
3502
4247
  checkAbort();
3503
4248
  const id = await identifySpeakersV2(
3504
4249
  {
@@ -3523,11 +4268,14 @@ ${lines.join("\n\n")}
3523
4268
  ).catch(stageTag("identify"));
3524
4269
  writeJson(idCachePath, { ...id, config: idConfig });
3525
4270
  nameMap = id.nameMap;
4271
+ if (id.allPassesFailed)
4272
+ emit({ type: "stage", stage: "identify", state: "failed" });
3526
4273
  }
3527
4274
  logger.info(
3528
4275
  `identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
3529
4276
  );
3530
4277
  const nm = nameMap;
4278
+ emit({ type: "names", names: nm });
3531
4279
  segments = segments.map(
3532
4280
  (s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
3533
4281
  );
@@ -3537,13 +4285,14 @@ ${lines.join("\n\n")}
3537
4285
  let finalSegments = [];
3538
4286
  if (has(passes, "finalize")) {
3539
4287
  logger.info("=== finalize ===");
4288
+ emit({ type: "stage", stage: "finalize", state: "start" });
3540
4289
  finalSegments = finalizeSegments(segments);
3541
4290
  writeJson(`${options.intermediatesDir}/final.json`, finalSegments);
3542
4291
  } else {
3543
4292
  finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
3544
4293
  }
3545
4294
  logger.info(`final segments: ${finalSegments.length}`);
3546
- const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
4295
+ const receipt = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
3547
4296
  const wallMs = Date.now() - runStartedAt;
3548
4297
  const metadata = {
3549
4298
  sourceFile: options.input,
@@ -3563,86 +4312,103 @@ ${lines.join("\n\n")}
3563
4312
  llmCalls: receipt.totals.calls,
3564
4313
  inputTokens: receipt.totals.inputTokens,
3565
4314
  outputTokens: receipt.totals.outputTokens
3566
- }
4315
+ },
4316
+ ...asrResult ? { quality: { chunks: quality, gapFilledWords, asrMissedSpeech } } : {},
4317
+ zeroStorage: options.zeroStorage
3567
4318
  };
4319
+ const degraded = quality.filter((q) => q.status !== "ok");
4320
+ if (degraded.length || asrMissedSpeech) {
4321
+ logger.warn(
4322
+ `quality: ${degraded.map((q) => `chunk ${q.chunk} ${q.status}`).join(", ") || "all chunks ok"}${asrMissedSpeech ? " \xB7 the ASR missed most of the speech" : ""} \xB7 ${gapFilledWords} words filled from the ASR`
4323
+ );
4324
+ }
3568
4325
  const result = { segments: finalSegments, speakers, metadata };
3569
4326
  writeJson(`${options.intermediatesDir}/result.json`, result);
4327
+ const base = basename3(options.input, ext(options.input));
4328
+ const written = [];
4329
+ const write = (name, content) => {
4330
+ const path = `${options.outputDir}/${name}`;
4331
+ writeFileSync2(path, content);
4332
+ written.push(resolve2(path));
4333
+ };
3570
4334
  for (const fmt of options.formats) {
3571
- const base = basename3(options.input, ext(options.input));
3572
- if (fmt === "srt")
3573
- writeFileSync2(
3574
- `${options.outputDir}/${base}.srt`,
3575
- formatSrt(result, { title: base })
3576
- );
4335
+ if (fmt === "srt") write(`${base}.srt`, formatSrt(result, { title: base }));
3577
4336
  if (fmt === "md")
3578
- writeFileSync2(
3579
- `${options.outputDir}/${base}.md`,
4337
+ write(
4338
+ `${base}.md`,
3580
4339
  formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
3581
4340
  );
3582
- if (fmt === "txt")
3583
- writeFileSync2(
3584
- `${options.outputDir}/${base}.txt`,
3585
- formatText(result, { title: base })
3586
- );
3587
- if (fmt === "html")
3588
- writeFileSync2(
3589
- `${options.outputDir}/${base}.html`,
3590
- formatHtml(result, { title: base })
3591
- );
3592
- if (fmt === "json")
3593
- writeFileSync2(`${options.outputDir}/${base}.json`, formatJson(result));
4341
+ if (fmt === "txt") write(`${base}.txt`, formatText(result, { title: base }));
4342
+ if (fmt === "html") write(`${base}.html`, formatHtml(result, { title: base }));
4343
+ if (fmt === "json") write(`${base}.json`, formatJson(result));
3594
4344
  }
3595
4345
  if (options.summary && finalSegments.length > 0) {
3596
- const reasoner = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
3597
- if (!reasoner) {
4346
+ if (!reasonerA) {
3598
4347
  logger.warn("summary: no reasoner-capable key \u2014 skipping");
3599
4348
  } else {
3600
- logger.info(`=== summary (${reasoner.info.model}) ===`);
4349
+ logger.info(`=== summary (${reasonerA.info.model}) ===`);
4350
+ emit({
4351
+ type: "stage",
4352
+ stage: "summary",
4353
+ state: "start",
4354
+ detail: reasonerA.info.model
4355
+ });
3601
4356
  try {
3602
4357
  const summary = await summarizeTranscript(
3603
- reasoner.client,
3604
- reasoner.info.model,
4358
+ reasonerA.client,
4359
+ reasonerA.info.model,
3605
4360
  result,
3606
4361
  options.instructions
3607
4362
  );
3608
- const base = basename3(options.input, ext(options.input));
3609
- writeFileSync2(`${options.outputDir}/${base}.summary.md`, summary);
4363
+ write(`${base}.summary.md`, summary);
3610
4364
  logger.info(`summary written to ${base}.summary.md`);
3611
4365
  } catch (err) {
3612
4366
  logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
4367
+ emit({ type: "stage", stage: "summary", state: "failed" });
3613
4368
  }
3614
4369
  }
3615
4370
  }
3616
4371
  try {
3617
- const base = basename3(options.input, ext(options.input));
3618
4372
  const partial = `${options.outputDir}/${base}.partial.md`;
3619
- if (existsSync3(partial)) (await import("fs/promises")).unlink(partial);
4373
+ if (existsSync4(partial)) (await import("fs/promises")).unlink(partial);
3620
4374
  } catch {
3621
4375
  }
3622
4376
  logger.info(`outputs written to ${options.outputDir}`);
3623
- const mins = Math.floor(wallMs / 6e4);
3624
- const secs = Math.round(wallMs % 6e4 / 1e3);
4377
+ const spent = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
4378
+ const runMs = Date.now() - runStartedAt;
4379
+ const mins = Math.floor(runMs / 6e4);
4380
+ const secs = Math.round(runMs % 6e4 / 1e3);
3625
4381
  logger.info(
3626
- `receipt: ${receipt.totals.calls} LLM calls \xB7 ${(receipt.totals.inputTokens / 1e3).toFixed(0)}k in / ${(receipt.totals.outputTokens / 1e3).toFixed(0)}k out \xB7 ~$${receipt.totalUsd.toFixed(2)}${receipt.incomplete ? " (+unpriced)" : ""} \xB7 ${mins ? `${mins}m` : ""}${secs}s`
4382
+ `receipt: ${spent.totals.calls} LLM calls \xB7 ${(spent.totals.inputTokens / 1e3).toFixed(0)}k in / ${(spent.totals.outputTokens / 1e3).toFixed(0)}k out \xB7 ~$${spent.totalUsd.toFixed(2)}${spent.incomplete ? " (+unpriced)" : ""} \xB7 ${mins ? `${mins}m` : ""}${secs}s`
3627
4383
  );
3628
- for (const line of receipt.lines) logger.info(` ${line}`);
4384
+ for (const line of spent.lines) logger.info(` ${line}`);
3629
4385
  recordRun(
3630
4386
  {
3631
4387
  ts: (/* @__PURE__ */ new Date()).toISOString(),
3632
4388
  input: basename3(options.input),
3633
4389
  durationSec: duration,
3634
- wallMs,
4390
+ wallMs: runMs,
3635
4391
  models: metadata.models,
3636
4392
  segments: finalSegments.length,
3637
4393
  characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
3638
4394
  speakers: speakers.length,
3639
- llmCalls: receipt.totals.calls,
3640
- inputTokens: receipt.totals.inputTokens,
3641
- outputTokens: receipt.totals.outputTokens,
3642
- costUsd: receipt.totalUsd
4395
+ llmCalls: spent.totals.calls,
4396
+ inputTokens: spent.totals.inputTokens,
4397
+ outputTokens: spent.totals.outputTokens,
4398
+ costUsd: spent.totalUsd
3643
4399
  },
3644
- receipt.perModel
4400
+ spent.perModel
3645
4401
  );
4402
+ emit({
4403
+ type: "done",
4404
+ segments: finalSegments.length,
4405
+ speakers: speakers.length,
4406
+ durationSec: duration,
4407
+ costUsd: spent.totalUsd,
4408
+ wallMs: runMs,
4409
+ retriedChunks: quality.filter((q) => q.status === "retried").length,
4410
+ outputs: written
4411
+ });
3646
4412
  return result;
3647
4413
  }
3648
4414
  function ext(p) {
@@ -3680,6 +4446,9 @@ function parseSrt(content) {
3680
4446
  return entries;
3681
4447
  }
3682
4448
  export {
4449
+ DEFAULT_REASONER_MODEL,
4450
+ DEFAULT_TRANSCRIBE_MODEL,
4451
+ PRO_TRANSCRIBE_MODEL,
3683
4452
  alignSegments,
3684
4453
  assignGlobalSpeakers,
3685
4454
  finalizeSegments,
@@ -3689,6 +4458,7 @@ export {
3689
4458
  formatSrt,
3690
4459
  formatText,
3691
4460
  identifySpeakers,
4461
+ identifySpeakersV2,
3692
4462
  parseSrt,
3693
4463
  planChunks,
3694
4464
  summarizeTranscript,