offmute-v2 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,6 +30,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
+ DEFAULT_REASONER_MODEL: () => DEFAULT_REASONER_MODEL,
34
+ DEFAULT_TRANSCRIBE_MODEL: () => DEFAULT_TRANSCRIBE_MODEL,
35
+ PRO_TRANSCRIBE_MODEL: () => PRO_TRANSCRIBE_MODEL,
33
36
  alignSegments: () => alignSegments,
34
37
  assignGlobalSpeakers: () => assignGlobalSpeakers,
35
38
  finalizeSegments: () => finalizeSegments,
@@ -39,6 +42,7 @@ __export(src_exports, {
39
42
  formatSrt: () => formatSrt,
40
43
  formatText: () => formatText,
41
44
  identifySpeakers: () => identifySpeakers,
45
+ identifySpeakersV2: () => identifySpeakersV2,
42
46
  parseSrt: () => parseSrt,
43
47
  planChunks: () => planChunks,
44
48
  summarizeTranscript: () => summarizeTranscript,
@@ -47,7 +51,13 @@ __export(src_exports, {
47
51
  module.exports = __toCommonJS(src_exports);
48
52
 
49
53
  // src/core/pipeline.ts
50
- var import_node_fs5 = require("fs");
54
+ var import_node_fs6 = require("fs");
55
+ var import_promises3 = require("fs/promises");
56
+
57
+ // src/core/models.ts
58
+ var DEFAULT_TRANSCRIBE_MODEL = "gemini-4-hydrogen";
59
+ var PRO_TRANSCRIBE_MODEL = "gemini-4-argon";
60
+ var DEFAULT_REASONER_MODEL = "deepseek-chat";
51
61
 
52
62
  // src/core/config.ts
53
63
  var import_node_crypto = require("crypto");
@@ -63,19 +73,6 @@ var DEFAULT_PASSES = [
63
73
  "consistency",
64
74
  "finalize"
65
75
  ];
66
- var MODELS = {
67
- gemini25Pro: "gemini-2.5-pro",
68
- gemini25Flash: "gemini-2.5-flash",
69
- gemini3Pro: "gemini-3-pro-preview",
70
- gemini31Pro: "gemini-3.1-pro-preview",
71
- geminiFlashLatest: "gemini-flash-latest",
72
- deepseek: "deepseek-chat",
73
- deepseekReasoner: "deepseek-reasoner",
74
- gpt4o: "gpt-4o",
75
- claudeSonnet: "claude-sonnet-4-5"
76
- };
77
- var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini31Pro;
78
- var DEFAULT_REASONER_MODEL = MODELS.deepseek;
79
76
  function resolveKeys(injected) {
80
77
  const env = process.env;
81
78
  return {
@@ -127,19 +124,22 @@ function resolveOptions(opts) {
127
124
  model: opts.model,
128
125
  reasoner: opts.reasoner,
129
126
  timestampedProvider: opts.timestampedProvider,
127
+ language: opts.language,
130
128
  force: opts.force ?? false,
131
129
  onlyChunk: opts.onlyChunk,
132
130
  showProgress: opts.showProgress ?? true,
133
131
  llmLog: opts.llmLog ?? true,
134
132
  logLevel: opts.logLevel ?? "info",
135
- signal: opts.signal
133
+ signal: opts.signal,
134
+ onProgress: opts.onProgress,
135
+ zeroStorage: opts.zeroStorage ?? true
136
136
  };
137
137
  }
138
- function deriveIntermediatesDir(input) {
138
+ function deriveIntermediatesDir(input, parent = (0, import_node_os.tmpdir)()) {
139
139
  const abs = (0, import_node_path.resolve)(input);
140
140
  const hash = (0, import_node_crypto.createHash)("sha1").update(abs).digest("hex").slice(0, 8);
141
141
  const base = (0, import_node_path.basename)(input, extOf(input)) || "input";
142
- return `${(0, import_node_os.tmpdir)()}/offmute-v2-${base}-${hash}`;
142
+ return (0, import_node_path.join)(parent, `offmute-v2-${base}-${hash}`);
143
143
  }
144
144
  function extOf(p) {
145
145
  const i = p.lastIndexOf(".");
@@ -159,9 +159,7 @@ function inputSignature(input) {
159
159
  function configSignature(o) {
160
160
  const relevant = {
161
161
  model: o.model ?? DEFAULT_TRANSCRIBE_MODEL,
162
- reasoner: o.reasoner ?? DEFAULT_REASONER_MODEL,
163
162
  instructions: o.instructions ?? "",
164
- knownSpeakers: o.knownSpeakers ?? [],
165
163
  chunkDurationSec: o.chunkDurationSec ?? 600,
166
164
  chunkOverlapSec: o.chunkOverlapSec ?? 60,
167
165
  screenshotCount: o.screenshotCount ?? 6,
@@ -197,6 +195,15 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
197
195
  return chunks;
198
196
  }
199
197
 
198
+ // src/core/progress.ts
199
+ function emitTo(listener, event) {
200
+ if (!listener) return;
201
+ try {
202
+ listener(event);
203
+ } catch {
204
+ }
205
+ }
206
+
200
207
  // src/utils/logger.ts
201
208
  var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
202
209
  var currentLevel = "info";
@@ -498,6 +505,38 @@ async function withRetry(label, fn, opts = {}) {
498
505
  throw lastErr;
499
506
  }
500
507
 
508
+ // src/providers/gemini-usage.ts
509
+ function usageFromMetadata(meta) {
510
+ const thoughtTokens = meta?.thoughtsTokenCount ?? 0;
511
+ return {
512
+ inputTokens: meta?.promptTokenCount ?? 0,
513
+ outputTokens: (meta?.candidatesTokenCount ?? 0) + thoughtTokens,
514
+ thoughtTokens,
515
+ totalTokens: meta?.totalTokenCount ?? 0
516
+ };
517
+ }
518
+
519
+ // src/providers/gemini-models.ts
520
+ function resolveThinking(model) {
521
+ const m = model.toLowerCase();
522
+ if (m.includes("gemini-2.0")) return void 0;
523
+ if (m.includes("gemini-4")) return { thinkingLevel: "LOW" };
524
+ if (m.includes("gemini-2.5")) {
525
+ return { thinkingBudget: m.includes("pro") ? 128 : 0 };
526
+ }
527
+ if (m.includes("-latest")) return { thinkingLevel: "LOW" };
528
+ if (m.includes("gemini-3"))
529
+ return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
530
+ return void 0;
531
+ }
532
+ function fallbackThinking(rejected) {
533
+ return rejected.thinkingLevel === "MINIMAL" ? { thinkingLevel: "LOW" } : void 0;
534
+ }
535
+ function isThinkingConfigError(message) {
536
+ if (!message) return false;
537
+ return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
538
+ }
539
+
501
540
  // src/providers/gemini.ts
502
541
  var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
503
542
  var originalWarn = console.warn.bind(console);
@@ -526,25 +565,15 @@ function detectMime(path) {
526
565
  return MIME_BY_EXT[ext2] ?? "application/octet-stream";
527
566
  }
528
567
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
529
- function resolveThinking(model) {
530
- const m = model.toLowerCase();
531
- if (m.includes("gemini-2.0")) return void 0;
532
- if (m.includes("gemini-2.5")) {
533
- return { thinkingBudget: m.includes("pro") ? 128 : 0 };
534
- }
535
- if (m.includes("gemini-3") || m.includes("flash-latest") || m.includes("pro-latest")) {
536
- return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
537
- }
538
- return void 0;
539
- }
540
- function isThinkingConfigError(message) {
541
- if (!message) return false;
542
- return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
543
- }
544
568
  var GeminiClient = class {
545
569
  ai;
546
- constructor(apiKey) {
547
- this.ai = new import_genai.GoogleGenAI({ apiKey });
570
+ zeroStorage;
571
+ constructor(apiKey, opts = {}) {
572
+ this.ai = new import_genai.GoogleGenAI({
573
+ apiKey,
574
+ ...opts.baseUrl ? { httpOptions: { baseUrl: opts.baseUrl } } : {}
575
+ });
576
+ this.zeroStorage = opts.zeroStorage ?? true;
548
577
  }
549
578
  /** Upload a file and wait until it's done processing. Uploads ride one long HTTP
550
579
  * request each — the retry loop in generate() doesn't cover them, and transient
@@ -587,12 +616,15 @@ var GeminiClient = class {
587
616
  maxOutputTokens,
588
617
  temperature
589
618
  };
619
+ if (this.zeroStorage) config.store = false;
590
620
  if (responseSchema) {
591
621
  config.responseMimeType = "application/json";
592
622
  config.responseSchema = responseSchema;
623
+ } else if (opts.responseJson) {
624
+ config.responseMimeType = "application/json";
593
625
  }
594
626
  if (systemInstruction) config.systemInstruction = systemInstruction;
595
- const thinking = resolveThinking(model);
627
+ let thinking = resolveThinking(model);
596
628
  if (thinking) config.thinkingConfig = thinking;
597
629
  const parts = uploaded.map((f) => ({
598
630
  fileData: { fileUri: f.uri, mimeType: f.mimeType }
@@ -602,21 +634,31 @@ var GeminiClient = class {
602
634
  for (let attempt = 0; attempt < maxRetries; attempt++) {
603
635
  const t0 = Date.now();
604
636
  try {
605
- const response = await this.ai.models.generateContent({
637
+ const controller = new AbortController();
638
+ const stream = await this.ai.models.generateContentStream({
606
639
  model,
607
640
  contents: [{ role: "user", parts }],
608
- config
641
+ config: { ...config, abortSignal: controller.signal }
609
642
  });
610
- const usage = response.usageMetadata || {};
611
- const text = response.text ?? "";
612
- const result = {
613
- text,
614
- usage: {
615
- inputTokens: usage.promptTokenCount ?? 0,
616
- outputTokens: usage.candidatesTokenCount ?? 0,
617
- totalTokens: usage.totalTokenCount ?? 0
643
+ let text = "";
644
+ let usageMeta;
645
+ let abortReason = null;
646
+ for await (const chunk of stream) {
647
+ text += chunk.text ?? "";
648
+ if (chunk.usageMetadata) usageMeta = chunk.usageMetadata;
649
+ abortReason = opts.shouldAbort?.(text) ?? null;
650
+ if (abortReason) {
651
+ controller.abort();
652
+ break;
618
653
  }
619
- };
654
+ }
655
+ const usage = usageFromMetadata(usageMeta);
656
+ const error = abortReason ? `aborted: ${abortReason}` : void 0;
657
+ if (error) {
658
+ logger.warn(
659
+ `[gemini] ${opts.logKind ?? "call"}${opts.logChunk !== void 0 ? ` chunk ${opts.logChunk}` : ""} ${error} after ${text.length} chars`
660
+ );
661
+ }
620
662
  logLlmCall({
621
663
  ts: new Date(t0).toISOString(),
622
664
  provider: "gemini",
@@ -625,18 +667,22 @@ var GeminiClient = class {
625
667
  chunk: opts.logChunk,
626
668
  prompt,
627
669
  response: text,
628
- usage: result.usage,
670
+ usage,
629
671
  durationMs: Date.now() - t0,
630
- attempt: attempt + 1
672
+ attempt: attempt + 1,
673
+ ...error ? { error } : {}
631
674
  });
632
- return result;
675
+ return error ? { text, usage, error } : { text, usage };
633
676
  } catch (err) {
634
677
  lastError = err instanceof Error ? err.message : String(err);
635
- if (config.thinkingConfig && isThinkingConfigError(lastError)) {
636
- delete config.thinkingConfig;
678
+ if (thinking && isThinkingConfigError(lastError)) {
679
+ const next = fallbackThinking(thinking);
637
680
  logger.warn(
638
- `[gemini] model ${model} rejected thinking config \u2014 retrying without it`
681
+ `[gemini] model ${model} rejected thinking config ${JSON.stringify(thinking)} \u2014 retrying ${next ? `with ${JSON.stringify(next)}` : "without it"}`
639
682
  );
683
+ thinking = next;
684
+ if (thinking) config.thinkingConfig = thinking;
685
+ else delete config.thinkingConfig;
640
686
  continue;
641
687
  }
642
688
  logger.warn(
@@ -711,42 +757,82 @@ async function fileHash(path) {
711
757
  const buf = await (0, import_promises2.readFile)(path);
712
758
  return (0, import_node_crypto2.createHash)("sha256").update(buf).digest("hex").slice(0, 24);
713
759
  }
760
+ var DELETED_TEXT = "Deleted by user.";
761
+ async function readPendingId(pendingPath) {
762
+ if (!(0, import_node_fs3.existsSync)(pendingPath)) return void 0;
763
+ try {
764
+ return JSON.parse(await (0, import_promises2.readFile)(pendingPath, "utf-8")).id;
765
+ } catch {
766
+ return void 0;
767
+ }
768
+ }
714
769
  var AssemblyAIProvider = class {
715
770
  client;
716
771
  cacheDir;
717
772
  constructor(opts) {
718
- this.client = new import_assemblyai.AssemblyAI({ apiKey: opts.apiKey });
773
+ this.client = new import_assemblyai.AssemblyAI({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });
719
774
  this.cacheDir = opts.cacheDir;
720
775
  this.speechModel = opts.speechModel ?? "universal";
721
776
  this.speakersExpected = opts.speakersExpected;
777
+ this.language = opts.language;
778
+ this.zeroStorage = opts.zeroStorage ?? true;
722
779
  }
723
780
  speechModel;
724
781
  speakersExpected;
782
+ language;
783
+ zeroStorage;
784
+ /** Whether the last transcribe() was served from the content-hash cache (no paid call). */
785
+ lastFromCache = false;
725
786
  /** Transcribe a local audio file. Returns cached result if available. */
726
787
  async transcribe(filePath) {
727
788
  const hash = await fileHash(filePath);
728
- const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}.json` : void 0;
789
+ const variant = [
790
+ `lang-${this.language ?? "auto"}`,
791
+ this.speakersExpected && `spk-${this.speakersExpected}`,
792
+ this.speechModel !== "universal" && this.speechModel
793
+ ].filter(Boolean).join("_");
794
+ const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}_${variant}.json` : void 0;
795
+ const pendingPath = cachePath?.replace(/\.json$/, ".pending.json");
796
+ this.lastFromCache = false;
729
797
  if (cachePath && (0, import_node_fs3.existsSync)(cachePath)) {
730
798
  logger.info(`[assemblyai] cache hit ${hash}`);
799
+ this.lastFromCache = true;
800
+ if (pendingPath) await this.finish(pendingPath, await readPendingId(pendingPath));
731
801
  return JSON.parse(await (0, import_promises2.readFile)(cachePath, "utf-8"));
732
802
  }
733
- logger.info(`[assemblyai] uploading ${filePath}...`);
734
- const uploadUrl = await withRetry(
735
- "assemblyai upload",
736
- () => this.client.files.upload(filePath)
737
- );
738
- logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
739
- const params = {
740
- audio: uploadUrl,
741
- speaker_labels: true,
742
- speech_model: this.speechModel
743
- };
744
- if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
745
- const transcript = await withRetry(
746
- "assemblyai transcribe",
747
- () => this.client.transcripts.transcribe(params)
748
- );
803
+ let transcript = pendingPath ? await this.resume(pendingPath) : void 0;
804
+ if (!transcript) {
805
+ logger.info(`[assemblyai] uploading ${filePath}...`);
806
+ const uploadUrl = await withRetry(
807
+ "assemblyai upload",
808
+ () => this.client.files.upload(filePath)
809
+ );
810
+ logger.info(
811
+ `[assemblyai] transcribing (speech_model=${this.speechModel}, language=${this.language ?? "auto-detect"})...`
812
+ );
813
+ const params = {
814
+ audio: uploadUrl,
815
+ speaker_labels: true,
816
+ speech_model: this.speechModel
817
+ };
818
+ if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
819
+ if (this.language) params.language_code = this.language;
820
+ else params.language_detection = true;
821
+ const job = await withRetry(
822
+ "assemblyai submit",
823
+ () => this.client.transcripts.submit(params)
824
+ );
825
+ if (pendingPath) {
826
+ await (0, import_promises2.mkdir)((0, import_node_path4.dirname)(pendingPath), { recursive: true });
827
+ await (0, import_promises2.writeFile)(pendingPath, JSON.stringify({ id: job.id }));
828
+ }
829
+ transcript = await withRetry(
830
+ "assemblyai transcribe",
831
+ () => this.client.transcripts.waitUntilReady(job.id)
832
+ );
833
+ }
749
834
  if (transcript.status === "error") {
835
+ if (pendingPath) await (0, import_promises2.rm)(pendingPath, { force: true });
750
836
  throw new Error(`AssemblyAI error: ${transcript.error}`);
751
837
  }
752
838
  const result = this.mapTranscript(transcript, hash);
@@ -755,10 +841,53 @@ var AssemblyAIProvider = class {
755
841
  await (0, import_promises2.writeFile)(cachePath, JSON.stringify(result, null, 2));
756
842
  }
757
843
  logger.info(
758
- `[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers`
844
+ `[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers, language ${result.languageCode ?? "?"}`
759
845
  );
846
+ if (pendingPath) await this.finish(pendingPath, transcript.id);
847
+ else if (this.zeroStorage && transcript.id) await this.deleteRemote(transcript.id);
760
848
  return result;
761
849
  }
850
+ /** Delete job `id` from AssemblyAI (with zero storage), then forget it. */
851
+ async finish(pendingPath, id) {
852
+ if (this.zeroStorage && id) await this.deleteRemote(id);
853
+ await (0, import_promises2.rm)(pendingPath, { force: true });
854
+ }
855
+ async deleteRemote(id) {
856
+ await this.client.transcripts.delete(id).then(
857
+ () => logger.debug(`[assemblyai] deleted transcript ${id} from AssemblyAI`),
858
+ (err) => logger.warn(
859
+ `[assemblyai] couldn't delete transcript ${id} from AssemblyAI (it expires in 30 days): ${err instanceof Error ? err.message : String(err)}`
860
+ )
861
+ );
862
+ }
863
+ /** The finished job a stopped run left at `pendingPath`, or undefined to send the audio
864
+ * again: when there is none, or AssemblyAI says it's gone (not found, failed, deleted).
865
+ * Anything less certain (offline, an outage, a refused key) is thrown with the job kept,
866
+ * so the next run neither pays twice nor leaves the job behind undeleted. */
867
+ async resume(pendingPath) {
868
+ const id = await readPendingId(pendingPath);
869
+ if (id) {
870
+ logger.info(`[assemblyai] picking up transcript ${id}, left by a stopped run...`);
871
+ let gone;
872
+ try {
873
+ const t = await withRetry(
874
+ "assemblyai transcribe",
875
+ () => this.client.transcripts.waitUntilReady(id)
876
+ );
877
+ if (t.status === "completed" && t.text !== DELETED_TEXT) return t;
878
+ gone = t.status === "error" ? `it failed: ${t.error}` : "it was deleted";
879
+ } catch (err) {
880
+ const message = err instanceof Error ? err.message : String(err);
881
+ if (!/not found/i.test(message)) throw err;
882
+ gone = message;
883
+ }
884
+ logger.warn(
885
+ `[assemblyai] transcript ${id} is gone (${gone}) \u2014 sending the audio again`
886
+ );
887
+ }
888
+ await (0, import_promises2.rm)(pendingPath, { force: true });
889
+ return void 0;
890
+ }
762
891
  mapTranscript(t, id) {
763
892
  const toWord = (w) => ({
764
893
  text: w.text,
@@ -788,6 +917,7 @@ var AssemblyAIProvider = class {
788
917
  durationSec,
789
918
  audioDurationSec: t.audio_duration ?? void 0,
790
919
  // AssemblyAI returns seconds (not ms)
920
+ languageCode: t.language_code ?? void 0,
791
921
  speakers: [...speakers].sort(),
792
922
  transcriptId: t.id ?? id,
793
923
  speechModelUsed: t.speech_model_used ?? void 0,
@@ -806,7 +936,7 @@ var WhisperGroqClient = class {
806
936
  apiKey;
807
937
  model;
808
938
  baseUrl;
809
- async transcribe(audio) {
939
+ async transcribe(audio, opts = {}) {
810
940
  const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
811
941
  const form = new FormData();
812
942
  form.append("file", blob, "audio.mp3");
@@ -814,6 +944,7 @@ var WhisperGroqClient = class {
814
944
  form.append("response_format", "verbose_json");
815
945
  form.append("timestamp_granularities[]", "word");
816
946
  form.append("timestamp_granularities[]", "segment");
947
+ if (opts.language) form.append("language", opts.language);
817
948
  const res = await fetch(`${this.baseUrl}/audio/transcriptions`, {
818
949
  method: "POST",
819
950
  headers: { Authorization: `Bearer ${this.apiKey}` },
@@ -868,6 +999,7 @@ var ElevenLabsClient = class {
868
999
  form.append("diarize", "true");
869
1000
  form.append("tag_audio_events", "false");
870
1001
  if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
1002
+ if (opts.languageCode) form.append("language_code", opts.languageCode);
871
1003
  for (const term of opts.keyterms ?? []) form.append("keyterms", term);
872
1004
  const data = await withRetry("elevenlabs", async () => {
873
1005
  const res = await fetch(`${this.baseUrl}/speech-to-text`, {
@@ -926,17 +1058,53 @@ var ElevenLabsClient = class {
926
1058
  };
927
1059
 
928
1060
  // src/core/pricing.ts
929
- var PRICES_AS_OF = "2026-07";
1061
+ var PRICES_AS_OF = "2026-11-17";
930
1062
  var MODEL_PRICES = {
931
- // Gemini (ai.google.dev/gemini-api/docs/pricing, standard tier, <=200k prompts)
1063
+ "gemini-4-hydrogen": { textIn: 1.5, out: 7.5 },
1064
+ "gemini-4-argon": {
1065
+ until: "2026-11-30",
1066
+ price: { textIn: 2, out: 10 },
1067
+ then: { textIn: 4, out: 20 }
1068
+ },
1069
+ "gemini-4-carbon": {
1070
+ until: "2026-11-30",
1071
+ price: { textIn: 2, out: 10 },
1072
+ then: { textIn: 4, out: 20 }
1073
+ },
932
1074
  "gemini-3.1-pro-preview": { textIn: 2, out: 12 },
933
- "gemini-3-pro-preview": { textIn: 2, out: 12 },
934
- "gemini-3.5-flash": { textIn: 1.5, out: 9 },
1075
+ // ≤200k-token prompts
1076
+ "gemini-3.8-flash": {
1077
+ until: "2026-12-31",
1078
+ price: { textIn: 0.75, out: 3.75 },
1079
+ then: { textIn: 1.5, out: 7.5 }
1080
+ },
1081
+ "gemini-3.6-flash": {
1082
+ until: "2026-12-31",
1083
+ price: { textIn: 0.75, out: 3.75 },
1084
+ then: { textIn: 1.5, out: 7.5 }
1085
+ },
1086
+ // Deprecated 2026-10-08; requests are served by gemini-3.6-flash (priced as such).
1087
+ "gemini-3.5-flash": {
1088
+ until: "2026-12-31",
1089
+ price: { textIn: 0.75, out: 3.75 },
1090
+ then: { textIn: 1.5, out: 7.5 }
1091
+ },
1092
+ "gemini-3.5-flash-lite": { textIn: 0.3, out: 2.5 },
935
1093
  "gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
936
- "gemini-2.5-pro": { textIn: 1.25, out: 10 },
937
- "gemini-2.5-flash": { textIn: 0.3, audioIn: 1, out: 2.5 },
1094
+ // From 2026-12-01 Google serves (and bills) 2.5 Pro as 3.8 Flash and 2.5 Flash as 3.5 Flash-Lite.
1095
+ "gemini-2.5-pro": {
1096
+ until: "2026-11-30",
1097
+ price: { textIn: 1.25, out: 10 },
1098
+ then: { textIn: 1.5, out: 7.5 }
1099
+ },
1100
+ "gemini-2.5-flash": {
1101
+ until: "2026-11-30",
1102
+ price: { textIn: 0.3, audioIn: 1, out: 2.5 },
1103
+ then: { textIn: 0.3, out: 2.5 }
1104
+ },
938
1105
  "gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
939
- // Moving aliases — priced as their current targets.
1106
+ // Moving aliases. Google hasn't documented their targets since January 2026; these are
1107
+ // the last documented targets' prices, so treat them as estimates.
940
1108
  "gemini-pro-latest": { textIn: 2, out: 12 },
941
1109
  "gemini-flash-latest": { textIn: 1.5, out: 9 },
942
1110
  "gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
@@ -955,17 +1123,27 @@ var ASR_HOURLY = {
955
1123
  // whisper-large-v3-turbo
956
1124
  none: 0
957
1125
  };
958
- var AUDIO_TOKENS_PER_SEC = 32;
959
- function priceFor(model) {
960
- if (MODEL_PRICES[model]) return MODEL_PRICES[model];
961
- const hit = Object.keys(MODEL_PRICES).find((k) => model.startsWith(k));
962
- return hit ? MODEL_PRICES[hit] : null;
1126
+ function audioTokensPerSec(model) {
1127
+ return model.startsWith("gemini-4") ? 32 : 25;
1128
+ }
1129
+ function priceFor(model, at = /* @__PURE__ */ new Date()) {
1130
+ const key = model in MODEL_PRICES ? model : Object.keys(MODEL_PRICES).filter((k) => model.startsWith(k)).sort((a, b) => b.length - a.length)[0];
1131
+ if (!key) return null;
1132
+ const p = MODEL_PRICES[key];
1133
+ if (!("until" in p)) return p;
1134
+ return at.toISOString().slice(0, 10) <= p.until ? p.price : p.then;
963
1135
  }
964
1136
  function asrCost(provider, durationSec) {
965
1137
  const hourly = ASR_HOURLY[provider];
966
1138
  if (hourly === void 0) return null;
967
1139
  return durationSec / 3600 * hourly;
968
1140
  }
1141
+ var OUTPUT_TOK_PER_AUDIO_MIN = 700;
1142
+ function thinkingOverhead(model) {
1143
+ if (model.startsWith("gemini-4-hydrogen")) return 0.5;
1144
+ if (model.includes("pro")) return 0.15;
1145
+ return 0;
1146
+ }
969
1147
  function estimateRunCost(opts) {
970
1148
  const lines = [];
971
1149
  let total = 0;
@@ -977,9 +1155,9 @@ function estimateRunCost(opts) {
977
1155
  );
978
1156
  const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
979
1157
  if (p) {
980
- const audioTok = billedAudioSec * AUDIO_TOKENS_PER_SEC;
1158
+ const audioTok = billedAudioSec * audioTokensPerSec(opts.model);
981
1159
  const promptTok = chunks * 1500;
982
- const outTok = opts.durationSec / 60 * 150 + 1500;
1160
+ const outTok = opts.durationSec / 60 * OUTPUT_TOK_PER_AUDIO_MIN * (1 + thinkingOverhead(opts.model)) + 1500;
983
1161
  const inRate = p.audioIn ?? p.textIn;
984
1162
  const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
985
1163
  total += llmUsd;
@@ -1007,7 +1185,7 @@ function estimateRunCost(opts) {
1007
1185
  }
1008
1186
  return { totalUsd: total, lines, incomplete };
1009
1187
  }
1010
- function computeReceipt(usage, tsProvider, durationSec) {
1188
+ function computeReceipt(usage, tsProvider, durationSec, asrBilled = true) {
1011
1189
  let llmUsd = 0;
1012
1190
  let incomplete = false;
1013
1191
  const lines = [];
@@ -1040,11 +1218,11 @@ function computeReceipt(usage, tsProvider, durationSec) {
1040
1218
  `${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
1041
1219
  );
1042
1220
  }
1043
- const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
1221
+ const asrUsd = tsProvider === "none" || !asrBilled ? 0 : asrCost(tsProvider, durationSec);
1044
1222
  if (asrUsd !== null && tsProvider !== "none") {
1045
1223
  perModel[tsProvider] = asrUsd;
1046
1224
  lines.push(
1047
- `${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 $${asrUsd.toFixed(2)}`
1225
+ `${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 ${asrBilled ? `$${asrUsd.toFixed(2)}` : "cached \xB7 $0.00"}`
1048
1226
  );
1049
1227
  }
1050
1228
  return {
@@ -1178,11 +1356,22 @@ async function describeMeeting(client, model, files, fileName, instructions, aud
1178
1356
  logKind: "describe"
1179
1357
  }
1180
1358
  );
1181
- const text = res.text || "";
1359
+ return { ...parseDescription(res.text || ""), raw: res.text || "" };
1360
+ }
1361
+ function parseDescription(text) {
1182
1362
  const parts = text.split(/\n---\n|\n\s*---\s*\n/);
1183
- const description = parts[0]?.trim() || text.trim();
1184
- const roster = parts.slice(1).join("\n---\n").trim() || "(no explicit roster)";
1185
- return { description, roster, raw: text };
1363
+ return {
1364
+ description: dropHeading(parts[0] ?? "", "DESCRIPTION") || text.trim(),
1365
+ roster: dropHeading(parts.slice(1).join("\n---\n"), "ROSTER") || "(no explicit roster)"
1366
+ };
1367
+ }
1368
+ function dropHeading(section, word) {
1369
+ const s = section.trim();
1370
+ const firstLine = s.split("\n", 1)[0] ?? "";
1371
+ if (new RegExp(`^[#*_\\s]*${word}[#*_:\\s]*$`, "i").test(firstLine)) {
1372
+ return s.slice(firstLine.length).trim();
1373
+ }
1374
+ return s.replace(new RegExp(`^[#*_\\s]*${word}[*_]*\\s*:[*_]*\\s*`, "i"), "");
1186
1375
  }
1187
1376
 
1188
1377
  // src/transcribe/prompts.ts
@@ -1275,13 +1464,6 @@ function transcriptionPrompt(ctx) {
1275
1464
  "Use a roster name ONLY when the voice itself tells you it's that person (they self-identify, are addressed by name, or the voice description clearly matches). If two speakers sound similar and you are not sure which name belongs to which voice, use 'Speaker A' / 'Speaker B' instead \u2014 a WRONG name is much worse than a generic label; a later pass verifies names."
1276
1465
  );
1277
1466
  }
1278
- if (ctx.previousTail) {
1279
- parts.push("");
1280
- parts.push(
1281
- "TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
1282
- );
1283
- parts.push(ctx.previousTail);
1284
- }
1285
1467
  if (ctx.instructions) {
1286
1468
  parts.push("");
1287
1469
  parts.push("ADDITIONAL INSTRUCTIONS:");
@@ -1344,6 +1526,51 @@ function formatDuration(seconds) {
1344
1526
  return parts.join(" ");
1345
1527
  }
1346
1528
 
1529
+ // src/transcribe/degeneration.ts
1530
+ var DEGENERATE_COMPRESSION_RATIO = 2.2;
1531
+ var WINDOW_CHARS = 400;
1532
+ var STEP_CHARS = 200;
1533
+ var MIN_MATCH = 4;
1534
+ var MAX_MATCH = 258;
1535
+ var REF_COST = 3;
1536
+ function ratio(s) {
1537
+ let cost = 0;
1538
+ for (let i = 0; i < s.length; ) {
1539
+ let best = 0;
1540
+ for (let j = Math.max(0, i - WINDOW_CHARS); j < i; j++) {
1541
+ let k = 0;
1542
+ while (i + k < s.length && k < MAX_MATCH && s[j + k] === s[i + k]) k++;
1543
+ if (k > best) best = k;
1544
+ }
1545
+ if (best >= MIN_MATCH) {
1546
+ cost += REF_COST;
1547
+ i += best;
1548
+ } else {
1549
+ cost += 1;
1550
+ i += 1;
1551
+ }
1552
+ }
1553
+ return s.length / cost;
1554
+ }
1555
+ function maxCompressionRatio(text) {
1556
+ if (text.length < WINDOW_CHARS) return 0;
1557
+ let max = 0;
1558
+ for (let i = 0; i + WINDOW_CHARS <= text.length; i += STEP_CHARS) {
1559
+ max = Math.max(max, ratio(text.slice(i, i + WINDOW_CHARS)));
1560
+ }
1561
+ return Math.max(max, ratio(text.slice(-WINDOW_CHARS)));
1562
+ }
1563
+ function tailIsDegenerate(text) {
1564
+ if (text.length < 2 * WINDOW_CHARS) return false;
1565
+ return ratio(text.slice(-WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO && ratio(text.slice(-2 * WINDOW_CHARS, -WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO;
1566
+ }
1567
+ function transcriptTextOf(partialJson) {
1568
+ const out = [];
1569
+ for (const m of partialJson.matchAll(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/g))
1570
+ out.push(m[1]);
1571
+ return out.join(" ");
1572
+ }
1573
+
1347
1574
  // src/transcribe/llm-transcribe.ts
1348
1575
  var MIN_SEGMENTS = 3;
1349
1576
  var MIN_SPAN_RATIO = 0.6;
@@ -1384,6 +1611,16 @@ function parseLlmSegments(data, chunkOffsetSec) {
1384
1611
  return { segments: out, dropped };
1385
1612
  }
1386
1613
  function validate(segments, chunkDuration) {
1614
+ const compression = maxCompressionRatio(segments.map((s) => s.text).join(" "));
1615
+ if (compression > DEGENERATE_COMPRESSION_RATIO) {
1616
+ return {
1617
+ isValid: false,
1618
+ degenerate: true,
1619
+ spanSec: segments.length ? segments[segments.length - 1].endSec - segments[0].startSec : 0,
1620
+ segmentCount: segments.length,
1621
+ message: `degenerate repetition (compression ratio ${compression.toFixed(1)} > ${DEGENERATE_COMPRESSION_RATIO})`
1622
+ };
1623
+ }
1387
1624
  if (segments.length < MIN_SEGMENTS) {
1388
1625
  return {
1389
1626
  isValid: false,
@@ -1414,72 +1651,135 @@ function validate(segments, chunkDuration) {
1414
1651
  async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
1415
1652
  const validationRetries = opts.validationRetries ?? 1;
1416
1653
  const prompt = transcriptionPrompt(ctx);
1417
- let lastResult;
1654
+ let temperature = opts.temperature ?? 0.2;
1655
+ let loopAborted = false;
1656
+ let checkedAt = 0;
1657
+ const shouldAbort = (raw) => {
1658
+ if (raw.length - checkedAt < 800) return null;
1659
+ checkedAt = raw.length;
1660
+ if (!tailIsDegenerate(transcriptTextOf(raw))) return null;
1661
+ loopAborted = true;
1662
+ return "degenerate repetition";
1663
+ };
1664
+ let best;
1665
+ const rank = (r) => r.validation.isValid ? 3 : r.error ? 0 : r.validation.degenerate ? 1 : 2;
1666
+ const keep = (r) => {
1667
+ if (!best || rank(r) > rank(best) || rank(r) === rank(best) && r.validation.spanSec > best.validation.spanSec)
1668
+ best = r;
1669
+ };
1418
1670
  for (let attempt = 0; attempt <= validationRetries; attempt++) {
1671
+ loopAborted = false;
1672
+ checkedAt = 0;
1419
1673
  const gen = await client.generateJson(
1420
1674
  model,
1421
1675
  prompt,
1422
1676
  [{ path: chunkPath }],
1423
1677
  TRANSCRIPT_SCHEMA,
1424
1678
  {
1425
- temperature: opts.temperature ?? 0.2,
1679
+ temperature,
1426
1680
  maxRetries: 3,
1427
1681
  logKind: "transcribe",
1428
- logChunk: ctx.index - 1
1682
+ logChunk: ctx.index - 1,
1683
+ shouldAbort
1429
1684
  }
1430
1685
  );
1431
1686
  if (gen.error || !gen.data) {
1432
- lastResult = {
1687
+ keep({
1433
1688
  segments: [],
1434
1689
  raw: gen.raw,
1435
1690
  usage: gen.usage,
1436
1691
  validation: {
1437
1692
  isValid: false,
1693
+ degenerate: loopAborted,
1438
1694
  spanSec: 0,
1439
1695
  segmentCount: 0,
1440
1696
  message: gen.error || "no data"
1441
1697
  },
1442
1698
  error: gen.error
1443
- };
1699
+ });
1444
1700
  logger.warn(
1445
1701
  `[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
1446
1702
  );
1703
+ if (loopAborted) temperature = Math.min(1, temperature + 0.3);
1447
1704
  continue;
1448
1705
  }
1449
1706
  const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
1450
1707
  const v = validate(segments, opts.chunkDurationSec);
1451
- lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
1708
+ const result = { segments, raw: gen.raw, usage: gen.usage, validation: v };
1709
+ keep(result);
1452
1710
  if (v.isValid) {
1453
1711
  logger.info(
1454
1712
  `[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
1455
1713
  );
1456
- return lastResult;
1714
+ return result;
1457
1715
  }
1458
1716
  logger.warn(
1459
1717
  `[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
1460
1718
  );
1719
+ if (v.degenerate) temperature = Math.min(1, temperature + 0.3);
1461
1720
  }
1462
1721
  logger.error(
1463
1722
  `[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
1464
1723
  );
1465
- return lastResult;
1724
+ return best;
1725
+ }
1726
+
1727
+ // src/transcribe/grounding.ts
1728
+ var MIN_GROUNDED_PRECISION = 0.3;
1729
+ var MIN_TOKENS = 30;
1730
+ var MAX_SCRIPT_SHARE_GAP = 0.2;
1731
+ var STOP_WORDS = Object.fromEntries(
1732
+ "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])
1733
+ );
1734
+ var NON_LATIN = /[^\u0000-\u024F\u2000-\u206F]/u;
1735
+ function contentTokens(words) {
1736
+ const bag = /* @__PURE__ */ new Map();
1737
+ for (const w of words) {
1738
+ const t = w.toLowerCase().replace(/^[^\p{L}\p{N}']+|[^\p{L}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
1739
+ if (t && !STOP_WORDS[t]) bag.set(t, (bag.get(t) ?? 0) + 1);
1740
+ }
1741
+ return bag;
1742
+ }
1743
+ function chunkGrounding(segments, asrWords, start, end) {
1744
+ const asrInRange = asrWords.filter((w) => w.start >= start && w.start < end);
1745
+ const llmWords = segments.map((s) => s.text.replace(/\[[^\]]*\]/g, " ")).join(" ").split(/\s+/).filter(Boolean);
1746
+ const llm = contentTokens(llmWords);
1747
+ const asr = contentTokens(asrInRange.map((w) => w.text));
1748
+ let llmTokens = 0;
1749
+ let asrTokens = 0;
1750
+ let shared = 0;
1751
+ for (const n of llm.values()) llmTokens += n;
1752
+ for (const n of asr.values()) asrTokens += n;
1753
+ for (const [t, n] of llm) shared += Math.min(n, asr.get(t) ?? 0);
1754
+ const share = (ws) => ws.length ? ws.filter((w) => NON_LATIN.test(w)).length / ws.length : 0;
1755
+ const scriptsMatch = Math.abs(share(llmWords) - share(asrInRange.map((w) => w.text))) <= MAX_SCRIPT_SHARE_GAP;
1756
+ const judged = llmTokens >= MIN_TOKENS && asrTokens >= MIN_TOKENS && scriptsMatch;
1757
+ const precision = llmTokens ? shared / llmTokens : 1;
1758
+ return {
1759
+ llmTokens,
1760
+ asrTokens,
1761
+ precision,
1762
+ judged,
1763
+ grounded: !judged || precision >= MIN_GROUNDED_PRECISION
1764
+ };
1466
1765
  }
1467
1766
 
1468
1767
  // src/align/normalize.ts
1469
- function normalize(word) {
1470
- return word.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "").replace(/'+$/g, "").replace(/^'+/g, "");
1768
+ function normalizeWord(word) {
1769
+ return word.normalize("NFKC").toLowerCase().replace(/[’‘`]/g, "'").replace(/^[^\p{L}\p{M}\p{N}']+|[^\p{L}\p{M}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
1471
1770
  }
1472
1771
  function tokenize(text) {
1473
1772
  const out = [];
1474
1773
  for (const raw of text.split(/\s+/)) {
1475
1774
  if (!raw) continue;
1476
- const norm2 = normalize(raw);
1775
+ const norm2 = normalizeWord(raw);
1477
1776
  if (norm2) out.push({ original: raw, norm: norm2 });
1478
1777
  }
1479
1778
  return out;
1480
1779
  }
1481
1780
  function fuzzyEqual(a, b) {
1482
1781
  if (a === b) return true;
1782
+ if (!a || !b) return false;
1483
1783
  if (Math.abs(a.length - b.length) <= 1) {
1484
1784
  return editDistanceChars(a, b, 1) <= 1;
1485
1785
  }
@@ -1505,9 +1805,85 @@ function editDistanceChars(a, b, max) {
1505
1805
  return prev[n];
1506
1806
  }
1507
1807
 
1808
+ // src/transcribe/coverage.ts
1809
+ var MIN_COVERAGE_RATIO = 0.6;
1810
+ var MIN_ASR_WORDS = 200;
1811
+ function chunkCoverage(segments, asrWords, start, end) {
1812
+ const llmWords = segments.reduce(
1813
+ (n, s) => n + tokenize(s.text.replace(/\[[^\]]*\]/g, " ")).length,
1814
+ 0
1815
+ );
1816
+ const asrCount = asrWords.reduce(
1817
+ (n, w) => n + (w.start >= start && w.start < end ? tokenize(w.text).length : 0),
1818
+ 0
1819
+ );
1820
+ const ratio2 = asrCount ? llmWords / asrCount : Infinity;
1821
+ const judged = asrCount >= MIN_ASR_WORDS;
1822
+ return {
1823
+ llmWords,
1824
+ asrWords: asrCount,
1825
+ ratio: ratio2,
1826
+ judged,
1827
+ low: judged && ratio2 < MIN_COVERAGE_RATIO
1828
+ };
1829
+ }
1830
+
1831
+ // src/core/retranscribe.ts
1832
+ var import_node_fs5 = require("fs");
1833
+ var HALF_OVERLAP_SEC = 5;
1834
+ async function transcribeInHalves(opts) {
1835
+ const { chunk } = opts;
1836
+ const mid = (chunk.start + chunk.end) / 2;
1837
+ const halves = [
1838
+ { name: "a", from: chunk.start, to: Math.min(chunk.end, mid + HALF_OVERLAP_SEC) },
1839
+ { name: "b", from: Math.max(chunk.start, mid - HALF_OVERLAP_SEC), to: chunk.end }
1840
+ ];
1841
+ const results = [];
1842
+ for (const h of halves) {
1843
+ const path = `${opts.pathPrefix}_half_${h.name}.mp3`;
1844
+ if (!(0, import_node_fs5.existsSync)(path))
1845
+ await extractChunk(opts.audioPath, path, h.from, h.to, opts.audioOpts);
1846
+ results.push(
1847
+ await transcribeChunk(opts.client, opts.model, path, h.from, opts.ctx, {
1848
+ chunkDurationSec: h.to - h.from,
1849
+ validationRetries: 0
1850
+ })
1851
+ );
1852
+ }
1853
+ const [a, b] = results;
1854
+ const center = (s) => (s.startSec + s.endSec) / 2;
1855
+ const segments = [
1856
+ ...a.segments.filter((s) => center(s) < mid),
1857
+ ...b.segments.filter((s) => center(s) >= mid)
1858
+ ];
1859
+ const first = segments[0];
1860
+ const last = segments[segments.length - 1];
1861
+ return {
1862
+ segments,
1863
+ raw: JSON.stringify({ halves: [a.raw, b.raw] }),
1864
+ usage: {
1865
+ inputTokens: a.usage.inputTokens + b.usage.inputTokens,
1866
+ outputTokens: a.usage.outputTokens + b.usage.outputTokens,
1867
+ thoughtTokens: (a.usage.thoughtTokens ?? 0) + (b.usage.thoughtTokens ?? 0),
1868
+ totalTokens: a.usage.totalTokens + b.usage.totalTokens
1869
+ },
1870
+ validation: {
1871
+ isValid: a.validation.isValid && b.validation.isValid,
1872
+ degenerate: Boolean(a.validation.degenerate || b.validation.degenerate),
1873
+ spanSec: first && last ? last.endSec - first.startSec : 0,
1874
+ segmentCount: segments.length,
1875
+ message: `halves: ${a.validation.message} | ${b.validation.message}`
1876
+ },
1877
+ ...a.error || b.error ? { error: [a.error, b.error].filter(Boolean).join(" | ") } : {}
1878
+ };
1879
+ }
1880
+
1508
1881
  // src/align/edit-distance.ts
1509
1882
  var INDEL = 2;
1883
+ var OUT_OF_WINDOW = { cost: 2 * INDEL + 1, fuzzy: false };
1510
1884
  function matchCost(a, b) {
1885
+ if (a.window && b.start !== void 0 && (b.start < a.window.lo || b.start > a.window.hi))
1886
+ return OUT_OF_WINDOW;
1511
1887
  if (a.norm === b.norm) return { cost: 0, fuzzy: false };
1512
1888
  if (fuzzyEqual(a.norm, b.norm)) return { cost: 1, fuzzy: true };
1513
1889
  return { cost: 2, fuzzy: false };
@@ -1585,12 +1961,19 @@ function alignWords(llm, asr) {
1585
1961
  }
1586
1962
 
1587
1963
  // src/align/aligner.ts
1964
+ var WINDOW_SLACK_SEC = 2;
1965
+ var UNANCHORED_MAX_DRIFT_SEC = 15;
1966
+ var STRETCH_MIN_SEC = 30;
1967
+ var STRETCH_SEC_PER_WORD = 3;
1968
+ var MAX_INNER_GAP_SEC = 8;
1969
+ var SPOKEN_SEC_PER_WORD = 0.5;
1970
+ var UNCONFIRMED_MAX_SEC = 5;
1588
1971
  function toAsrTokens(words) {
1589
1972
  return words.map((w) => ({
1590
1973
  text: w.text,
1591
1974
  start: w.start,
1592
1975
  end: w.end,
1593
- norm: w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
1976
+ norm: normalizeWord(w.text)
1594
1977
  }));
1595
1978
  }
1596
1979
  function transferTiming(llm, asr, ops) {
@@ -1649,7 +2032,9 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
1649
2032
  for (const { s, i } of sorted) {
1650
2033
  const toks = tokenize(s.text);
1651
2034
  const start = flat.length;
1652
- for (const t of toks) flat.push({ original: t.original, norm: t.norm, segIdx: i });
2035
+ const window = s.chunkStart !== void 0 && s.chunkEnd !== void 0 ? { lo: s.chunkStart - WINDOW_SLACK_SEC, hi: s.chunkEnd + WINDOW_SLACK_SEC } : void 0;
2036
+ for (const t of toks)
2037
+ flat.push({ original: t.original, norm: t.norm, segIdx: i, window });
1653
2038
  segRanges.push({ src: i, start, end: flat.length });
1654
2039
  }
1655
2040
  if (flat.length === 0 || asrWords.length === 0) {
@@ -1694,21 +2079,53 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
1694
2079
  let end;
1695
2080
  let timingSource;
1696
2081
  const confidence = tokenCount ? exact / tokenCount : 0;
1697
- if (firstTimed && lastTimed) {
2082
+ const unanchoredDrift = segOps.length === 0 && firstTimed ? Math.abs(firstTimed.start - s.startSec) : 0;
2083
+ if (firstTimed && lastTimed && unanchoredDrift <= UNANCHORED_MAX_DRIFT_SEC) {
1698
2084
  start = firstTimed.start;
1699
2085
  end = lastTimed.end;
1700
2086
  timingSource = confidence >= confThreshold ? "aligned" : "interpolated";
2087
+ if (end - start > Math.max(STRETCH_MIN_SEC, STRETCH_SEC_PER_WORD * tokenCount)) {
2088
+ const runs = [];
2089
+ for (const t of segTimes) {
2090
+ if (isNaN(t.start)) continue;
2091
+ const run2 = runs[runs.length - 1];
2092
+ if (run2 && t.start - run2.end <= MAX_INNER_GAP_SEC) {
2093
+ run2.end = Math.max(run2.end, t.end);
2094
+ if (t.matched) run2.matched++;
2095
+ } else {
2096
+ runs.push({ start: t.start, end: t.end, matched: t.matched ? 1 : 0 });
2097
+ }
2098
+ }
2099
+ const best = runs.reduce(
2100
+ (a, b) => b.matched > a.matched || b.matched === a.matched && Math.abs(b.start - s.startSec) < Math.abs(a.start - s.startSec) ? b : a
2101
+ );
2102
+ start = best.start;
2103
+ end = best.end;
2104
+ }
2105
+ const spoken = Math.max(1, SPOKEN_SEC_PER_WORD * tokenCount);
2106
+ if (exact === 0 && end - start > Math.max(UNCONFIRMED_MAX_SEC, 3 * spoken)) {
2107
+ end = start + spoken;
2108
+ }
1701
2109
  } else {
1702
2110
  start = s.startSec;
1703
2111
  end = s.endSec;
1704
2112
  timingSource = "coarse";
1705
2113
  }
1706
- const words = segTimes.map((t, idx) => ({
1707
- text: flat[range.start + idx].original,
1708
- start: isNaN(t.start) ? start : t.start,
1709
- end: isNaN(t.end) ? end : t.end,
1710
- matched: t.matched
1711
- }));
2114
+ const step = timingSource === "coarse" && tokenCount ? (end - start) / tokenCount : 0;
2115
+ const inside = (x) => Math.min(Math.max(x, start), end);
2116
+ const words = segTimes.map(
2117
+ (t, idx) => timingSource === "coarse" ? {
2118
+ text: flat[range.start + idx].original,
2119
+ start: start + step * idx,
2120
+ end: start + step * (idx + 1),
2121
+ matched: false
2122
+ } : {
2123
+ text: flat[range.start + idx].original,
2124
+ start: isNaN(t.start) ? start : inside(t.start),
2125
+ end: isNaN(t.end) ? end : inside(t.end),
2126
+ matched: t.matched
2127
+ }
2128
+ );
1712
2129
  out.push({
1713
2130
  speaker: s.speaker,
1714
2131
  start,
@@ -1723,23 +2140,90 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
1723
2140
  }
1724
2141
  return out;
1725
2142
  }
2143
+ var CLOCK_ANCHOR_MIN_WORDS = 3;
2144
+ var CLOCK_ANCHOR_MIN_SHARE = 0.6;
2145
+ function toAsrClock(segments, asrWords) {
2146
+ if (!asrWords.length) return segments;
2147
+ const chunks = /* @__PURE__ */ new Map();
2148
+ for (const s of segments) {
2149
+ if (s.chunkIndex === void 0) continue;
2150
+ const group = chunks.get(s.chunkIndex);
2151
+ if (group) group.push(s);
2152
+ else chunks.set(s.chunkIndex, [s]);
2153
+ }
2154
+ const moved = /* @__PURE__ */ new Map();
2155
+ for (const group of chunks.values()) {
2156
+ const lo = Math.min(...group.map((s) => s.chunkStart ?? s.startSec)) - WINDOW_SLACK_SEC;
2157
+ const hi = Math.max(...group.map((s) => s.chunkEnd ?? s.endSec)) + WINDOW_SLACK_SEC;
2158
+ const aligned = alignSegments(
2159
+ group,
2160
+ asrWords.filter((w) => w.end >= lo && w.start <= hi)
2161
+ );
2162
+ const shifts = aligned.map(
2163
+ (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
2164
+ );
2165
+ for (let k = 0; k < aligned.length; k++) {
2166
+ let shift = shifts[k];
2167
+ for (let r = 1; shift === void 0 && r < aligned.length; r++) {
2168
+ shift = shifts[k - r] ?? shifts[k + r];
2169
+ }
2170
+ const s = group[aligned[k].sourceIndex];
2171
+ moved.set(s, {
2172
+ ...s,
2173
+ startSec: s.startSec + (shift ?? 0),
2174
+ endSec: s.endSec + (shift ?? 0)
2175
+ });
2176
+ }
2177
+ }
2178
+ return segments.map((s) => moved.get(s) ?? s);
2179
+ }
1726
2180
 
1727
2181
  // src/align/fill-gaps.ts
1728
2182
  var MIN_GAP_SEC = 0.8;
1729
2183
  var MIN_WORDS = 1;
1730
- function normSet(text) {
1731
- return new Set(tokenize(text).map((t) => t.norm));
2184
+ var HEAD_SLACK_WORDS = 5;
2185
+ function utteranceAt(utts, t) {
2186
+ let lo = 0;
2187
+ let hi = utts.length - 1;
2188
+ let found = -1;
2189
+ while (lo <= hi) {
2190
+ const mid = lo + hi >> 1;
2191
+ if (utts[mid].start <= t) {
2192
+ found = mid;
2193
+ lo = mid + 1;
2194
+ } else {
2195
+ hi = mid - 1;
2196
+ }
2197
+ }
2198
+ return found >= 0 && t <= utts[found].end ? found : -1;
2199
+ }
2200
+ function dominantSpeaker(utts, start, end) {
2201
+ let best = utts[0]?.speaker || "speaker_?";
2202
+ let bestOv = 0;
2203
+ for (const u of utts) {
2204
+ const ov = Math.max(0, Math.min(end, u.end) - Math.max(start, u.start));
2205
+ if (ov > bestOv) {
2206
+ bestOv = ov;
2207
+ best = u.speaker;
2208
+ }
2209
+ }
2210
+ return best;
1732
2211
  }
1733
2212
  function fillAsrGaps(segments, asrWords, asrUtterances) {
1734
2213
  if (!asrWords.length) return segments;
1735
2214
  const sorted = [...segments].sort((a, b) => a.start - b.start);
2215
+ const utts = [...asrUtterances].sort((a, b) => a.start - b.start);
1736
2216
  const ranges = [];
1737
- const firstStart = sorted.length ? sorted[0].start : asrWords[asrWords.length - 1].end;
1738
- if (firstStart > 0) ranges.push([0, firstStart, sorted[0]]);
1739
- for (let i = 0; i < sorted.length - 1; i++) {
1740
- const cur = sorted[i];
1741
- const next = sorted[i + 1];
1742
- if (next.start > cur.end) ranges.push([cur.end, next.start, next]);
2217
+ if (!sorted.length) {
2218
+ ranges.push([0, Infinity, void 0]);
2219
+ } else {
2220
+ if (sorted[0].start > 0) ranges.push([0, sorted[0].start, sorted[0]]);
2221
+ let coveredTo = sorted[0].end;
2222
+ for (const next of sorted.slice(1)) {
2223
+ if (next.start > coveredTo) ranges.push([coveredTo, next.start, next]);
2224
+ coveredTo = Math.max(coveredTo, next.end);
2225
+ }
2226
+ ranges.push([coveredTo, Infinity, void 0]);
1743
2227
  }
1744
2228
  const filled = [];
1745
2229
  for (const [gs, ge, following] of ranges) {
@@ -1747,38 +2231,44 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
1747
2231
  const words = asrWords.filter((w) => w.start >= gs && w.start < ge);
1748
2232
  if (words.length < MIN_WORDS) continue;
1749
2233
  if (following) {
1750
- const followingWords = normSet(following.text);
1751
- const gapNorms = words.map(
1752
- (w) => w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
2234
+ const gapNorms = words.map((w) => normalizeWord(w.text)).filter(Boolean);
2235
+ const head = new Set(
2236
+ tokenize(following.text).slice(0, gapNorms.length + HEAD_SLACK_WORDS).map((t) => t.norm)
1753
2237
  );
1754
- const covered = gapNorms.filter((n) => n && followingWords.has(n)).length;
1755
- if (covered / gapNorms.filter(Boolean).length >= 0.6) continue;
1756
- }
1757
- let bestSp = asrUtterances[0]?.speaker || "speaker_?";
1758
- let bestOv = 0;
1759
- for (const u of asrUtterances) {
1760
- const ov = Math.max(0, Math.min(ge, u.end) - Math.max(gs, u.start));
1761
- if (ov > bestOv) {
1762
- bestOv = ov;
1763
- bestSp = u.speaker;
2238
+ const covered = gapNorms.filter((n) => head.has(n)).length;
2239
+ if (covered / gapNorms.length >= 0.6) continue;
2240
+ }
2241
+ const runs = [];
2242
+ for (const w of words) {
2243
+ const u = utteranceAt(utts, w.start);
2244
+ const cur = runs[runs.length - 1];
2245
+ if (cur && (u === -1 || u === cur.utt || cur.utt === -1)) {
2246
+ cur.words.push(w);
2247
+ if (cur.utt === -1) cur.utt = u;
2248
+ } else {
2249
+ runs.push({ words: [w], utt: u });
1764
2250
  }
1765
2251
  }
1766
- filled.push({
1767
- speaker: bestSp,
1768
- start: words[0].start,
1769
- end: words[words.length - 1].end,
1770
- text: words.map((w) => w.text).join(" "),
1771
- tone: [],
1772
- confidence: 0,
1773
- timingSource: "timestamped",
1774
- words: words.map((w) => ({
1775
- text: w.text,
1776
- start: w.start,
1777
- end: w.end,
1778
- matched: true
1779
- })),
1780
- sourceIndex: -1
1781
- });
2252
+ for (const run2 of runs) {
2253
+ const first = run2.words[0];
2254
+ const last = run2.words[run2.words.length - 1];
2255
+ filled.push({
2256
+ speaker: run2.utt >= 0 ? utts[run2.utt].speaker : dominantSpeaker(utts, first.start, last.end),
2257
+ start: first.start,
2258
+ end: last.end,
2259
+ text: run2.words.map((w) => w.text).join(" "),
2260
+ tone: [],
2261
+ confidence: 0,
2262
+ timingSource: "timestamped",
2263
+ words: run2.words.map((w) => ({
2264
+ text: w.text,
2265
+ start: w.start,
2266
+ end: w.end,
2267
+ matched: true
2268
+ })),
2269
+ sourceIndex: -1
2270
+ });
2271
+ }
1782
2272
  }
1783
2273
  if (!filled.length) return sorted;
1784
2274
  return [...sorted, ...filled].sort((a, b) => a.start - b.start);
@@ -2030,150 +2520,31 @@ function splitMixedVoiceSegments(segments, utterances) {
2030
2520
  return out.sort((a, b) => a.start - b.start);
2031
2521
  }
2032
2522
 
2033
- // src/providers/openai-compat.ts
2034
- var PROVIDER_BASE = {
2035
- deepseek: "https://api.deepseek.com/v1",
2036
- groq: "https://api.groq.com/openai/v1",
2037
- openai: "https://api.openai.com/v1"
2038
- };
2039
- var OpenAICompatClient = class _OpenAICompatClient {
2040
- constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
2041
- this.baseUrl = baseUrl;
2042
- this.apiKey = apiKey;
2043
- this.defaultModel = defaultModel;
2044
- this.providerName = providerName;
2523
+ // src/diarize/identify.ts
2524
+ var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
2525
+ function buildTranscriptExcerpt(segments, speakers) {
2526
+ const speakerHeader = (sp) => {
2527
+ const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
2528
+ return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
2529
+ };
2530
+ const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
2531
+ if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
2532
+ const parts2 = [
2533
+ "SPEAKERS:",
2534
+ ...speakers.map((sp) => `- ${speakerHeader(sp)}`),
2535
+ "",
2536
+ "FULL TRANSCRIPT (in order):"
2537
+ ];
2538
+ for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
2539
+ return parts2.join("\n");
2045
2540
  }
2046
- baseUrl;
2047
- apiKey;
2048
- defaultModel;
2049
- providerName;
2050
- static fromProvider(provider, apiKey, defaultModel) {
2051
- const base = PROVIDER_BASE[provider] ?? provider;
2052
- return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
2053
- }
2054
- async chat(model, messages, opts = {}) {
2055
- const m = model ?? this.defaultModel;
2056
- const maxRetries = opts.maxRetries ?? 5;
2057
- const body = {
2058
- model: m,
2059
- messages,
2060
- temperature: opts.temperature ?? 0.2
2061
- };
2062
- if (opts.maxTokens) body.max_tokens = opts.maxTokens;
2063
- if (opts.responseJson) {
2064
- body.response_format = { type: "json_object" };
2065
- }
2066
- if (this.providerName === "gemini") {
2067
- body.reasoning_effort = "low";
2068
- }
2069
- let lastError;
2070
- const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
2071
- for (let attempt = 0; attempt < maxRetries; attempt++) {
2072
- const t0 = Date.now();
2073
- try {
2074
- const res = await fetch(`${this.baseUrl}/chat/completions`, {
2075
- method: "POST",
2076
- headers: {
2077
- "Content-Type": "application/json",
2078
- Authorization: `Bearer ${this.apiKey}`
2079
- },
2080
- body: JSON.stringify(body)
2081
- });
2082
- if (!res.ok) {
2083
- const txt = await res.text();
2084
- throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
2085
- }
2086
- const data = await res.json();
2087
- const text = data.choices?.[0]?.message?.content ?? "";
2088
- const usage = {
2089
- inputTokens: data.usage?.prompt_tokens ?? 0,
2090
- outputTokens: data.usage?.completion_tokens ?? 0
2091
- };
2092
- logLlmCall({
2093
- ts: new Date(t0).toISOString(),
2094
- provider: this.providerName,
2095
- model: m,
2096
- kind: opts.logKind,
2097
- prompt: promptStr,
2098
- response: text,
2099
- usage,
2100
- durationMs: Date.now() - t0,
2101
- attempt: attempt + 1
2102
- });
2103
- return { text, usage };
2104
- } catch (err) {
2105
- lastError = err instanceof Error ? err.message : String(err);
2106
- if (body.response_format && /response_format/i.test(lastError)) {
2107
- delete body.response_format;
2108
- continue;
2109
- }
2110
- if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
2111
- delete body.reasoning_effort;
2112
- continue;
2113
- }
2114
- logLlmCall({
2115
- ts: new Date(t0).toISOString(),
2116
- provider: this.providerName,
2117
- model: m,
2118
- kind: opts.logKind,
2119
- prompt: promptStr,
2120
- response: "",
2121
- durationMs: Date.now() - t0,
2122
- attempt: attempt + 1,
2123
- error: lastError
2124
- });
2125
- if (attempt < maxRetries - 1)
2126
- await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
2127
- }
2128
- }
2129
- return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
2130
- }
2131
- async chatJson(model, messages, opts = {}) {
2132
- let lastRaw = "";
2133
- let lastError;
2134
- for (let attempt = 0; attempt < 2; attempt++) {
2135
- const res = await this.chat(model, messages, { ...opts, responseJson: true });
2136
- lastRaw = res.text;
2137
- lastError = res.error;
2138
- if (res.error || !res.text) continue;
2139
- try {
2140
- let txt = res.text.trim();
2141
- const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
2142
- if (fence && fence[1]) txt = fence[1];
2143
- return { data: JSON.parse(txt), raw: res.text };
2144
- } catch (err) {
2145
- lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
2146
- }
2147
- }
2148
- return { data: null, raw: lastRaw, error: lastError };
2149
- }
2150
- };
2151
-
2152
- // src/diarize/identify.ts
2153
- var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
2154
- function buildTranscriptExcerpt(segments, speakers) {
2155
- const speakerHeader = (sp) => {
2156
- const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
2157
- return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
2158
- };
2159
- const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
2160
- if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
2161
- const parts2 = [
2162
- "SPEAKERS:",
2163
- ...speakers.map((sp) => `- ${speakerHeader(sp)}`),
2164
- "",
2165
- "FULL TRANSCRIPT (in order):"
2166
- ];
2167
- for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
2168
- return parts2.join("\n");
2169
- }
2170
- const bySpeaker = {};
2171
- for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
2172
- const parts = [];
2173
- for (const sp of speakers) {
2174
- const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
2175
- parts.push(`### ${speakerHeader(sp)}`);
2176
- for (const s of segs) parts.push(` ${s.text}`);
2541
+ const bySpeaker = {};
2542
+ for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
2543
+ const parts = [];
2544
+ for (const sp of speakers) {
2545
+ const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
2546
+ parts.push(`### ${speakerHeader(sp)}`);
2547
+ for (const s of segs) parts.push(` ${s.text}`);
2177
2548
  }
2178
2549
  return parts.join("\n");
2179
2550
  }
@@ -2414,7 +2785,8 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
2414
2785
  wantB ? runPass(reasonerB) : Promise.resolve(void 0)
2415
2786
  ]);
2416
2787
  const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
2417
- if (passFailed(resA) && (!wantB || passFailed(resB))) {
2788
+ const allPassesFailed = passFailed(resA) && (!wantB || passFailed(resB));
2789
+ if (allPassesFailed) {
2418
2790
  logger.warn(
2419
2791
  `identify: ALL passes failed (${resA.reasoning.slice(0, 80)}) \u2014 speakers left as generic labels. Re-run to retry naming cheaply (everything else is cached).`
2420
2792
  );
@@ -2519,10 +2891,164 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
2519
2891
  decisions,
2520
2892
  tripwires,
2521
2893
  passA: { ...resA, model: reasonerA.model },
2522
- passB: resB ? { ...resB, model: reasonerB.model } : void 0
2894
+ passB: resB ? { ...resB, model: reasonerB.model } : void 0,
2895
+ allPassesFailed
2523
2896
  };
2524
2897
  }
2525
2898
 
2899
+ // src/providers/openai-compat.ts
2900
+ async function chatJsonWith(client, model, messages, opts) {
2901
+ let lastRaw = "";
2902
+ let lastError;
2903
+ for (let attempt = 0; attempt < 2; attempt++) {
2904
+ const res = await client.chat(model, messages, { ...opts, responseJson: true });
2905
+ lastRaw = res.text;
2906
+ lastError = res.error;
2907
+ if (res.error || !res.text) continue;
2908
+ try {
2909
+ let txt = res.text.trim();
2910
+ const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
2911
+ if (fence && fence[1]) txt = fence[1];
2912
+ return { data: JSON.parse(txt), raw: res.text };
2913
+ } catch (err) {
2914
+ lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
2915
+ }
2916
+ }
2917
+ return { data: null, raw: lastRaw, error: lastError };
2918
+ }
2919
+ var PROVIDER_BASE = {
2920
+ deepseek: "https://api.deepseek.com/v1",
2921
+ groq: "https://api.groq.com/openai/v1",
2922
+ openai: "https://api.openai.com/v1"
2923
+ };
2924
+ var OpenAICompatClient = class _OpenAICompatClient {
2925
+ constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
2926
+ this.baseUrl = baseUrl;
2927
+ this.apiKey = apiKey;
2928
+ this.defaultModel = defaultModel;
2929
+ this.providerName = providerName;
2930
+ }
2931
+ baseUrl;
2932
+ apiKey;
2933
+ defaultModel;
2934
+ providerName;
2935
+ static fromProvider(provider, apiKey, defaultModel) {
2936
+ const base = PROVIDER_BASE[provider] ?? provider;
2937
+ return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
2938
+ }
2939
+ async chat(model, messages, opts = {}) {
2940
+ const m = model ?? this.defaultModel;
2941
+ const maxRetries = opts.maxRetries ?? 5;
2942
+ const body = {
2943
+ model: m,
2944
+ messages,
2945
+ temperature: opts.temperature ?? 0.2
2946
+ };
2947
+ if (opts.maxTokens) body.max_tokens = opts.maxTokens;
2948
+ if (opts.responseJson) {
2949
+ body.response_format = { type: "json_object" };
2950
+ }
2951
+ if (this.providerName === "gemini") {
2952
+ body.reasoning_effort = "low";
2953
+ }
2954
+ let lastError;
2955
+ const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
2956
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
2957
+ const t0 = Date.now();
2958
+ try {
2959
+ const res = await fetch(`${this.baseUrl}/chat/completions`, {
2960
+ method: "POST",
2961
+ headers: {
2962
+ "Content-Type": "application/json",
2963
+ Authorization: `Bearer ${this.apiKey}`
2964
+ },
2965
+ body: JSON.stringify(body)
2966
+ });
2967
+ if (!res.ok) {
2968
+ const txt = await res.text();
2969
+ throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
2970
+ }
2971
+ const data = await res.json();
2972
+ const text = data.choices?.[0]?.message?.content ?? "";
2973
+ const usage = {
2974
+ inputTokens: data.usage?.prompt_tokens ?? 0,
2975
+ outputTokens: data.usage?.completion_tokens ?? 0
2976
+ };
2977
+ logLlmCall({
2978
+ ts: new Date(t0).toISOString(),
2979
+ provider: this.providerName,
2980
+ model: m,
2981
+ kind: opts.logKind,
2982
+ prompt: promptStr,
2983
+ response: text,
2984
+ usage,
2985
+ durationMs: Date.now() - t0,
2986
+ attempt: attempt + 1
2987
+ });
2988
+ return { text, usage };
2989
+ } catch (err) {
2990
+ lastError = err instanceof Error ? err.message : String(err);
2991
+ if (body.response_format && /response_format/i.test(lastError)) {
2992
+ delete body.response_format;
2993
+ continue;
2994
+ }
2995
+ if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
2996
+ delete body.reasoning_effort;
2997
+ continue;
2998
+ }
2999
+ logLlmCall({
3000
+ ts: new Date(t0).toISOString(),
3001
+ provider: this.providerName,
3002
+ model: m,
3003
+ kind: opts.logKind,
3004
+ prompt: promptStr,
3005
+ response: "",
3006
+ durationMs: Date.now() - t0,
3007
+ attempt: attempt + 1,
3008
+ error: lastError
3009
+ });
3010
+ if (attempt < maxRetries - 1)
3011
+ await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
3012
+ }
3013
+ }
3014
+ return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
3015
+ }
3016
+ chatJson(model, messages, opts = {}) {
3017
+ return chatJsonWith(this, model, messages, opts);
3018
+ }
3019
+ };
3020
+
3021
+ // src/providers/gemini-chat.ts
3022
+ var THINKING_HEADROOM_TOKENS = 4096;
3023
+ var GeminiChatClient = class {
3024
+ constructor(gemini, defaultModel) {
3025
+ this.gemini = gemini;
3026
+ this.defaultModel = defaultModel;
3027
+ }
3028
+ gemini;
3029
+ defaultModel;
3030
+ async chat(model, messages, opts = {}) {
3031
+ const system = messages.filter((m) => m.role === "system").map((m) => m.content);
3032
+ const prompt = messages.filter((m) => m.role !== "system").map((m) => m.content).join("\n\n");
3033
+ const r = await this.gemini.generate(model ?? this.defaultModel, prompt, [], {
3034
+ temperature: opts.temperature ?? 0.2,
3035
+ maxOutputTokens: opts.maxTokens ? opts.maxTokens + THINKING_HEADROOM_TOKENS : void 0,
3036
+ responseJson: opts.responseJson,
3037
+ systemInstruction: system.length ? system.join("\n\n") : void 0,
3038
+ maxRetries: opts.maxRetries ?? 5,
3039
+ logKind: opts.logKind
3040
+ });
3041
+ const usage = {
3042
+ inputTokens: r.usage.inputTokens,
3043
+ outputTokens: r.usage.outputTokens
3044
+ };
3045
+ return r.error ? { text: r.text, usage, error: r.error } : { text: r.text, usage };
3046
+ }
3047
+ chatJson(model, messages, opts = {}) {
3048
+ return chatJsonWith(this, model, messages, opts);
3049
+ }
3050
+ };
3051
+
2526
3052
  // src/providers/reasoner.ts
2527
3053
  var PROVIDERS = {
2528
3054
  deepseek: { baseUrl: "https://api.deepseek.com/v1", keyName: "deepseek" },
@@ -2566,41 +3092,36 @@ function reasonerKey(info, keys) {
2566
3092
  if (info.keyName === "gemini") return keys.gemini || keys.google;
2567
3093
  return keys[info.keyName];
2568
3094
  }
2569
- function resolveReasoner(spec, keys) {
3095
+ function clientFor(info, key, opts) {
3096
+ return info.provider === "gemini" ? new GeminiChatClient(
3097
+ new GeminiClient(key, { zeroStorage: opts.zeroStorage }),
3098
+ info.model
3099
+ ) : new OpenAICompatClient(info.baseUrl, key, info.model, info.provider);
3100
+ }
3101
+ function resolveReasoner(spec, keys, opts = {}) {
2570
3102
  const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
2571
3103
  (s) => !!s
2572
3104
  );
2573
3105
  for (const c of candidates) {
2574
3106
  const info = resolveReasonerInfo(c);
2575
3107
  const key = reasonerKey(info, keys);
2576
- if (key) {
2577
- return {
2578
- client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2579
- info
2580
- };
2581
- }
3108
+ if (key) return { client: clientFor(info, key, opts), info };
2582
3109
  }
2583
3110
  return null;
2584
3111
  }
2585
- function resolveSecondReasoner(first, keys) {
3112
+ function resolveSecondReasoner(first, keys, opts = {}) {
2586
3113
  const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
2587
3114
  for (const c of candidates) {
2588
3115
  const info = resolveReasonerInfo(c);
2589
3116
  if (info.provider === first.provider) continue;
2590
3117
  const key = reasonerKey(info, keys);
2591
- if (key) {
2592
- return {
2593
- client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2594
- info
2595
- };
2596
- }
3118
+ if (key) return { client: clientFor(info, key, opts), info };
2597
3119
  }
2598
3120
  return null;
2599
3121
  }
2600
3122
 
2601
3123
  // src/finalize/finalize.ts
2602
3124
  var MIN_DUR = 0.5;
2603
- var MAX_DUR = 7;
2604
3125
  var OVERLAP_GAP = 0.05;
2605
3126
  function textSimilarity(a, b) {
2606
3127
  const ta = new Set(tokenize(a).map((t) => t.norm));
@@ -2744,16 +3265,14 @@ function fixOverlaps(segments) {
2744
3265
  }
2745
3266
  function clampAndFix(segments) {
2746
3267
  for (const s of segments) {
2747
- const dur = s.end - s.start;
2748
- if (dur < MIN_DUR) s.end = s.start + MIN_DUR;
2749
- else if (dur > MAX_DUR) s.end = s.start + MAX_DUR;
3268
+ if (s.end - s.start < MIN_DUR) s.end = s.start + MIN_DUR;
2750
3269
  }
2751
3270
  return fixOverlaps(segments);
2752
3271
  }
2753
- function finalizeSegments(segments, opts = {}) {
2754
- const minSeg = opts.minSegmentSec ?? 0.2;
2755
- let deduped = dedupSegments(trimSeamOverlaps(segments));
2756
- deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
3272
+ function finalizeSegments(segments) {
3273
+ const deduped = dedupSegments(trimSeamOverlaps(segments)).filter(
3274
+ (s) => s.text.trim().length > 0
3275
+ );
2757
3276
  const out = deduped.map((s, i) => ({
2758
3277
  id: i + 1,
2759
3278
  start: s.start,
@@ -3081,17 +3600,18 @@ async function summarizeTranscript(client, model, result, instructions) {
3081
3600
 
3082
3601
  // src/core/pipeline.ts
3083
3602
  var import_node_path6 = require("path");
3603
+ var import_node_crypto3 = require("crypto");
3084
3604
  var JSON_OPTS = { encoding: "utf-8" };
3085
3605
  function readJson(p) {
3086
- if (!(0, import_node_fs5.existsSync)(p)) return null;
3606
+ if (!(0, import_node_fs6.existsSync)(p)) return null;
3087
3607
  try {
3088
- return JSON.parse((0, import_node_fs5.readFileSync)(p, JSON_OPTS));
3608
+ return JSON.parse((0, import_node_fs6.readFileSync)(p, JSON_OPTS));
3089
3609
  } catch {
3090
3610
  return null;
3091
3611
  }
3092
3612
  }
3093
3613
  function writeJson(p, data) {
3094
- (0, import_node_fs5.writeFileSync)(p, JSON.stringify(data, null, 2), JSON_OPTS);
3614
+ (0, import_node_fs6.writeFileSync)(p, JSON.stringify(data, null, 2), JSON_OPTS);
3095
3615
  }
3096
3616
  async function mapPool(items, limit, fn) {
3097
3617
  const results = new Array(items.length);
@@ -3109,6 +3629,12 @@ async function mapPool(items, limit, fn) {
3109
3629
  function has(passes, p) {
3110
3630
  return passes.includes(p);
3111
3631
  }
3632
+ var ASR_NAMES = {
3633
+ assemblyai: "AssemblyAI",
3634
+ elevenlabs: "ElevenLabs Scribe",
3635
+ "whisper-groq": "Groq Whisper",
3636
+ none: "none"
3637
+ };
3112
3638
  function stageTag(name) {
3113
3639
  return (err) => {
3114
3640
  const msg = err instanceof Error ? err.message : String(err);
@@ -3118,6 +3644,37 @@ function stageTag(name) {
3118
3644
  throw e;
3119
3645
  };
3120
3646
  }
3647
+ async function preflight(opts) {
3648
+ const options = resolveOptions(opts);
3649
+ const keys = resolveKeys(options.apiKeys);
3650
+ if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
3651
+ if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
3652
+ if (!has(options.passes, "timestamped") && !has(options.passes, "align")) return;
3653
+ const tsProvider = options.timestampedProvider ?? "assemblyai";
3654
+ if (tsProvider === "assemblyai" && !keys.assemblyai) {
3655
+ throw new Error(
3656
+ "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
3657
+ );
3658
+ }
3659
+ if (tsProvider === "whisper-groq" && !keys.groq) {
3660
+ throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
3661
+ }
3662
+ if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
3663
+ throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3664
+ }
3665
+ }
3666
+ function estimateRun(opts, durationSec) {
3667
+ const options = resolveOptions(opts);
3668
+ return estimateRunCost({
3669
+ durationSec,
3670
+ model: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
3671
+ reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL,
3672
+ tsProvider: options.timestampedProvider ?? "assemblyai",
3673
+ chunkSec: options.chunkDurationSec,
3674
+ overlapSec: options.chunkOverlapSec,
3675
+ identify: options.diarizationLevel >= 3 && has(options.passes, "identify")
3676
+ });
3677
+ }
3121
3678
  async function transcribe(opts) {
3122
3679
  if (!opts || typeof opts.input !== "string" || opts.input.length === 0) {
3123
3680
  throw new Error(
@@ -3127,11 +3684,11 @@ async function transcribe(opts) {
3127
3684
  const options = resolveOptions(opts);
3128
3685
  const keys = resolveKeys(options.apiKeys);
3129
3686
  logger.setLevel(options.logLevel);
3130
- if (!(0, import_node_fs5.existsSync)(options.input)) {
3687
+ if (!(0, import_node_fs6.existsSync)(options.input)) {
3131
3688
  throw new Error(`Input file not found: ${options.input}`);
3132
3689
  }
3133
- (0, import_node_fs5.mkdirSync)(options.intermediatesDir, { recursive: true });
3134
- (0, import_node_fs5.mkdirSync)(options.outputDir, { recursive: true });
3690
+ (0, import_node_fs6.mkdirSync)(options.intermediatesDir, { recursive: true });
3691
+ (0, import_node_fs6.mkdirSync)(options.outputDir, { recursive: true });
3135
3692
  logger.info(
3136
3693
  `intermediates: ${(0, import_node_path6.resolve)(options.intermediatesDir)} (file://${(0, import_node_path6.resolve)(options.intermediatesDir)})`
3137
3694
  );
@@ -3170,23 +3727,11 @@ async function transcribe(opts) {
3170
3727
  const checkAbort = () => {
3171
3728
  options.signal?.throwIfAborted();
3172
3729
  };
3173
- if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
3174
- if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
3730
+ const emit = (event) => emitTo(options.onProgress, event);
3731
+ const geminiOpts = { zeroStorage: options.zeroStorage };
3732
+ await preflight(opts);
3175
3733
  const tsProvider = options.timestampedProvider ?? "assemblyai";
3176
3734
  const willTimestamp = has(passes, "timestamped") || has(passes, "align");
3177
- if (willTimestamp) {
3178
- if (tsProvider === "assemblyai" && !keys.assemblyai) {
3179
- throw new Error(
3180
- "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
3181
- );
3182
- }
3183
- if (tsProvider === "whisper-groq" && !keys.groq) {
3184
- throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
3185
- }
3186
- if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
3187
- throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3188
- }
3189
- }
3190
3735
  let probeInfo = null;
3191
3736
  const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
3192
3737
  const audioPath = `${options.intermediatesDir}/audio.mp3`;
@@ -3194,12 +3739,13 @@ async function transcribe(opts) {
3194
3739
  if (has(passes, "preprocess")) {
3195
3740
  checkAbort();
3196
3741
  logger.info("=== preprocess ===");
3742
+ emit({ type: "stage", stage: "preprocess", state: "start" });
3197
3743
  probeInfo = forceAll ? null : readJson(probePath);
3198
3744
  if (!probeInfo) {
3199
3745
  probeInfo = await probe(options.input).catch(stageTag("preprocess"));
3200
3746
  writeJson(probePath, probeInfo);
3201
3747
  }
3202
- if (!(0, import_node_fs5.existsSync)(audioPath) || forceAll) {
3748
+ if (!(0, import_node_fs6.existsSync)(audioPath) || forceAll) {
3203
3749
  logger.info("extracting audio (mono 16kHz mp3)...");
3204
3750
  await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
3205
3751
  stageTag("preprocess")
@@ -3207,7 +3753,7 @@ async function transcribe(opts) {
3207
3753
  }
3208
3754
  if (probeInfo.hasVideo) {
3209
3755
  const kfDir = `${options.intermediatesDir}/keyframes`;
3210
- if (!(0, import_node_fs5.existsSync)(kfDir) || forceAll) {
3756
+ if (!(0, import_node_fs6.existsSync)(kfDir) || forceAll) {
3211
3757
  logger.info("extracting keyframes...");
3212
3758
  await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
3213
3759
  (err) => {
@@ -3223,26 +3769,124 @@ async function transcribe(opts) {
3223
3769
  }
3224
3770
  if (!probeInfo) throw new Error("probe info missing (run preprocess)");
3225
3771
  const duration = probeInfo.duration;
3226
- const estimate = estimateRunCost({
3772
+ const estimate = estimateRun(opts, duration);
3773
+ logger.info(
3774
+ `estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
3775
+ );
3776
+ const naming = options.diarizationLevel >= 3 && has(passes, "identify");
3777
+ const reasonerA = naming || options.summary ? resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys, geminiOpts) : null;
3778
+ const reasonerB = naming && reasonerA && options.identifyMode === "dual" ? resolveSecondReasoner(reasonerA.info, keys, geminiOpts) : null;
3779
+ const asksAssemblyAI = willTimestamp && tsProvider === "assemblyai";
3780
+ const notAsked = options.zeroStorage ? [
3781
+ ...willTimestamp && (tsProvider === "elevenlabs" || tsProvider === "whisper-groq") ? [{ name: ASR_NAMES[tsProvider], role: "timing" }] : [],
3782
+ ...[reasonerA, reasonerB].flatMap(
3783
+ (r) => r && r.info.provider !== "gemini" ? [{ name: r.info.model, role: "text" }] : []
3784
+ )
3785
+ ] : [];
3786
+ if (options.zeroStorage) {
3787
+ logger.info(
3788
+ `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` : ""}`
3789
+ );
3790
+ }
3791
+ emit({
3792
+ type: "plan",
3227
3793
  durationSec: duration,
3228
3794
  model: models.transcribe,
3229
- reasoner: models.reasoner,
3230
- tsProvider,
3231
- chunkSec: options.chunkDurationSec,
3232
- overlapSec: options.chunkOverlapSec,
3233
- identify: options.diarizationLevel >= 3 && has(passes, "identify")
3795
+ asr: ASR_NAMES[tsProvider],
3796
+ estimateUsd: estimate.totalUsd,
3797
+ zeroStorage: options.zeroStorage,
3798
+ notAsked
3234
3799
  });
3235
- logger.info(
3236
- `estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
3800
+ const runTimestamped = async () => {
3801
+ if (!has(passes, "timestamped") && !has(passes, "align")) {
3802
+ const cached = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
3803
+ return { result: cached, billed: false };
3804
+ }
3805
+ checkAbort();
3806
+ if (tsProvider === "none") {
3807
+ logger.info("=== timestamped: none (the LLM's own timestamps are used) ===");
3808
+ return { result: null, billed: false };
3809
+ }
3810
+ if (tsProvider === "whisper-groq") {
3811
+ logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
3812
+ if (!(0, import_node_fs6.existsSync)(audioPath))
3813
+ await extractAudio(options.input, audioPath, AUDIO_OPTS);
3814
+ const groq = new WhisperGroqClient(keys.groq);
3815
+ const result3 = await groq.transcribe(await (0, import_promises3.readFile)(audioPath), { language: options.language }).catch(stageTag("asr"));
3816
+ writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
3817
+ return { result: result3, billed: true };
3818
+ }
3819
+ if (tsProvider === "elevenlabs") {
3820
+ logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
3821
+ const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs${options.language ? `-${options.language}` : ""}.json`;
3822
+ let result3 = forceAll ? null : readJson(cachePath);
3823
+ let billed = false;
3824
+ if (!result3) {
3825
+ const el = new ElevenLabsClient(keys.elevenlabs);
3826
+ result3 = await el.transcribe(await (0, import_promises3.readFile)(audioPath), { languageCode: options.language }).catch(stageTag("asr"));
3827
+ billed = true;
3828
+ writeJson(cachePath, result3);
3829
+ } else {
3830
+ logger.info("[elevenlabs] cache hit");
3831
+ }
3832
+ writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
3833
+ logger.info(
3834
+ `[elevenlabs] ${result3.utterances.length} utterances, ${result3.words.length} words`
3835
+ );
3836
+ return { result: result3, billed };
3837
+ }
3838
+ logger.info("=== timestamped (AssemblyAI) ===");
3839
+ const aai = new AssemblyAIProvider({
3840
+ apiKey: keys.assemblyai,
3841
+ cacheDir: `${options.intermediatesDir}/assemblyai`,
3842
+ language: options.language,
3843
+ zeroStorage: options.zeroStorage
3844
+ });
3845
+ const result2 = await aai.transcribe(audioPath).catch(stageTag("asr"));
3846
+ writeJson(`${options.intermediatesDir}/timestamped.json`, result2);
3847
+ return { result: result2, billed: !aai.lastFromCache };
3848
+ };
3849
+ const asrName = ASR_NAMES[tsProvider];
3850
+ if (willTimestamp && tsProvider !== "none") {
3851
+ emit({ type: "asr", provider: asrName, state: "start" });
3852
+ }
3853
+ const asrRun = runTimestamped().then(
3854
+ (r) => {
3855
+ if (willTimestamp && r.result) {
3856
+ const speakers2 = new Set(r.result.utterances.map((u) => u.speaker)).size;
3857
+ emit({
3858
+ type: "asr",
3859
+ provider: asrName,
3860
+ state: r.billed ? "done" : "cached",
3861
+ words: r.result.words.length,
3862
+ speakers: speakers2 || void 0,
3863
+ language: r.result.languageCode
3864
+ });
3865
+ }
3866
+ return r;
3867
+ },
3868
+ (err) => {
3869
+ emit({
3870
+ type: "asr",
3871
+ provider: asrName,
3872
+ state: "failed",
3873
+ error: err instanceof Error ? err.message : String(err)
3874
+ });
3875
+ throw err;
3876
+ }
3237
3877
  );
3878
+ asrRun.catch(() => void 0);
3238
3879
  let description = null;
3239
3880
  if (has(passes, "describe")) {
3240
3881
  const descPath = `${options.intermediatesDir}/description.json`;
3241
3882
  description = forceAll ? null : readJson(descPath);
3242
- if (!description) {
3883
+ if (description) {
3884
+ emit({ type: "stage", stage: "describe", state: "cached" });
3885
+ } else {
3243
3886
  checkAbort();
3244
3887
  logger.info("=== describe ===");
3245
- const client = new GeminiClient(keys.gemini);
3888
+ emit({ type: "stage", stage: "describe", state: "start" });
3889
+ const client = new GeminiClient(keys.gemini, geminiOpts);
3246
3890
  const sampleSpans = duration <= 360 ? [[0, duration]] : [
3247
3891
  [0, 150],
3248
3892
  [Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
@@ -3252,17 +3896,17 @@ async function transcribe(opts) {
3252
3896
  for (let i = 0; i < sampleSpans.length; i++) {
3253
3897
  const [s, e] = sampleSpans[i];
3254
3898
  const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
3255
- if (!(0, import_node_fs5.existsSync)(samplePath) || forceAll) {
3899
+ if (!(0, import_node_fs6.existsSync)(samplePath) || forceAll) {
3256
3900
  await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
3257
3901
  }
3258
3902
  files.push({ path: samplePath });
3259
3903
  }
3260
3904
  const audioSampleCount = files.length;
3261
3905
  const kfDir = `${options.intermediatesDir}/keyframes`;
3262
- if ((0, import_node_fs5.existsSync)(kfDir)) {
3906
+ if ((0, import_node_fs6.existsSync)(kfDir)) {
3263
3907
  for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
3264
3908
  const p = `${kfDir}/${f}`;
3265
- if ((0, import_node_fs5.existsSync)(p)) files.push({ path: p });
3909
+ if ((0, import_node_fs6.existsSync)(p)) files.push({ path: p });
3266
3910
  }
3267
3911
  }
3268
3912
  description = await describeMeeting(
@@ -3291,14 +3935,14 @@ async function transcribe(opts) {
3291
3935
  }
3292
3936
  chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
3293
3937
  if (silences.length > 3) {
3294
- chunks = chunks.map((c) => {
3295
- const snapped = snapToSilence(
3938
+ chunks = chunks.map((c) => ({
3939
+ ...c,
3940
+ start: snapToSilence(
3296
3941
  c.start,
3297
3942
  silences,
3298
3943
  Math.min(10, options.chunkOverlapSec / 2)
3299
- );
3300
- return { ...c, start: snapped, trustedStart: snapped + c.overlapWithPrevious };
3301
- });
3944
+ )
3945
+ }));
3302
3946
  }
3303
3947
  }
3304
3948
  const tagWith = (r, chunk) => ({
@@ -3306,21 +3950,26 @@ async function transcribe(opts) {
3306
3950
  segments: r.segments.map((s) => ({
3307
3951
  ...s,
3308
3952
  chunkIndex: chunk.index,
3309
- trustedStart: chunk.trustedStart
3953
+ trustedStart: chunk.trustedStart,
3954
+ chunkStart: chunk.start,
3955
+ chunkEnd: chunk.end
3310
3956
  }))
3311
3957
  });
3958
+ const llmDir = `${options.intermediatesDir}/llm`;
3312
3959
  let llmChunkResults = [];
3960
+ let llmChunkPlans = [];
3313
3961
  if (has(passes, "llm-transcribe")) {
3314
3962
  logger.info("=== llm-transcribe ===");
3963
+ emit({ type: "stage", stage: "transcribe", state: "start" });
3315
3964
  let runChunks = chunks;
3316
3965
  if (options.onlyChunk !== void 0)
3317
3966
  runChunks = chunks.filter((c) => c.index === options.onlyChunk);
3318
3967
  logger.info(
3319
3968
  `${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`
3320
3969
  );
3321
- const client = new GeminiClient(keys.gemini);
3322
- const llmDir = `${options.intermediatesDir}/llm`;
3323
- (0, import_node_fs5.mkdirSync)(llmDir, { recursive: true });
3970
+ emit({ type: "chunks", total: runChunks.length, chunkSec: options.chunkDurationSec });
3971
+ const client = new GeminiClient(keys.gemini, geminiOpts);
3972
+ (0, import_node_fs6.mkdirSync)(llmDir, { recursive: true });
3324
3973
  const partialPath = `${options.outputDir}/${(0, import_node_path6.basename)(options.input, ext(options.input))}.partial.md`;
3325
3974
  const completed = [];
3326
3975
  const writePartial = () => {
@@ -3332,7 +3981,7 @@ async function transcribe(opts) {
3332
3981
  const ss = Math.floor(s.startSec % 60).toString().padStart(2, "0");
3333
3982
  return `[${mm}:${ss}] **${s.speaker}**: ${s.text}`;
3334
3983
  });
3335
- (0, import_node_fs5.writeFileSync)(
3984
+ (0, import_node_fs6.writeFileSync)(
3336
3985
  partialPath,
3337
3986
  `> Partial transcript (run in progress \u2014 coarse LLM timings, speakers not yet unified)
3338
3987
 
@@ -3348,25 +3997,23 @@ ${lines.join("\n\n")}
3348
3997
  const cached = forceAll ? null : readJson(parsedPath);
3349
3998
  if (cached && cached.segments.length > 0) {
3350
3999
  logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
4000
+ emit({
4001
+ type: "chunk",
4002
+ index: chunk.index,
4003
+ state: "cached",
4004
+ segments: cached.segments.length
4005
+ });
3351
4006
  completed.push(cached);
3352
4007
  return tagWith(cached, chunk);
3353
4008
  }
3354
4009
  const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
3355
- if (!(0, import_node_fs5.existsSync)(chunkPath) || forceAll) {
4010
+ if (!(0, import_node_fs6.existsSync)(chunkPath) || forceAll) {
3356
4011
  await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
3357
4012
  }
3358
- let previousTail;
3359
- if (chunk.index > 0) {
3360
- const prev = readJson(
3361
- `${llmDir}/chunk_${String(chunk.index - 1).padStart(2, "0")}_parsed.json`
3362
- );
3363
- if (prev && prev.segments.length) {
3364
- previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
3365
- }
3366
- }
3367
4013
  logger.info(
3368
4014
  `chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`
3369
4015
  );
4016
+ emit({ type: "chunk", index: chunk.index, state: "running" });
3370
4017
  const result2 = await transcribeChunk(
3371
4018
  client,
3372
4019
  models.transcribe,
@@ -3377,13 +4024,20 @@ ${lines.join("\n\n")}
3377
4024
  total: runChunks.length,
3378
4025
  description: description?.description,
3379
4026
  roster: description?.roster,
3380
- previousTail,
3381
4027
  instructions: options.instructions
3382
4028
  },
3383
4029
  { chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
3384
4030
  );
3385
4031
  writeJson(parsedPath, result2);
3386
- (0, import_node_fs5.writeFileSync)(
4032
+ emit(
4033
+ result2.error && result2.segments.length === 0 ? { type: "chunk", index: chunk.index, state: "failed", error: result2.error } : {
4034
+ type: "chunk",
4035
+ index: chunk.index,
4036
+ state: "done",
4037
+ segments: result2.segments.length
4038
+ }
4039
+ );
4040
+ (0, import_node_fs6.writeFileSync)(
3387
4041
  `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
3388
4042
  result2.raw
3389
4043
  );
@@ -3391,6 +4045,7 @@ ${lines.join("\n\n")}
3391
4045
  writePartial();
3392
4046
  return tagWith(result2, chunk);
3393
4047
  });
4048
+ llmChunkPlans = runChunks;
3394
4049
  const errored = llmChunkResults.filter((r) => r.error);
3395
4050
  const producedSegments = llmChunkResults.reduce((n, r) => n + r.segments.length, 0);
3396
4051
  if (llmChunkResults.length > 0 && producedSegments === 0 && errored.length === llmChunkResults.length) {
@@ -3399,16 +4054,118 @@ ${lines.join("\n\n")}
3399
4054
  );
3400
4055
  }
3401
4056
  } else {
3402
- const llmDir = `${options.intermediatesDir}/llm`;
3403
- if (!forceAll && (0, import_node_fs5.existsSync)(llmDir)) {
3404
- const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
3405
- llmChunkResults = files.map((f, i) => {
3406
- const r = readJson(`${llmDir}/${f}`);
3407
- return r && chunks[i] ? tagWith(r, chunks[i]) : r;
3408
- }).filter(Boolean);
4057
+ if (!forceAll && (0, import_node_fs6.existsSync)(llmDir)) {
4058
+ for (const f of (0, import_node_fs6.readdirSync)(llmDir).sort()) {
4059
+ const m = /^chunk_(\d+)_parsed\.json$/.exec(f);
4060
+ const plan = m ? chunks.find((c) => c.index === Number(m[1])) : void 0;
4061
+ const r = plan ? readJson(`${llmDir}/${f}`) : null;
4062
+ if (r && plan) {
4063
+ llmChunkResults.push(tagWith(r, plan));
4064
+ llmChunkPlans.push(plan);
4065
+ }
4066
+ }
3409
4067
  }
3410
4068
  }
4069
+ const { result: asrResult, billed: asrBilled } = await asrRun;
4070
+ const quality = [];
4071
+ if (asrResult?.words.length) {
4072
+ let client;
4073
+ for (let i = 0; i < llmChunkResults.length; i++) {
4074
+ const plan = llmChunkPlans[i];
4075
+ const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
4076
+ let cov = chunkCoverage(
4077
+ llmChunkResults[i].segments,
4078
+ asrResult.words,
4079
+ plan.start,
4080
+ plan.end
4081
+ );
4082
+ let status = cov.low ? "low-coverage" : "ok";
4083
+ if (cov.low) {
4084
+ const retryPath = `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}_retry_parsed.json`;
4085
+ let retry = forceAll ? null : readJson(retryPath);
4086
+ const span = { index: plan.index, startSec: plan.start, endSec: plan.end };
4087
+ if (!retry && has(passes, "llm-transcribe")) {
4088
+ checkAbort();
4089
+ logger.warn(
4090
+ `${where}: ${cov.llmWords} words transcribed where the ASR heard ${cov.asrWords} \u2014 transcribing it again in two halves`
4091
+ );
4092
+ emit({
4093
+ type: "guard",
4094
+ ...span,
4095
+ state: "retrying",
4096
+ llmWords: cov.llmWords,
4097
+ asrWords: cov.asrWords
4098
+ });
4099
+ client ??= new GeminiClient(keys.gemini, geminiOpts);
4100
+ retry = await transcribeInHalves({
4101
+ client,
4102
+ model: models.transcribe,
4103
+ audioPath,
4104
+ chunk: plan,
4105
+ pathPrefix: `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}`,
4106
+ ctx: {
4107
+ index: plan.index + 1,
4108
+ total: chunks.length,
4109
+ description: description?.description,
4110
+ roster: description?.roster,
4111
+ instructions: options.instructions
4112
+ },
4113
+ audioOpts: AUDIO_OPTS
4114
+ }).catch(stageTag("llm-transcribe"));
4115
+ writeJson(retryPath, retry);
4116
+ }
4117
+ if (retry) {
4118
+ const again = chunkCoverage(
4119
+ retry.segments,
4120
+ asrResult.words,
4121
+ plan.start,
4122
+ plan.end
4123
+ );
4124
+ logger.info(
4125
+ `${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"}`
4126
+ );
4127
+ const kept = again.ratio > cov.ratio;
4128
+ emit({
4129
+ type: "guard",
4130
+ ...span,
4131
+ state: kept ? "recovered" : "unchanged",
4132
+ llmWords: cov.llmWords,
4133
+ asrWords: cov.asrWords,
4134
+ retryWords: again.llmWords
4135
+ });
4136
+ if (kept) {
4137
+ llmChunkResults[i] = tagWith(retry, plan);
4138
+ cov = again;
4139
+ status = again.low ? "low-coverage" : "retried";
4140
+ }
4141
+ }
4142
+ }
4143
+ quality.push({
4144
+ chunk: plan.index,
4145
+ start: plan.start,
4146
+ end: plan.end,
4147
+ status,
4148
+ llmWords: cov.llmWords,
4149
+ asrWords: cov.asrWords,
4150
+ coverage: Number.isFinite(cov.ratio) ? Number(cov.ratio.toFixed(2)) : null
4151
+ });
4152
+ }
4153
+ }
4154
+ const whole = asrResult?.words.length ? chunkCoverage(
4155
+ llmChunkResults.flatMap((r) => r.segments),
4156
+ asrResult.words,
4157
+ 0,
4158
+ Infinity
4159
+ ) : null;
4160
+ const asrMissedSpeech = !!whole && whole.llmWords >= 200 && whole.ratio > 3;
4161
+ if (asrMissedSpeech) {
4162
+ logger.warn(
4163
+ `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)`
4164
+ );
4165
+ }
3411
4166
  let allLlmSegments = llmChunkResults.flatMap((r) => r.segments);
4167
+ const timingWords = asrMissedSpeech ? [] : asrResult?.words ?? [];
4168
+ allLlmSegments = toAsrClock(allLlmSegments, timingWords);
3412
4169
  const beforePart = allLlmSegments.length;
3413
4170
  allLlmSegments = partitionByOwnership(allLlmSegments);
3414
4171
  if (beforePart !== allLlmSegments.length) {
@@ -3417,81 +4174,68 @@ ${lines.join("\n\n")}
3417
4174
  );
3418
4175
  }
3419
4176
  logger.info(`total LLM segments: ${allLlmSegments.length}`);
3420
- let asrResult = null;
3421
- if (has(passes, "timestamped") || has(passes, "align")) {
3422
- checkAbort();
3423
- const provider = options.timestampedProvider ?? "assemblyai";
3424
- if (provider === "whisper-groq") {
3425
- logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
3426
- if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
3427
- if (!(0, import_node_fs5.existsSync)(audioPath) || forceAll) {
3428
- await extractAudio(options.input, audioPath, AUDIO_OPTS);
4177
+ if (asrResult?.words.length && (has(passes, "align") || has(passes, "consistency"))) {
4178
+ const dropped = /* @__PURE__ */ new Set();
4179
+ for (let i = 0; i < llmChunkResults.length; i++) {
4180
+ const r = llmChunkResults[i];
4181
+ const plan = llmChunkPlans[i];
4182
+ const q = quality.find((x) => x.chunk === plan.index);
4183
+ const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
4184
+ const compression = maxCompressionRatio(r.segments.map((s) => s.text).join(" "));
4185
+ if (compression > DEGENERATE_COMPRESSION_RATIO) {
4186
+ dropped.add(plan.index);
4187
+ if (q) q.status = "dropped-loop";
4188
+ logger.warn(
4189
+ `${where}: dropping repetition-loop text (compression ratio ${compression.toFixed(1)}) \u2014 ASR will fill this range`
4190
+ );
4191
+ continue;
3429
4192
  }
3430
- const { readFile: readFile2 } = await import("fs/promises");
3431
- const buf = await readFile2(audioPath);
3432
- const groq = new WhisperGroqClient(keys.groq);
3433
- asrResult = await groq.transcribe(buf).catch(stageTag("asr"));
3434
- writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3435
- } else if (provider === "elevenlabs") {
3436
- logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
3437
- if (!keys.elevenlabs)
3438
- throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3439
- const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs.json`;
3440
- asrResult = forceAll ? null : readJson(cachePath);
3441
- if (!asrResult) {
3442
- const { readFile: readFile2 } = await import("fs/promises");
3443
- const buf = await readFile2(audioPath);
3444
- const el = new ElevenLabsClient(keys.elevenlabs);
3445
- asrResult = await el.transcribe(buf).catch(stageTag("asr"));
3446
- writeJson(cachePath, asrResult);
3447
- } else {
3448
- logger.info("[elevenlabs] cache hit");
4193
+ const g = chunkGrounding(r.segments, asrResult.words, plan.start, plan.end);
4194
+ if (!g.grounded) {
4195
+ if (q) q.ungrounded = true;
4196
+ logger.warn(
4197
+ `${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)`
4198
+ );
3449
4199
  }
3450
- writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3451
- logger.info(
3452
- `[elevenlabs] ${asrResult.utterances.length} utterances, ${asrResult.words.length} words, ${asrResult.speakers?.length ?? "?"} speakers`
4200
+ }
4201
+ if (dropped.size) {
4202
+ allLlmSegments = allLlmSegments.filter(
4203
+ (s) => s.chunkIndex === void 0 || !dropped.has(s.chunkIndex)
3453
4204
  );
3454
- } else {
3455
- logger.info("=== timestamped (AssemblyAI) ===");
3456
- if (!keys.assemblyai)
3457
- throw new Error(
3458
- "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
3459
- );
3460
- const aai = new AssemblyAIProvider({
3461
- apiKey: keys.assemblyai,
3462
- cacheDir: `${options.intermediatesDir}/assemblyai`
3463
- });
3464
- asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
3465
- writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3466
4205
  }
3467
- } else {
3468
- asrResult = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
3469
4206
  }
3470
4207
  let aligned = [];
3471
- if (has(passes, "align") && asrResult) {
4208
+ if (has(passes, "align") && (asrResult || tsProvider === "none")) {
3472
4209
  logger.info("=== align ===");
3473
- aligned = alignSegments(allLlmSegments, asrResult.words, { timeMarginSec: 30 });
4210
+ emit({ type: "stage", stage: "align", state: "start" });
4211
+ aligned = alignSegments(allLlmSegments, timingWords, { timeMarginSec: 30 });
3474
4212
  writeJson(`${options.intermediatesDir}/aligned.json`, aligned);
3475
4213
  } else {
3476
4214
  aligned = (forceAll ? null : readJson(`${options.intermediatesDir}/aligned.json`)) ?? [];
3477
4215
  }
3478
4216
  const alignedOk = aligned.filter((a) => a.timingSource !== "coarse").length;
3479
4217
  logger.info(`aligned: ${alignedOk}/${aligned.length} with ASR timing`);
3480
- if (asrResult && (has(passes, "align") || has(passes, "consistency"))) {
3481
- const before = aligned.length;
4218
+ let gapFilledWords = 0;
4219
+ if (asrResult && !asrMissedSpeech && (has(passes, "align") || has(passes, "consistency"))) {
3482
4220
  aligned = fillAsrGaps(aligned, asrResult.words, asrResult.utterances);
3483
- const added = aligned.length - before;
3484
- if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
4221
+ const added = aligned.filter((a) => a.timingSource === "timestamped");
4222
+ gapFilledWords = added.reduce((n, a) => n + a.words.length, 0);
4223
+ if (added.length) {
4224
+ logger.info(
4225
+ `gap-filled ${added.length} ASR fallback segment(s) (${gapFilledWords} words)`
4226
+ );
4227
+ }
3485
4228
  }
3486
4229
  if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
3487
4230
  aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
3488
4231
  }
3489
4232
  let segments = aligned;
3490
4233
  let speakers = [];
3491
- if (has(passes, "consistency") && asrResult) {
4234
+ if (has(passes, "consistency") && (asrResult || tsProvider === "none")) {
3492
4235
  logger.info("=== consistency ===");
3493
- const cons = assignGlobalSpeakers(aligned, asrResult.utterances, {
3494
- hasDiarization: asrResult.hasDiarization ?? true
4236
+ emit({ type: "stage", stage: "speakers", state: "start" });
4237
+ const cons = assignGlobalSpeakers(aligned, asrResult?.utterances ?? [], {
4238
+ hasDiarization: asrResult ? asrResult.hasDiarization ?? true : false
3495
4239
  });
3496
4240
  segments = cons.segments;
3497
4241
  speakers = cons.speakers;
@@ -3513,19 +4257,22 @@ ${lines.join("\n\n")}
3513
4257
  (s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
3514
4258
  );
3515
4259
  speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
3516
- if (options.diarizationLevel >= 3 && has(passes, "identify")) {
3517
- const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
4260
+ if (naming) {
3518
4261
  if (!reasonerA) {
3519
4262
  logger.warn(
3520
4263
  "identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
3521
4264
  );
3522
4265
  } else {
3523
4266
  const mode = options.identifyMode;
3524
- const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
3525
4267
  const idConfig = {
3526
4268
  mode,
3527
4269
  reasonerA: reasonerA.info.model,
3528
- reasonerB: reasonerB?.info.model ?? null
4270
+ reasonerB: reasonerB?.info.model ?? null,
4271
+ knownSpeakers: options.knownSpeakers ?? [],
4272
+ // What the naming step reads. If a re-run changes the transcript (a re-transcribed
4273
+ // chunk can reorder speakers by talk time), "Speaker A" may now be the other voice,
4274
+ // and the cached names must not be applied to it.
4275
+ inputs: (0, import_node_crypto3.createHash)("sha1").update(JSON.stringify(segments.map((s) => [s.speaker, s.text]))).update(JSON.stringify(speakers.map((sp) => sp.id))).digest("hex")
3529
4276
  };
3530
4277
  const idCachePath = `${options.intermediatesDir}/identified.json`;
3531
4278
  const cachedId = forceAll ? null : readJson(
@@ -3535,11 +4282,18 @@ ${lines.join("\n\n")}
3535
4282
  let nameMap = null;
3536
4283
  if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
3537
4284
  logger.info("=== identify (cached) ===");
4285
+ emit({ type: "stage", stage: "identify", state: "cached" });
3538
4286
  nameMap = cachedId.nameMap;
3539
4287
  } else {
3540
4288
  logger.info(
3541
4289
  `=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
3542
4290
  );
4291
+ emit({
4292
+ type: "stage",
4293
+ stage: "identify",
4294
+ state: "start",
4295
+ detail: reasonerB ? `${reasonerA.info.model} + ${reasonerB.info.model}` : reasonerA.info.model
4296
+ });
3543
4297
  checkAbort();
3544
4298
  const id = await identifySpeakersV2(
3545
4299
  {
@@ -3564,11 +4318,14 @@ ${lines.join("\n\n")}
3564
4318
  ).catch(stageTag("identify"));
3565
4319
  writeJson(idCachePath, { ...id, config: idConfig });
3566
4320
  nameMap = id.nameMap;
4321
+ if (id.allPassesFailed)
4322
+ emit({ type: "stage", stage: "identify", state: "failed" });
3567
4323
  }
3568
4324
  logger.info(
3569
4325
  `identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
3570
4326
  );
3571
4327
  const nm = nameMap;
4328
+ emit({ type: "names", names: nm });
3572
4329
  segments = segments.map(
3573
4330
  (s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
3574
4331
  );
@@ -3578,13 +4335,14 @@ ${lines.join("\n\n")}
3578
4335
  let finalSegments = [];
3579
4336
  if (has(passes, "finalize")) {
3580
4337
  logger.info("=== finalize ===");
4338
+ emit({ type: "stage", stage: "finalize", state: "start" });
3581
4339
  finalSegments = finalizeSegments(segments);
3582
4340
  writeJson(`${options.intermediatesDir}/final.json`, finalSegments);
3583
4341
  } else {
3584
4342
  finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
3585
4343
  }
3586
4344
  logger.info(`final segments: ${finalSegments.length}`);
3587
- const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
4345
+ const receipt = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
3588
4346
  const wallMs = Date.now() - runStartedAt;
3589
4347
  const metadata = {
3590
4348
  sourceFile: options.input,
@@ -3604,86 +4362,103 @@ ${lines.join("\n\n")}
3604
4362
  llmCalls: receipt.totals.calls,
3605
4363
  inputTokens: receipt.totals.inputTokens,
3606
4364
  outputTokens: receipt.totals.outputTokens
3607
- }
4365
+ },
4366
+ ...asrResult ? { quality: { chunks: quality, gapFilledWords, asrMissedSpeech } } : {},
4367
+ zeroStorage: options.zeroStorage
3608
4368
  };
4369
+ const degraded = quality.filter((q) => q.status !== "ok");
4370
+ if (degraded.length || asrMissedSpeech) {
4371
+ logger.warn(
4372
+ `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`
4373
+ );
4374
+ }
3609
4375
  const result = { segments: finalSegments, speakers, metadata };
3610
4376
  writeJson(`${options.intermediatesDir}/result.json`, result);
4377
+ const base = (0, import_node_path6.basename)(options.input, ext(options.input));
4378
+ const written = [];
4379
+ const write = (name, content) => {
4380
+ const path = `${options.outputDir}/${name}`;
4381
+ (0, import_node_fs6.writeFileSync)(path, content);
4382
+ written.push((0, import_node_path6.resolve)(path));
4383
+ };
3611
4384
  for (const fmt of options.formats) {
3612
- const base = (0, import_node_path6.basename)(options.input, ext(options.input));
3613
- if (fmt === "srt")
3614
- (0, import_node_fs5.writeFileSync)(
3615
- `${options.outputDir}/${base}.srt`,
3616
- formatSrt(result, { title: base })
3617
- );
4385
+ if (fmt === "srt") write(`${base}.srt`, formatSrt(result, { title: base }));
3618
4386
  if (fmt === "md")
3619
- (0, import_node_fs5.writeFileSync)(
3620
- `${options.outputDir}/${base}.md`,
4387
+ write(
4388
+ `${base}.md`,
3621
4389
  formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
3622
4390
  );
3623
- if (fmt === "txt")
3624
- (0, import_node_fs5.writeFileSync)(
3625
- `${options.outputDir}/${base}.txt`,
3626
- formatText(result, { title: base })
3627
- );
3628
- if (fmt === "html")
3629
- (0, import_node_fs5.writeFileSync)(
3630
- `${options.outputDir}/${base}.html`,
3631
- formatHtml(result, { title: base })
3632
- );
3633
- if (fmt === "json")
3634
- (0, import_node_fs5.writeFileSync)(`${options.outputDir}/${base}.json`, formatJson(result));
4391
+ if (fmt === "txt") write(`${base}.txt`, formatText(result, { title: base }));
4392
+ if (fmt === "html") write(`${base}.html`, formatHtml(result, { title: base }));
4393
+ if (fmt === "json") write(`${base}.json`, formatJson(result));
3635
4394
  }
3636
4395
  if (options.summary && finalSegments.length > 0) {
3637
- const reasoner = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
3638
- if (!reasoner) {
4396
+ if (!reasonerA) {
3639
4397
  logger.warn("summary: no reasoner-capable key \u2014 skipping");
3640
4398
  } else {
3641
- logger.info(`=== summary (${reasoner.info.model}) ===`);
4399
+ logger.info(`=== summary (${reasonerA.info.model}) ===`);
4400
+ emit({
4401
+ type: "stage",
4402
+ stage: "summary",
4403
+ state: "start",
4404
+ detail: reasonerA.info.model
4405
+ });
3642
4406
  try {
3643
4407
  const summary = await summarizeTranscript(
3644
- reasoner.client,
3645
- reasoner.info.model,
4408
+ reasonerA.client,
4409
+ reasonerA.info.model,
3646
4410
  result,
3647
4411
  options.instructions
3648
4412
  );
3649
- const base = (0, import_node_path6.basename)(options.input, ext(options.input));
3650
- (0, import_node_fs5.writeFileSync)(`${options.outputDir}/${base}.summary.md`, summary);
4413
+ write(`${base}.summary.md`, summary);
3651
4414
  logger.info(`summary written to ${base}.summary.md`);
3652
4415
  } catch (err) {
3653
4416
  logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
4417
+ emit({ type: "stage", stage: "summary", state: "failed" });
3654
4418
  }
3655
4419
  }
3656
4420
  }
3657
4421
  try {
3658
- const base = (0, import_node_path6.basename)(options.input, ext(options.input));
3659
4422
  const partial = `${options.outputDir}/${base}.partial.md`;
3660
- if ((0, import_node_fs5.existsSync)(partial)) (await import("fs/promises")).unlink(partial);
4423
+ if ((0, import_node_fs6.existsSync)(partial)) (await import("fs/promises")).unlink(partial);
3661
4424
  } catch {
3662
4425
  }
3663
4426
  logger.info(`outputs written to ${options.outputDir}`);
3664
- const mins = Math.floor(wallMs / 6e4);
3665
- const secs = Math.round(wallMs % 6e4 / 1e3);
4427
+ const spent = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
4428
+ const runMs = Date.now() - runStartedAt;
4429
+ const mins = Math.floor(runMs / 6e4);
4430
+ const secs = Math.round(runMs % 6e4 / 1e3);
3666
4431
  logger.info(
3667
- `receipt: ${receipt.totals.calls} LLM calls \xB7 ${(receipt.totals.inputTokens / 1e3).toFixed(0)}k in / ${(receipt.totals.outputTokens / 1e3).toFixed(0)}k out \xB7 ~$${receipt.totalUsd.toFixed(2)}${receipt.incomplete ? " (+unpriced)" : ""} \xB7 ${mins ? `${mins}m` : ""}${secs}s`
4432
+ `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`
3668
4433
  );
3669
- for (const line of receipt.lines) logger.info(` ${line}`);
4434
+ for (const line of spent.lines) logger.info(` ${line}`);
3670
4435
  recordRun(
3671
4436
  {
3672
4437
  ts: (/* @__PURE__ */ new Date()).toISOString(),
3673
4438
  input: (0, import_node_path6.basename)(options.input),
3674
4439
  durationSec: duration,
3675
- wallMs,
4440
+ wallMs: runMs,
3676
4441
  models: metadata.models,
3677
4442
  segments: finalSegments.length,
3678
4443
  characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
3679
4444
  speakers: speakers.length,
3680
- llmCalls: receipt.totals.calls,
3681
- inputTokens: receipt.totals.inputTokens,
3682
- outputTokens: receipt.totals.outputTokens,
3683
- costUsd: receipt.totalUsd
4445
+ llmCalls: spent.totals.calls,
4446
+ inputTokens: spent.totals.inputTokens,
4447
+ outputTokens: spent.totals.outputTokens,
4448
+ costUsd: spent.totalUsd
3684
4449
  },
3685
- receipt.perModel
4450
+ spent.perModel
3686
4451
  );
4452
+ emit({
4453
+ type: "done",
4454
+ segments: finalSegments.length,
4455
+ speakers: speakers.length,
4456
+ durationSec: duration,
4457
+ costUsd: spent.totalUsd,
4458
+ wallMs: runMs,
4459
+ retriedChunks: quality.filter((q) => q.status === "retried").length,
4460
+ outputs: written
4461
+ });
3687
4462
  return result;
3688
4463
  }
3689
4464
  function ext(p) {
@@ -3722,6 +4497,9 @@ function parseSrt(content) {
3722
4497
  }
3723
4498
  // Annotate the CommonJS export names for ESM import in node:
3724
4499
  0 && (module.exports = {
4500
+ DEFAULT_REASONER_MODEL,
4501
+ DEFAULT_TRANSCRIBE_MODEL,
4502
+ PRO_TRANSCRIBE_MODEL,
3725
4503
  alignSegments,
3726
4504
  assignGlobalSpeakers,
3727
4505
  finalizeSegments,
@@ -3731,6 +4509,7 @@ function parseSrt(content) {
3731
4509
  formatSrt,
3732
4510
  formatText,
3733
4511
  identifySpeakers,
4512
+ identifySpeakersV2,
3734
4513
  parseSrt,
3735
4514
  planChunks,
3736
4515
  summarizeTranscript,