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/cli.js CHANGED
@@ -1,17 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import { Command } from "commander";
4
+ import { Command, Option } from "commander";
5
5
  import { readFileSync as readFileSync6 } from "fs";
6
6
  import { fileURLToPath } from "url";
7
- import { dirname as dirname5, join as join5, basename as basename6, resolve as resolve4 } from "path";
7
+ import { dirname as dirname6, extname as extname3, join as join7, basename as basename8 } from "path";
8
8
 
9
9
  // src/core/pipeline.ts
10
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
10
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
11
+ import { readFile as readFile2 } from "fs/promises";
12
+
13
+ // src/core/models.ts
14
+ var DEFAULT_TRANSCRIBE_MODEL = "gemini-4-hydrogen";
15
+ var PRO_TRANSCRIBE_MODEL = "gemini-4-argon";
16
+ var DEFAULT_REASONER_MODEL = "deepseek-chat";
11
17
 
12
18
  // src/core/config.ts
13
19
  import { createHash } from "crypto";
14
- import { basename, dirname, resolve } from "path";
20
+ import { basename, dirname, join, resolve } from "path";
15
21
  import { statSync } from "fs";
16
22
  import { tmpdir } from "os";
17
23
  var DEFAULT_PASSES = [
@@ -23,19 +29,6 @@ var DEFAULT_PASSES = [
23
29
  "consistency",
24
30
  "finalize"
25
31
  ];
26
- var MODELS = {
27
- gemini25Pro: "gemini-2.5-pro",
28
- gemini25Flash: "gemini-2.5-flash",
29
- gemini3Pro: "gemini-3-pro-preview",
30
- gemini31Pro: "gemini-3.1-pro-preview",
31
- geminiFlashLatest: "gemini-flash-latest",
32
- deepseek: "deepseek-chat",
33
- deepseekReasoner: "deepseek-reasoner",
34
- gpt4o: "gpt-4o",
35
- claudeSonnet: "claude-sonnet-4-5"
36
- };
37
- var DEFAULT_TRANSCRIBE_MODEL = MODELS.gemini31Pro;
38
- var DEFAULT_REASONER_MODEL = MODELS.deepseek;
39
32
  function resolveKeys(injected) {
40
33
  const env = process.env;
41
34
  return {
@@ -87,19 +80,22 @@ function resolveOptions(opts) {
87
80
  model: opts.model,
88
81
  reasoner: opts.reasoner,
89
82
  timestampedProvider: opts.timestampedProvider,
83
+ language: opts.language,
90
84
  force: opts.force ?? false,
91
85
  onlyChunk: opts.onlyChunk,
92
86
  showProgress: opts.showProgress ?? true,
93
87
  llmLog: opts.llmLog ?? true,
94
88
  logLevel: opts.logLevel ?? "info",
95
- signal: opts.signal
89
+ signal: opts.signal,
90
+ onProgress: opts.onProgress,
91
+ zeroStorage: opts.zeroStorage ?? true
96
92
  };
97
93
  }
98
- function deriveIntermediatesDir(input) {
94
+ function deriveIntermediatesDir(input, parent = tmpdir()) {
99
95
  const abs = resolve(input);
100
96
  const hash = createHash("sha1").update(abs).digest("hex").slice(0, 8);
101
97
  const base = basename(input, extOf(input)) || "input";
102
- return `${tmpdir()}/offmute-v2-${base}-${hash}`;
98
+ return join(parent, `offmute-v2-${base}-${hash}`);
103
99
  }
104
100
  function extOf(p) {
105
101
  const i = p.lastIndexOf(".");
@@ -119,9 +115,7 @@ function inputSignature(input) {
119
115
  function configSignature(o) {
120
116
  const relevant = {
121
117
  model: o.model ?? DEFAULT_TRANSCRIBE_MODEL,
122
- reasoner: o.reasoner ?? DEFAULT_REASONER_MODEL,
123
118
  instructions: o.instructions ?? "",
124
- knownSpeakers: o.knownSpeakers ?? [],
125
119
  chunkDurationSec: o.chunkDurationSec ?? 600,
126
120
  chunkOverlapSec: o.chunkOverlapSec ?? 60,
127
121
  screenshotCount: o.screenshotCount ?? 6,
@@ -157,6 +151,15 @@ function planChunks(totalDuration, chunkDuration, overlap2) {
157
151
  return chunks;
158
152
  }
159
153
 
154
+ // src/core/progress.ts
155
+ function emitTo(listener, event) {
156
+ if (!listener) return;
157
+ try {
158
+ listener(event);
159
+ } catch {
160
+ }
161
+ }
162
+
160
163
  // src/utils/logger.ts
161
164
  var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
162
165
  var currentLevel = "info";
@@ -303,22 +306,22 @@ async function getSceneChangeTimes(input, threshold) {
303
306
  return [];
304
307
  }
305
308
  }
306
- async function extractKeyframes(input, outputDir, count, opts = {}) {
309
+ async function extractKeyframes(input, outputDir, count2, opts = {}) {
307
310
  await mkdir(outputDir, { recursive: true });
308
311
  const width = opts.width ?? 1280;
309
312
  const { duration } = await probe(input);
310
313
  if (!duration) return [];
311
314
  const sceneTimes = await getSceneChangeTimes(input, opts.sceneThreshold ?? 0.3);
312
315
  const times = [];
313
- if (sceneTimes.length >= count) {
314
- const step = sceneTimes.length / count;
315
- for (let i = 0; i < count; i++) {
316
+ if (sceneTimes.length >= count2) {
317
+ const step = sceneTimes.length / count2;
318
+ for (let i = 0; i < count2; i++) {
316
319
  const idx = Math.floor(i * step);
317
320
  times.push(sceneTimes[idx] ?? 0);
318
321
  }
319
322
  } else {
320
323
  times.push(...sceneTimes);
321
- const need = count - times.length;
324
+ const need = count2 - times.length;
322
325
  const start = duration * 0.02;
323
326
  const end = duration * 0.98;
324
327
  for (let i = 0; i < need; i++) {
@@ -390,7 +393,9 @@ function snapToSilence(boundary, silences, tolerance) {
390
393
  }
391
394
 
392
395
  // src/providers/gemini.ts
393
- import { GoogleGenAI } from "@google/genai";
396
+ import {
397
+ GoogleGenAI
398
+ } from "@google/genai";
394
399
  import { basename as basename2 } from "path";
395
400
 
396
401
  // src/providers/llm-log.ts
@@ -458,6 +463,38 @@ async function withRetry(label, fn, opts = {}) {
458
463
  throw lastErr;
459
464
  }
460
465
 
466
+ // src/providers/gemini-usage.ts
467
+ function usageFromMetadata(meta) {
468
+ const thoughtTokens = meta?.thoughtsTokenCount ?? 0;
469
+ return {
470
+ inputTokens: meta?.promptTokenCount ?? 0,
471
+ outputTokens: (meta?.candidatesTokenCount ?? 0) + thoughtTokens,
472
+ thoughtTokens,
473
+ totalTokens: meta?.totalTokenCount ?? 0
474
+ };
475
+ }
476
+
477
+ // src/providers/gemini-models.ts
478
+ function resolveThinking(model) {
479
+ const m = model.toLowerCase();
480
+ if (m.includes("gemini-2.0")) return void 0;
481
+ if (m.includes("gemini-4")) return { thinkingLevel: "LOW" };
482
+ if (m.includes("gemini-2.5")) {
483
+ return { thinkingBudget: m.includes("pro") ? 128 : 0 };
484
+ }
485
+ if (m.includes("-latest")) return { thinkingLevel: "LOW" };
486
+ if (m.includes("gemini-3"))
487
+ return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
488
+ return void 0;
489
+ }
490
+ function fallbackThinking(rejected) {
491
+ return rejected.thinkingLevel === "MINIMAL" ? { thinkingLevel: "LOW" } : void 0;
492
+ }
493
+ function isThinkingConfigError(message) {
494
+ if (!message) return false;
495
+ return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
496
+ }
497
+
461
498
  // src/providers/gemini.ts
462
499
  var SDK_KEY_WARNING = "Both GOOGLE_API_KEY and GEMINI_API_KEY are set";
463
500
  var originalWarn = console.warn.bind(console);
@@ -486,25 +523,15 @@ function detectMime(path) {
486
523
  return MIME_BY_EXT[ext2] ?? "application/octet-stream";
487
524
  }
488
525
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
489
- function resolveThinking(model) {
490
- const m = model.toLowerCase();
491
- if (m.includes("gemini-2.0")) return void 0;
492
- if (m.includes("gemini-2.5")) {
493
- return { thinkingBudget: m.includes("pro") ? 128 : 0 };
494
- }
495
- if (m.includes("gemini-3") || m.includes("flash-latest") || m.includes("pro-latest")) {
496
- return { thinkingLevel: m.includes("pro") ? "LOW" : "MINIMAL" };
497
- }
498
- return void 0;
499
- }
500
- function isThinkingConfigError(message) {
501
- if (!message) return false;
502
- return /thinking/i.test(message) && /(not supported|invalid|unsupported|unknown name|unexpected)/i.test(message);
503
- }
504
526
  var GeminiClient = class {
505
527
  ai;
506
- constructor(apiKey) {
507
- this.ai = new GoogleGenAI({ apiKey });
528
+ zeroStorage;
529
+ constructor(apiKey, opts = {}) {
530
+ this.ai = new GoogleGenAI({
531
+ apiKey,
532
+ ...opts.baseUrl ? { httpOptions: { baseUrl: opts.baseUrl } } : {}
533
+ });
534
+ this.zeroStorage = opts.zeroStorage ?? true;
508
535
  }
509
536
  /** Upload a file and wait until it's done processing. Uploads ride one long HTTP
510
537
  * request each — the retry loop in generate() doesn't cover them, and transient
@@ -547,12 +574,15 @@ var GeminiClient = class {
547
574
  maxOutputTokens,
548
575
  temperature
549
576
  };
577
+ if (this.zeroStorage) config.store = false;
550
578
  if (responseSchema) {
551
579
  config.responseMimeType = "application/json";
552
580
  config.responseSchema = responseSchema;
581
+ } else if (opts.responseJson) {
582
+ config.responseMimeType = "application/json";
553
583
  }
554
584
  if (systemInstruction) config.systemInstruction = systemInstruction;
555
- const thinking = resolveThinking(model);
585
+ let thinking = resolveThinking(model);
556
586
  if (thinking) config.thinkingConfig = thinking;
557
587
  const parts = uploaded.map((f) => ({
558
588
  fileData: { fileUri: f.uri, mimeType: f.mimeType }
@@ -562,21 +592,31 @@ var GeminiClient = class {
562
592
  for (let attempt = 0; attempt < maxRetries; attempt++) {
563
593
  const t0 = Date.now();
564
594
  try {
565
- const response = await this.ai.models.generateContent({
595
+ const controller = new AbortController();
596
+ const stream = await this.ai.models.generateContentStream({
566
597
  model,
567
598
  contents: [{ role: "user", parts }],
568
- config
599
+ config: { ...config, abortSignal: controller.signal }
569
600
  });
570
- const usage = response.usageMetadata || {};
571
- const text = response.text ?? "";
572
- const result = {
573
- text,
574
- usage: {
575
- inputTokens: usage.promptTokenCount ?? 0,
576
- outputTokens: usage.candidatesTokenCount ?? 0,
577
- totalTokens: usage.totalTokenCount ?? 0
601
+ let text = "";
602
+ let usageMeta;
603
+ let abortReason = null;
604
+ for await (const chunk of stream) {
605
+ text += chunk.text ?? "";
606
+ if (chunk.usageMetadata) usageMeta = chunk.usageMetadata;
607
+ abortReason = opts.shouldAbort?.(text) ?? null;
608
+ if (abortReason) {
609
+ controller.abort();
610
+ break;
578
611
  }
579
- };
612
+ }
613
+ const usage = usageFromMetadata(usageMeta);
614
+ const error = abortReason ? `aborted: ${abortReason}` : void 0;
615
+ if (error) {
616
+ logger.warn(
617
+ `[gemini] ${opts.logKind ?? "call"}${opts.logChunk !== void 0 ? ` chunk ${opts.logChunk}` : ""} ${error} after ${text.length} chars`
618
+ );
619
+ }
580
620
  logLlmCall({
581
621
  ts: new Date(t0).toISOString(),
582
622
  provider: "gemini",
@@ -585,18 +625,22 @@ var GeminiClient = class {
585
625
  chunk: opts.logChunk,
586
626
  prompt,
587
627
  response: text,
588
- usage: result.usage,
628
+ usage,
589
629
  durationMs: Date.now() - t0,
590
- attempt: attempt + 1
630
+ attempt: attempt + 1,
631
+ ...error ? { error } : {}
591
632
  });
592
- return result;
633
+ return error ? { text, usage, error } : { text, usage };
593
634
  } catch (err) {
594
635
  lastError = err instanceof Error ? err.message : String(err);
595
- if (config.thinkingConfig && isThinkingConfigError(lastError)) {
596
- delete config.thinkingConfig;
636
+ if (thinking && isThinkingConfigError(lastError)) {
637
+ const next = fallbackThinking(thinking);
597
638
  logger.warn(
598
- `[gemini] model ${model} rejected thinking config \u2014 retrying without it`
639
+ `[gemini] model ${model} rejected thinking config ${JSON.stringify(thinking)} \u2014 retrying ${next ? `with ${JSON.stringify(next)}` : "without it"}`
599
640
  );
641
+ thinking = next;
642
+ if (thinking) config.thinkingConfig = thinking;
643
+ else delete config.thinkingConfig;
600
644
  continue;
601
645
  }
602
646
  logger.warn(
@@ -662,51 +706,93 @@ var GeminiClient = class {
662
706
  };
663
707
 
664
708
  // src/providers/assemblyai.ts
665
- import { AssemblyAI } from "assemblyai";
709
+ import {
710
+ AssemblyAI
711
+ } from "assemblyai";
666
712
  import { createHash as createHash2 } from "crypto";
667
- import { readFile, mkdir as mkdir2, writeFile } from "fs/promises";
713
+ import { readFile, mkdir as mkdir2, writeFile, rm } from "fs/promises";
668
714
  import { existsSync } from "fs";
669
715
  import { dirname as dirname3 } from "path";
670
716
  async function fileHash(path) {
671
717
  const buf = await readFile(path);
672
718
  return createHash2("sha256").update(buf).digest("hex").slice(0, 24);
673
719
  }
720
+ var DELETED_TEXT = "Deleted by user.";
721
+ async function readPendingId(pendingPath) {
722
+ if (!existsSync(pendingPath)) return void 0;
723
+ try {
724
+ return JSON.parse(await readFile(pendingPath, "utf-8")).id;
725
+ } catch {
726
+ return void 0;
727
+ }
728
+ }
674
729
  var AssemblyAIProvider = class {
675
730
  client;
676
731
  cacheDir;
677
732
  constructor(opts) {
678
- this.client = new AssemblyAI({ apiKey: opts.apiKey });
733
+ this.client = new AssemblyAI({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });
679
734
  this.cacheDir = opts.cacheDir;
680
735
  this.speechModel = opts.speechModel ?? "universal";
681
736
  this.speakersExpected = opts.speakersExpected;
737
+ this.language = opts.language;
738
+ this.zeroStorage = opts.zeroStorage ?? true;
682
739
  }
683
740
  speechModel;
684
741
  speakersExpected;
742
+ language;
743
+ zeroStorage;
744
+ /** Whether the last transcribe() was served from the content-hash cache (no paid call). */
745
+ lastFromCache = false;
685
746
  /** Transcribe a local audio file. Returns cached result if available. */
686
747
  async transcribe(filePath) {
687
748
  const hash = await fileHash(filePath);
688
- const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}.json` : void 0;
749
+ const variant = [
750
+ `lang-${this.language ?? "auto"}`,
751
+ this.speakersExpected && `spk-${this.speakersExpected}`,
752
+ this.speechModel !== "universal" && this.speechModel
753
+ ].filter(Boolean).join("_");
754
+ const cachePath = this.cacheDir ? `${this.cacheDir}/${hash}_${variant}.json` : void 0;
755
+ const pendingPath = cachePath?.replace(/\.json$/, ".pending.json");
756
+ this.lastFromCache = false;
689
757
  if (cachePath && existsSync(cachePath)) {
690
758
  logger.info(`[assemblyai] cache hit ${hash}`);
759
+ this.lastFromCache = true;
760
+ if (pendingPath) await this.finish(pendingPath, await readPendingId(pendingPath));
691
761
  return JSON.parse(await readFile(cachePath, "utf-8"));
692
762
  }
693
- logger.info(`[assemblyai] uploading ${filePath}...`);
694
- const uploadUrl = await withRetry(
695
- "assemblyai upload",
696
- () => this.client.files.upload(filePath)
697
- );
698
- logger.info(`[assemblyai] transcribing (speech_model=${this.speechModel})...`);
699
- const params = {
700
- audio: uploadUrl,
701
- speaker_labels: true,
702
- speech_model: this.speechModel
703
- };
704
- if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
705
- const transcript = await withRetry(
706
- "assemblyai transcribe",
707
- () => this.client.transcripts.transcribe(params)
708
- );
763
+ let transcript = pendingPath ? await this.resume(pendingPath) : void 0;
764
+ if (!transcript) {
765
+ logger.info(`[assemblyai] uploading ${filePath}...`);
766
+ const uploadUrl = await withRetry(
767
+ "assemblyai upload",
768
+ () => this.client.files.upload(filePath)
769
+ );
770
+ logger.info(
771
+ `[assemblyai] transcribing (speech_model=${this.speechModel}, language=${this.language ?? "auto-detect"})...`
772
+ );
773
+ const params = {
774
+ audio: uploadUrl,
775
+ speaker_labels: true,
776
+ speech_model: this.speechModel
777
+ };
778
+ if (this.speakersExpected) params.speakers_expected = this.speakersExpected;
779
+ if (this.language) params.language_code = this.language;
780
+ else params.language_detection = true;
781
+ const job = await withRetry(
782
+ "assemblyai submit",
783
+ () => this.client.transcripts.submit(params)
784
+ );
785
+ if (pendingPath) {
786
+ await mkdir2(dirname3(pendingPath), { recursive: true });
787
+ await writeFile(pendingPath, JSON.stringify({ id: job.id }));
788
+ }
789
+ transcript = await withRetry(
790
+ "assemblyai transcribe",
791
+ () => this.client.transcripts.waitUntilReady(job.id)
792
+ );
793
+ }
709
794
  if (transcript.status === "error") {
795
+ if (pendingPath) await rm(pendingPath, { force: true });
710
796
  throw new Error(`AssemblyAI error: ${transcript.error}`);
711
797
  }
712
798
  const result = this.mapTranscript(transcript, hash);
@@ -715,10 +801,53 @@ var AssemblyAIProvider = class {
715
801
  await writeFile(cachePath, JSON.stringify(result, null, 2));
716
802
  }
717
803
  logger.info(
718
- `[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers`
804
+ `[assemblyai] done: ${result.utterances.length} utterances, ${result.words.length} words, ${result.speakers.length} speakers, language ${result.languageCode ?? "?"}`
719
805
  );
806
+ if (pendingPath) await this.finish(pendingPath, transcript.id);
807
+ else if (this.zeroStorage && transcript.id) await this.deleteRemote(transcript.id);
720
808
  return result;
721
809
  }
810
+ /** Delete job `id` from AssemblyAI (with zero storage), then forget it. */
811
+ async finish(pendingPath, id) {
812
+ if (this.zeroStorage && id) await this.deleteRemote(id);
813
+ await rm(pendingPath, { force: true });
814
+ }
815
+ async deleteRemote(id) {
816
+ await this.client.transcripts.delete(id).then(
817
+ () => logger.debug(`[assemblyai] deleted transcript ${id} from AssemblyAI`),
818
+ (err) => logger.warn(
819
+ `[assemblyai] couldn't delete transcript ${id} from AssemblyAI (it expires in 30 days): ${err instanceof Error ? err.message : String(err)}`
820
+ )
821
+ );
822
+ }
823
+ /** The finished job a stopped run left at `pendingPath`, or undefined to send the audio
824
+ * again: when there is none, or AssemblyAI says it's gone (not found, failed, deleted).
825
+ * Anything less certain (offline, an outage, a refused key) is thrown with the job kept,
826
+ * so the next run neither pays twice nor leaves the job behind undeleted. */
827
+ async resume(pendingPath) {
828
+ const id = await readPendingId(pendingPath);
829
+ if (id) {
830
+ logger.info(`[assemblyai] picking up transcript ${id}, left by a stopped run...`);
831
+ let gone;
832
+ try {
833
+ const t = await withRetry(
834
+ "assemblyai transcribe",
835
+ () => this.client.transcripts.waitUntilReady(id)
836
+ );
837
+ if (t.status === "completed" && t.text !== DELETED_TEXT) return t;
838
+ gone = t.status === "error" ? `it failed: ${t.error}` : "it was deleted";
839
+ } catch (err) {
840
+ const message = err instanceof Error ? err.message : String(err);
841
+ if (!/not found/i.test(message)) throw err;
842
+ gone = message;
843
+ }
844
+ logger.warn(
845
+ `[assemblyai] transcript ${id} is gone (${gone}) \u2014 sending the audio again`
846
+ );
847
+ }
848
+ await rm(pendingPath, { force: true });
849
+ return void 0;
850
+ }
722
851
  mapTranscript(t, id) {
723
852
  const toWord = (w) => ({
724
853
  text: w.text,
@@ -748,6 +877,7 @@ var AssemblyAIProvider = class {
748
877
  durationSec,
749
878
  audioDurationSec: t.audio_duration ?? void 0,
750
879
  // AssemblyAI returns seconds (not ms)
880
+ languageCode: t.language_code ?? void 0,
751
881
  speakers: [...speakers].sort(),
752
882
  transcriptId: t.id ?? id,
753
883
  speechModelUsed: t.speech_model_used ?? void 0,
@@ -766,7 +896,7 @@ var WhisperGroqClient = class {
766
896
  apiKey;
767
897
  model;
768
898
  baseUrl;
769
- async transcribe(audio) {
899
+ async transcribe(audio, opts = {}) {
770
900
  const blob = audio instanceof Blob ? audio : new Blob([audio], { type: "audio/mpeg" });
771
901
  const form = new FormData();
772
902
  form.append("file", blob, "audio.mp3");
@@ -774,6 +904,7 @@ var WhisperGroqClient = class {
774
904
  form.append("response_format", "verbose_json");
775
905
  form.append("timestamp_granularities[]", "word");
776
906
  form.append("timestamp_granularities[]", "segment");
907
+ if (opts.language) form.append("language", opts.language);
777
908
  const res = await fetch(`${this.baseUrl}/audio/transcriptions`, {
778
909
  method: "POST",
779
910
  headers: { Authorization: `Bearer ${this.apiKey}` },
@@ -828,6 +959,7 @@ var ElevenLabsClient = class {
828
959
  form.append("diarize", "true");
829
960
  form.append("tag_audio_events", "false");
830
961
  if (opts.numSpeakers) form.append("num_speakers", String(opts.numSpeakers));
962
+ if (opts.languageCode) form.append("language_code", opts.languageCode);
831
963
  for (const term of opts.keyterms ?? []) form.append("keyterms", term);
832
964
  const data = await withRetry("elevenlabs", async () => {
833
965
  const res = await fetch(`${this.baseUrl}/speech-to-text`, {
@@ -886,17 +1018,53 @@ var ElevenLabsClient = class {
886
1018
  };
887
1019
 
888
1020
  // src/core/pricing.ts
889
- var PRICES_AS_OF = "2026-07";
1021
+ var PRICES_AS_OF = "2026-11-17";
890
1022
  var MODEL_PRICES = {
891
- // Gemini (ai.google.dev/gemini-api/docs/pricing, standard tier, <=200k prompts)
1023
+ "gemini-4-hydrogen": { textIn: 1.5, out: 7.5 },
1024
+ "gemini-4-argon": {
1025
+ until: "2026-11-30",
1026
+ price: { textIn: 2, out: 10 },
1027
+ then: { textIn: 4, out: 20 }
1028
+ },
1029
+ "gemini-4-carbon": {
1030
+ until: "2026-11-30",
1031
+ price: { textIn: 2, out: 10 },
1032
+ then: { textIn: 4, out: 20 }
1033
+ },
892
1034
  "gemini-3.1-pro-preview": { textIn: 2, out: 12 },
893
- "gemini-3-pro-preview": { textIn: 2, out: 12 },
894
- "gemini-3.5-flash": { textIn: 1.5, out: 9 },
1035
+ // ≤200k-token prompts
1036
+ "gemini-3.8-flash": {
1037
+ until: "2026-12-31",
1038
+ price: { textIn: 0.75, out: 3.75 },
1039
+ then: { textIn: 1.5, out: 7.5 }
1040
+ },
1041
+ "gemini-3.6-flash": {
1042
+ until: "2026-12-31",
1043
+ price: { textIn: 0.75, out: 3.75 },
1044
+ then: { textIn: 1.5, out: 7.5 }
1045
+ },
1046
+ // Deprecated 2026-10-08; requests are served by gemini-3.6-flash (priced as such).
1047
+ "gemini-3.5-flash": {
1048
+ until: "2026-12-31",
1049
+ price: { textIn: 0.75, out: 3.75 },
1050
+ then: { textIn: 1.5, out: 7.5 }
1051
+ },
1052
+ "gemini-3.5-flash-lite": { textIn: 0.3, out: 2.5 },
895
1053
  "gemini-3-flash-preview": { textIn: 0.5, audioIn: 1, out: 3 },
896
- "gemini-2.5-pro": { textIn: 1.25, out: 10 },
897
- "gemini-2.5-flash": { textIn: 0.3, audioIn: 1, out: 2.5 },
1054
+ // From 2026-12-01 Google serves (and bills) 2.5 Pro as 3.8 Flash and 2.5 Flash as 3.5 Flash-Lite.
1055
+ "gemini-2.5-pro": {
1056
+ until: "2026-11-30",
1057
+ price: { textIn: 1.25, out: 10 },
1058
+ then: { textIn: 1.5, out: 7.5 }
1059
+ },
1060
+ "gemini-2.5-flash": {
1061
+ until: "2026-11-30",
1062
+ price: { textIn: 0.3, audioIn: 1, out: 2.5 },
1063
+ then: { textIn: 0.3, out: 2.5 }
1064
+ },
898
1065
  "gemini-2.5-flash-lite": { textIn: 0.1, audioIn: 0.3, out: 0.4 },
899
- // Moving aliases — priced as their current targets.
1066
+ // Moving aliases. Google hasn't documented their targets since January 2026; these are
1067
+ // the last documented targets' prices, so treat them as estimates.
900
1068
  "gemini-pro-latest": { textIn: 2, out: 12 },
901
1069
  "gemini-flash-latest": { textIn: 1.5, out: 9 },
902
1070
  "gemini-flash-lite-latest": { textIn: 0.25, audioIn: 0.5, out: 1.5 },
@@ -915,17 +1083,27 @@ var ASR_HOURLY = {
915
1083
  // whisper-large-v3-turbo
916
1084
  none: 0
917
1085
  };
918
- var AUDIO_TOKENS_PER_SEC = 32;
919
- function priceFor(model) {
920
- if (MODEL_PRICES[model]) return MODEL_PRICES[model];
921
- const hit = Object.keys(MODEL_PRICES).find((k) => model.startsWith(k));
922
- return hit ? MODEL_PRICES[hit] : null;
1086
+ function audioTokensPerSec(model) {
1087
+ return model.startsWith("gemini-4") ? 32 : 25;
1088
+ }
1089
+ function priceFor(model, at = /* @__PURE__ */ new Date()) {
1090
+ const key = model in MODEL_PRICES ? model : Object.keys(MODEL_PRICES).filter((k) => model.startsWith(k)).sort((a, b) => b.length - a.length)[0];
1091
+ if (!key) return null;
1092
+ const p = MODEL_PRICES[key];
1093
+ if (!("until" in p)) return p;
1094
+ return at.toISOString().slice(0, 10) <= p.until ? p.price : p.then;
923
1095
  }
924
1096
  function asrCost(provider, durationSec) {
925
1097
  const hourly = ASR_HOURLY[provider];
926
1098
  if (hourly === void 0) return null;
927
1099
  return durationSec / 3600 * hourly;
928
1100
  }
1101
+ var OUTPUT_TOK_PER_AUDIO_MIN = 700;
1102
+ function thinkingOverhead(model) {
1103
+ if (model.startsWith("gemini-4-hydrogen")) return 0.5;
1104
+ if (model.includes("pro")) return 0.15;
1105
+ return 0;
1106
+ }
929
1107
  function estimateRunCost(opts) {
930
1108
  const lines = [];
931
1109
  let total = 0;
@@ -937,9 +1115,9 @@ function estimateRunCost(opts) {
937
1115
  );
938
1116
  const billedAudioSec = opts.durationSec + Math.max(0, chunks - 1) * opts.overlapSec + Math.min(370, opts.durationSec);
939
1117
  if (p) {
940
- const audioTok = billedAudioSec * AUDIO_TOKENS_PER_SEC;
1118
+ const audioTok = billedAudioSec * audioTokensPerSec(opts.model);
941
1119
  const promptTok = chunks * 1500;
942
- const outTok = opts.durationSec / 60 * 150 + 1500;
1120
+ const outTok = opts.durationSec / 60 * OUTPUT_TOK_PER_AUDIO_MIN * (1 + thinkingOverhead(opts.model)) + 1500;
943
1121
  const inRate = p.audioIn ?? p.textIn;
944
1122
  const llmUsd = (audioTok * inRate + promptTok * p.textIn + outTok * p.out) / 1e6;
945
1123
  total += llmUsd;
@@ -950,11 +1128,11 @@ function estimateRunCost(opts) {
950
1128
  incomplete = true;
951
1129
  lines.push(`${opts.model}: unpriced`);
952
1130
  }
953
- const asr = asrCost(opts.tsProvider, opts.durationSec);
954
- if (asr !== null && opts.tsProvider !== "none") {
955
- total += asr;
1131
+ const asr2 = asrCost(opts.tsProvider, opts.durationSec);
1132
+ if (asr2 !== null && opts.tsProvider !== "none") {
1133
+ total += asr2;
956
1134
  lines.push(
957
- `${opts.tsProvider}: ${(opts.durationSec / 60).toFixed(0)}min \u2248 $${asr.toFixed(2)}`
1135
+ `${opts.tsProvider}: ${(opts.durationSec / 60).toFixed(0)}min \u2248 $${asr2.toFixed(2)}`
958
1136
  );
959
1137
  }
960
1138
  if (opts.identify && opts.reasoner) {
@@ -967,7 +1145,7 @@ function estimateRunCost(opts) {
967
1145
  }
968
1146
  return { totalUsd: total, lines, incomplete };
969
1147
  }
970
- function computeReceipt(usage, tsProvider, durationSec) {
1148
+ function computeReceipt(usage, tsProvider, durationSec, asrBilled = true) {
971
1149
  let llmUsd = 0;
972
1150
  let incomplete = false;
973
1151
  const lines = [];
@@ -1000,11 +1178,11 @@ function computeReceipt(usage, tsProvider, durationSec) {
1000
1178
  `${model}: ${m.calls} call${m.calls > 1 ? "s" : ""} \xB7 ${fmtTok(m.in)} in / ${fmtTok(m.out)} out \xB7 $${usd.toFixed(2)}`
1001
1179
  );
1002
1180
  }
1003
- const asrUsd = tsProvider === "none" ? 0 : asrCost(tsProvider, durationSec);
1181
+ const asrUsd = tsProvider === "none" || !asrBilled ? 0 : asrCost(tsProvider, durationSec);
1004
1182
  if (asrUsd !== null && tsProvider !== "none") {
1005
1183
  perModel[tsProvider] = asrUsd;
1006
1184
  lines.push(
1007
- `${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 $${asrUsd.toFixed(2)}`
1185
+ `${tsProvider}: ${(durationSec / 60).toFixed(0)}min \xB7 ${asrBilled ? `$${asrUsd.toFixed(2)}` : "cached \xB7 $0.00"}`
1008
1186
  );
1009
1187
  }
1010
1188
  return {
@@ -1033,9 +1211,9 @@ import {
1033
1211
  writeFileSync
1034
1212
  } from "fs";
1035
1213
  import { homedir } from "os";
1036
- import { join } from "path";
1214
+ import { join as join2 } from "path";
1037
1215
  function statsDir() {
1038
- return process.env.OFFMUTE_HOME || join(homedir(), ".offmute");
1216
+ return process.env.OFFMUTE_HOME || join2(homedir(), ".offmute");
1039
1217
  }
1040
1218
  function statsEnabled() {
1041
1219
  return !process.env.OFFMUTE_NO_STATS;
@@ -1053,7 +1231,7 @@ var EMPTY = {
1053
1231
  };
1054
1232
  function readStats() {
1055
1233
  try {
1056
- const p = join(statsDir(), "stats.json");
1234
+ const p = join2(statsDir(), "stats.json");
1057
1235
  if (!existsSync2(p)) return { ...EMPTY };
1058
1236
  return { ...EMPTY, ...JSON.parse(readFileSync(p, "utf-8")) };
1059
1237
  } catch {
@@ -1061,7 +1239,7 @@ function readStats() {
1061
1239
  }
1062
1240
  }
1063
1241
  function withStatsLock(dir, fn) {
1064
- const lock = join(dir, ".stats.lock");
1242
+ const lock = join2(dir, ".stats.lock");
1065
1243
  const deadline = Date.now() + 2e3;
1066
1244
  for (; ; ) {
1067
1245
  try {
@@ -1088,7 +1266,7 @@ function recordRun(rec, perModelCost) {
1088
1266
  try {
1089
1267
  const dir = statsDir();
1090
1268
  mkdirSync(dir, { recursive: true });
1091
- appendFileSync2(join(dir, "history.jsonl"), JSON.stringify(rec) + "\n");
1269
+ appendFileSync2(join2(dir, "history.jsonl"), JSON.stringify(rec) + "\n");
1092
1270
  withStatsLock(dir, () => {
1093
1271
  foldIntoAggregates(rec, perModelCost, dir);
1094
1272
  });
@@ -1111,7 +1289,7 @@ function foldIntoAggregates(rec, perModelCost, dir) {
1111
1289
  if (tModel) s.runsByModel[tModel] = (s.runsByModel[tModel] ?? 0) + 1;
1112
1290
  s.firstRun ??= rec.ts;
1113
1291
  s.lastRun = rec.ts;
1114
- writeFileSync(join(dir, "stats.json"), JSON.stringify(s, null, 2));
1292
+ writeFileSync(join2(dir, "stats.json"), JSON.stringify(s, null, 2));
1115
1293
  }
1116
1294
 
1117
1295
  // src/transcribe/describe.ts
@@ -1145,11 +1323,22 @@ async function describeMeeting(client, model, files, fileName, instructions, aud
1145
1323
  logKind: "describe"
1146
1324
  }
1147
1325
  );
1148
- const text = res.text || "";
1326
+ return { ...parseDescription(res.text || ""), raw: res.text || "" };
1327
+ }
1328
+ function parseDescription(text) {
1149
1329
  const parts = text.split(/\n---\n|\n\s*---\s*\n/);
1150
- const description = parts[0]?.trim() || text.trim();
1151
- const roster = parts.slice(1).join("\n---\n").trim() || "(no explicit roster)";
1152
- return { description, roster, raw: text };
1330
+ return {
1331
+ description: dropHeading(parts[0] ?? "", "DESCRIPTION") || text.trim(),
1332
+ roster: dropHeading(parts.slice(1).join("\n---\n"), "ROSTER") || "(no explicit roster)"
1333
+ };
1334
+ }
1335
+ function dropHeading(section, word) {
1336
+ const s = section.trim();
1337
+ const firstLine = s.split("\n", 1)[0] ?? "";
1338
+ if (new RegExp(`^[#*_\\s]*${word}[#*_:\\s]*$`, "i").test(firstLine)) {
1339
+ return s.slice(firstLine.length).trim();
1340
+ }
1341
+ return s.replace(new RegExp(`^[#*_\\s]*${word}[*_]*\\s*:[*_]*\\s*`, "i"), "");
1153
1342
  }
1154
1343
 
1155
1344
  // src/transcribe/prompts.ts
@@ -1242,13 +1431,6 @@ function transcriptionPrompt(ctx) {
1242
1431
  "Use a roster name ONLY when the voice itself tells you it's that person (they self-identify, are addressed by name, or the voice description clearly matches). If two speakers sound similar and you are not sure which name belongs to which voice, use 'Speaker A' / 'Speaker B' instead \u2014 a WRONG name is much worse than a generic label; a later pass verifies names."
1243
1432
  );
1244
1433
  }
1245
- if (ctx.previousTail) {
1246
- parts.push("");
1247
- parts.push(
1248
- "TRANSCRIPT OF THE END OF THE PREVIOUS CHUNK (for continuity \u2014 do NOT repeat this content, continue from where it leaves off):"
1249
- );
1250
- parts.push(ctx.previousTail);
1251
- }
1252
1434
  if (ctx.instructions) {
1253
1435
  parts.push("");
1254
1436
  parts.push("ADDITIONAL INSTRUCTIONS:");
@@ -1293,6 +1475,51 @@ function formatDuration(seconds) {
1293
1475
  return parts.join(" ");
1294
1476
  }
1295
1477
 
1478
+ // src/transcribe/degeneration.ts
1479
+ var DEGENERATE_COMPRESSION_RATIO = 2.2;
1480
+ var WINDOW_CHARS = 400;
1481
+ var STEP_CHARS = 200;
1482
+ var MIN_MATCH = 4;
1483
+ var MAX_MATCH = 258;
1484
+ var REF_COST = 3;
1485
+ function ratio(s) {
1486
+ let cost = 0;
1487
+ for (let i = 0; i < s.length; ) {
1488
+ let best = 0;
1489
+ for (let j = Math.max(0, i - WINDOW_CHARS); j < i; j++) {
1490
+ let k = 0;
1491
+ while (i + k < s.length && k < MAX_MATCH && s[j + k] === s[i + k]) k++;
1492
+ if (k > best) best = k;
1493
+ }
1494
+ if (best >= MIN_MATCH) {
1495
+ cost += REF_COST;
1496
+ i += best;
1497
+ } else {
1498
+ cost += 1;
1499
+ i += 1;
1500
+ }
1501
+ }
1502
+ return s.length / cost;
1503
+ }
1504
+ function maxCompressionRatio(text) {
1505
+ if (text.length < WINDOW_CHARS) return 0;
1506
+ let max = 0;
1507
+ for (let i = 0; i + WINDOW_CHARS <= text.length; i += STEP_CHARS) {
1508
+ max = Math.max(max, ratio(text.slice(i, i + WINDOW_CHARS)));
1509
+ }
1510
+ return Math.max(max, ratio(text.slice(-WINDOW_CHARS)));
1511
+ }
1512
+ function tailIsDegenerate(text) {
1513
+ if (text.length < 2 * WINDOW_CHARS) return false;
1514
+ return ratio(text.slice(-WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO && ratio(text.slice(-2 * WINDOW_CHARS, -WINDOW_CHARS)) > DEGENERATE_COMPRESSION_RATIO;
1515
+ }
1516
+ function transcriptTextOf(partialJson) {
1517
+ const out = [];
1518
+ for (const m of partialJson.matchAll(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/g))
1519
+ out.push(m[1]);
1520
+ return out.join(" ");
1521
+ }
1522
+
1296
1523
  // src/transcribe/llm-transcribe.ts
1297
1524
  var MIN_SEGMENTS = 3;
1298
1525
  var MIN_SPAN_RATIO = 0.6;
@@ -1333,6 +1560,16 @@ function parseLlmSegments(data, chunkOffsetSec) {
1333
1560
  return { segments: out, dropped };
1334
1561
  }
1335
1562
  function validate(segments, chunkDuration) {
1563
+ const compression = maxCompressionRatio(segments.map((s) => s.text).join(" "));
1564
+ if (compression > DEGENERATE_COMPRESSION_RATIO) {
1565
+ return {
1566
+ isValid: false,
1567
+ degenerate: true,
1568
+ spanSec: segments.length ? segments[segments.length - 1].endSec - segments[0].startSec : 0,
1569
+ segmentCount: segments.length,
1570
+ message: `degenerate repetition (compression ratio ${compression.toFixed(1)} > ${DEGENERATE_COMPRESSION_RATIO})`
1571
+ };
1572
+ }
1336
1573
  if (segments.length < MIN_SEGMENTS) {
1337
1574
  return {
1338
1575
  isValid: false,
@@ -1343,92 +1580,155 @@ function validate(segments, chunkDuration) {
1343
1580
  }
1344
1581
  const first = segments[0].startSec;
1345
1582
  const last = segments[segments.length - 1].endSec;
1346
- const span = last - first;
1583
+ const span2 = last - first;
1347
1584
  const minSpan = chunkDuration * MIN_SPAN_RATIO;
1348
- if (span < minSpan) {
1585
+ if (span2 < minSpan) {
1349
1586
  return {
1350
1587
  isValid: false,
1351
- spanSec: span,
1588
+ spanSec: span2,
1352
1589
  segmentCount: segments.length,
1353
- message: `span ${span.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)`
1590
+ message: `span ${span2.toFixed(0)}s < ${minSpan.toFixed(0)}s required (${MIN_SPAN_RATIO * 100}% of chunk)`
1354
1591
  };
1355
1592
  }
1356
1593
  return {
1357
1594
  isValid: true,
1358
- spanSec: span,
1595
+ spanSec: span2,
1359
1596
  segmentCount: segments.length,
1360
- message: `ok (${segments.length} segments, ${span.toFixed(0)}s span)`
1597
+ message: `ok (${segments.length} segments, ${span2.toFixed(0)}s span)`
1361
1598
  };
1362
1599
  }
1363
1600
  async function transcribeChunk(client, model, chunkPath, chunkStartSec, ctx, opts) {
1364
1601
  const validationRetries = opts.validationRetries ?? 1;
1365
1602
  const prompt = transcriptionPrompt(ctx);
1366
- let lastResult;
1603
+ let temperature = opts.temperature ?? 0.2;
1604
+ let loopAborted = false;
1605
+ let checkedAt = 0;
1606
+ const shouldAbort = (raw) => {
1607
+ if (raw.length - checkedAt < 800) return null;
1608
+ checkedAt = raw.length;
1609
+ if (!tailIsDegenerate(transcriptTextOf(raw))) return null;
1610
+ loopAborted = true;
1611
+ return "degenerate repetition";
1612
+ };
1613
+ let best;
1614
+ const rank = (r) => r.validation.isValid ? 3 : r.error ? 0 : r.validation.degenerate ? 1 : 2;
1615
+ const keep = (r) => {
1616
+ if (!best || rank(r) > rank(best) || rank(r) === rank(best) && r.validation.spanSec > best.validation.spanSec)
1617
+ best = r;
1618
+ };
1367
1619
  for (let attempt = 0; attempt <= validationRetries; attempt++) {
1620
+ loopAborted = false;
1621
+ checkedAt = 0;
1368
1622
  const gen = await client.generateJson(
1369
1623
  model,
1370
1624
  prompt,
1371
1625
  [{ path: chunkPath }],
1372
1626
  TRANSCRIPT_SCHEMA,
1373
1627
  {
1374
- temperature: opts.temperature ?? 0.2,
1628
+ temperature,
1375
1629
  maxRetries: 3,
1376
1630
  logKind: "transcribe",
1377
- logChunk: ctx.index - 1
1631
+ logChunk: ctx.index - 1,
1632
+ shouldAbort
1378
1633
  }
1379
1634
  );
1380
1635
  if (gen.error || !gen.data) {
1381
- lastResult = {
1636
+ keep({
1382
1637
  segments: [],
1383
1638
  raw: gen.raw,
1384
1639
  usage: gen.usage,
1385
1640
  validation: {
1386
1641
  isValid: false,
1642
+ degenerate: loopAborted,
1387
1643
  spanSec: 0,
1388
1644
  segmentCount: 0,
1389
1645
  message: gen.error || "no data"
1390
1646
  },
1391
1647
  error: gen.error
1392
- };
1648
+ });
1393
1649
  logger.warn(
1394
1650
  `[llm] chunk ${ctx.index} attempt ${attempt + 1}: API/parse error \u2014 ${gen.error}`
1395
1651
  );
1652
+ if (loopAborted) temperature = Math.min(1, temperature + 0.3);
1396
1653
  continue;
1397
1654
  }
1398
1655
  const { segments, dropped } = parseLlmSegments(gen.data, chunkStartSec);
1399
1656
  const v = validate(segments, opts.chunkDurationSec);
1400
- lastResult = { segments, raw: gen.raw, usage: gen.usage, validation: v };
1657
+ const result = { segments, raw: gen.raw, usage: gen.usage, validation: v };
1658
+ keep(result);
1401
1659
  if (v.isValid) {
1402
1660
  logger.info(
1403
1661
  `[llm] chunk ${ctx.index} ok: ${v.message}${dropped ? `, dropped ${dropped}` : ""}`
1404
1662
  );
1405
- return lastResult;
1663
+ return result;
1406
1664
  }
1407
1665
  logger.warn(
1408
1666
  `[llm] chunk ${ctx.index} attempt ${attempt + 1} validation: ${v.message}`
1409
1667
  );
1668
+ if (v.degenerate) temperature = Math.min(1, temperature + 0.3);
1410
1669
  }
1411
1670
  logger.error(
1412
1671
  `[llm] chunk ${ctx.index} failed validation after ${validationRetries + 1} attempts`
1413
1672
  );
1414
- return lastResult;
1673
+ return best;
1674
+ }
1675
+
1676
+ // src/transcribe/grounding.ts
1677
+ var MIN_GROUNDED_PRECISION = 0.3;
1678
+ var MIN_TOKENS = 30;
1679
+ var MAX_SCRIPT_SHARE_GAP = 0.2;
1680
+ var STOP_WORDS = Object.fromEntries(
1681
+ "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])
1682
+ );
1683
+ var NON_LATIN = /[^\u0000-\u024F\u2000-\u206F]/u;
1684
+ function contentTokens(words) {
1685
+ const bag = /* @__PURE__ */ new Map();
1686
+ for (const w of words) {
1687
+ const t = w.toLowerCase().replace(/^[^\p{L}\p{N}']+|[^\p{L}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
1688
+ if (t && !STOP_WORDS[t]) bag.set(t, (bag.get(t) ?? 0) + 1);
1689
+ }
1690
+ return bag;
1691
+ }
1692
+ function chunkGrounding(segments, asrWords, start, end) {
1693
+ const asrInRange = asrWords.filter((w) => w.start >= start && w.start < end);
1694
+ const llmWords = segments.map((s) => s.text.replace(/\[[^\]]*\]/g, " ")).join(" ").split(/\s+/).filter(Boolean);
1695
+ const llm = contentTokens(llmWords);
1696
+ const asr2 = contentTokens(asrInRange.map((w) => w.text));
1697
+ let llmTokens = 0;
1698
+ let asrTokens = 0;
1699
+ let shared = 0;
1700
+ for (const n of llm.values()) llmTokens += n;
1701
+ for (const n of asr2.values()) asrTokens += n;
1702
+ for (const [t, n] of llm) shared += Math.min(n, asr2.get(t) ?? 0);
1703
+ const share = (ws) => ws.length ? ws.filter((w) => NON_LATIN.test(w)).length / ws.length : 0;
1704
+ const scriptsMatch = Math.abs(share(llmWords) - share(asrInRange.map((w) => w.text))) <= MAX_SCRIPT_SHARE_GAP;
1705
+ const judged = llmTokens >= MIN_TOKENS && asrTokens >= MIN_TOKENS && scriptsMatch;
1706
+ const precision = llmTokens ? shared / llmTokens : 1;
1707
+ return {
1708
+ llmTokens,
1709
+ asrTokens,
1710
+ precision,
1711
+ judged,
1712
+ grounded: !judged || precision >= MIN_GROUNDED_PRECISION
1713
+ };
1415
1714
  }
1416
1715
 
1417
1716
  // src/align/normalize.ts
1418
- function normalize(word) {
1419
- return word.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "").replace(/'+$/g, "").replace(/^'+/g, "");
1717
+ function normalizeWord(word) {
1718
+ return word.normalize("NFKC").toLowerCase().replace(/[’‘`]/g, "'").replace(/^[^\p{L}\p{M}\p{N}']+|[^\p{L}\p{M}\p{N}']+$/gu, "").replace(/^'+|'+$/g, "");
1420
1719
  }
1421
1720
  function tokenize(text) {
1422
1721
  const out = [];
1423
1722
  for (const raw of text.split(/\s+/)) {
1424
1723
  if (!raw) continue;
1425
- const norm2 = normalize(raw);
1724
+ const norm2 = normalizeWord(raw);
1426
1725
  if (norm2) out.push({ original: raw, norm: norm2 });
1427
1726
  }
1428
1727
  return out;
1429
1728
  }
1430
1729
  function fuzzyEqual(a, b) {
1431
1730
  if (a === b) return true;
1731
+ if (!a || !b) return false;
1432
1732
  if (Math.abs(a.length - b.length) <= 1) {
1433
1733
  return editDistanceChars(a, b, 1) <= 1;
1434
1734
  }
@@ -1454,16 +1754,92 @@ function editDistanceChars(a, b, max) {
1454
1754
  return prev[n];
1455
1755
  }
1456
1756
 
1757
+ // src/transcribe/coverage.ts
1758
+ var MIN_COVERAGE_RATIO = 0.6;
1759
+ var MIN_ASR_WORDS = 200;
1760
+ function chunkCoverage(segments, asrWords, start, end) {
1761
+ const llmWords = segments.reduce(
1762
+ (n, s) => n + tokenize(s.text.replace(/\[[^\]]*\]/g, " ")).length,
1763
+ 0
1764
+ );
1765
+ const asrCount = asrWords.reduce(
1766
+ (n, w) => n + (w.start >= start && w.start < end ? tokenize(w.text).length : 0),
1767
+ 0
1768
+ );
1769
+ const ratio2 = asrCount ? llmWords / asrCount : Infinity;
1770
+ const judged = asrCount >= MIN_ASR_WORDS;
1771
+ return {
1772
+ llmWords,
1773
+ asrWords: asrCount,
1774
+ ratio: ratio2,
1775
+ judged,
1776
+ low: judged && ratio2 < MIN_COVERAGE_RATIO
1777
+ };
1778
+ }
1779
+
1780
+ // src/core/retranscribe.ts
1781
+ import { existsSync as existsSync3 } from "fs";
1782
+ var HALF_OVERLAP_SEC = 5;
1783
+ async function transcribeInHalves(opts) {
1784
+ const { chunk } = opts;
1785
+ const mid = (chunk.start + chunk.end) / 2;
1786
+ const halves = [
1787
+ { name: "a", from: chunk.start, to: Math.min(chunk.end, mid + HALF_OVERLAP_SEC) },
1788
+ { name: "b", from: Math.max(chunk.start, mid - HALF_OVERLAP_SEC), to: chunk.end }
1789
+ ];
1790
+ const results = [];
1791
+ for (const h of halves) {
1792
+ const path = `${opts.pathPrefix}_half_${h.name}.mp3`;
1793
+ if (!existsSync3(path))
1794
+ await extractChunk(opts.audioPath, path, h.from, h.to, opts.audioOpts);
1795
+ results.push(
1796
+ await transcribeChunk(opts.client, opts.model, path, h.from, opts.ctx, {
1797
+ chunkDurationSec: h.to - h.from,
1798
+ validationRetries: 0
1799
+ })
1800
+ );
1801
+ }
1802
+ const [a, b] = results;
1803
+ const center = (s) => (s.startSec + s.endSec) / 2;
1804
+ const segments = [
1805
+ ...a.segments.filter((s) => center(s) < mid),
1806
+ ...b.segments.filter((s) => center(s) >= mid)
1807
+ ];
1808
+ const first = segments[0];
1809
+ const last = segments[segments.length - 1];
1810
+ return {
1811
+ segments,
1812
+ raw: JSON.stringify({ halves: [a.raw, b.raw] }),
1813
+ usage: {
1814
+ inputTokens: a.usage.inputTokens + b.usage.inputTokens,
1815
+ outputTokens: a.usage.outputTokens + b.usage.outputTokens,
1816
+ thoughtTokens: (a.usage.thoughtTokens ?? 0) + (b.usage.thoughtTokens ?? 0),
1817
+ totalTokens: a.usage.totalTokens + b.usage.totalTokens
1818
+ },
1819
+ validation: {
1820
+ isValid: a.validation.isValid && b.validation.isValid,
1821
+ degenerate: Boolean(a.validation.degenerate || b.validation.degenerate),
1822
+ spanSec: first && last ? last.endSec - first.startSec : 0,
1823
+ segmentCount: segments.length,
1824
+ message: `halves: ${a.validation.message} | ${b.validation.message}`
1825
+ },
1826
+ ...a.error || b.error ? { error: [a.error, b.error].filter(Boolean).join(" | ") } : {}
1827
+ };
1828
+ }
1829
+
1457
1830
  // src/align/edit-distance.ts
1458
1831
  var INDEL = 2;
1832
+ var OUT_OF_WINDOW = { cost: 2 * INDEL + 1, fuzzy: false };
1459
1833
  function matchCost(a, b) {
1834
+ if (a.window && b.start !== void 0 && (b.start < a.window.lo || b.start > a.window.hi))
1835
+ return OUT_OF_WINDOW;
1460
1836
  if (a.norm === b.norm) return { cost: 0, fuzzy: false };
1461
1837
  if (fuzzyEqual(a.norm, b.norm)) return { cost: 1, fuzzy: true };
1462
1838
  return { cost: 2, fuzzy: false };
1463
1839
  }
1464
- function alignWords(llm, asr) {
1840
+ function alignWords(llm, asr2) {
1465
1841
  const m = llm.length;
1466
- const n = asr.length;
1842
+ const n = asr2.length;
1467
1843
  const dp = new Array(m + 1);
1468
1844
  for (let i2 = 0; i2 <= m; i2++) {
1469
1845
  const row = new Int32Array(n + 1);
@@ -1476,7 +1852,7 @@ function alignWords(llm, asr) {
1476
1852
  const row = dp[i2];
1477
1853
  const prev = dp[i2 - 1];
1478
1854
  for (let j2 = 1; j2 <= n; j2++) {
1479
- const { cost } = matchCost(llm[i2 - 1], asr[j2 - 1]);
1855
+ const { cost } = matchCost(llm[i2 - 1], asr2[j2 - 1]);
1480
1856
  const sub = prev[j2 - 1] + cost;
1481
1857
  const ins2 = prev[j2] + INDEL;
1482
1858
  const del2 = row[j2 - 1] + INDEL;
@@ -1494,7 +1870,7 @@ function alignWords(llm, asr) {
1494
1870
  while (i > 0 || j > 0) {
1495
1871
  const cur = dp[i];
1496
1872
  if (i > 0 && j > 0) {
1497
- const { cost } = matchCost(llm[i - 1], asr[j - 1]);
1873
+ const { cost } = matchCost(llm[i - 1], asr2[j - 1]);
1498
1874
  const sub = dp[i - 1][j - 1] + cost;
1499
1875
  if (cur[j] === sub) {
1500
1876
  if (cost === 0) {
@@ -1534,19 +1910,26 @@ function alignWords(llm, asr) {
1534
1910
  }
1535
1911
 
1536
1912
  // src/align/aligner.ts
1913
+ var WINDOW_SLACK_SEC = 2;
1914
+ var UNANCHORED_MAX_DRIFT_SEC = 15;
1915
+ var STRETCH_MIN_SEC = 30;
1916
+ var STRETCH_SEC_PER_WORD = 3;
1917
+ var MAX_INNER_GAP_SEC = 8;
1918
+ var SPOKEN_SEC_PER_WORD = 0.5;
1919
+ var UNCONFIRMED_MAX_SEC = 5;
1537
1920
  function toAsrTokens(words) {
1538
1921
  return words.map((w) => ({
1539
1922
  text: w.text,
1540
1923
  start: w.start,
1541
1924
  end: w.end,
1542
- norm: w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
1925
+ norm: normalizeWord(w.text)
1543
1926
  }));
1544
1927
  }
1545
- function transferTiming(llm, asr, ops) {
1928
+ function transferTiming(llm, asr2, ops) {
1546
1929
  const times = llm.map(() => ({ start: NaN, end: NaN, matched: false }));
1547
1930
  for (const op of ops) {
1548
1931
  if (op.type === "match" || op.type === "substitute") {
1549
- const a = asr[op.asr];
1932
+ const a = asr2[op.asr];
1550
1933
  times[op.llm] = {
1551
1934
  start: a.start,
1552
1935
  end: a.end,
@@ -1598,7 +1981,9 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
1598
1981
  for (const { s, i } of sorted) {
1599
1982
  const toks = tokenize(s.text);
1600
1983
  const start = flat.length;
1601
- for (const t of toks) flat.push({ original: t.original, norm: t.norm, segIdx: i });
1984
+ const window = s.chunkStart !== void 0 && s.chunkEnd !== void 0 ? { lo: s.chunkStart - WINDOW_SLACK_SEC, hi: s.chunkEnd + WINDOW_SLACK_SEC } : void 0;
1985
+ for (const t of toks)
1986
+ flat.push({ original: t.original, norm: t.norm, segIdx: i, window });
1602
1987
  segRanges.push({ src: i, start, end: flat.length });
1603
1988
  }
1604
1989
  if (flat.length === 0 || asrWords.length === 0) {
@@ -1614,17 +1999,17 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
1614
1999
  sourceIndex: i
1615
2000
  }));
1616
2001
  }
1617
- let asr = toAsrTokens(asrWords);
2002
+ let asr2 = toAsrTokens(asrWords);
1618
2003
  if (margin > 0) {
1619
2004
  const lo = sorted[0].s.startSec - margin;
1620
2005
  const hi = sorted[sorted.length - 1].s.endSec + margin;
1621
- asr = asr.filter((w) => w.end >= lo && w.start <= hi);
2006
+ asr2 = asr2.filter((w) => w.end >= lo && w.start <= hi);
1622
2007
  }
1623
- const result = alignWords(flat, asr);
1624
- const times = transferTiming(flat, asr, result.ops);
2008
+ const result = alignWords(flat, asr2);
2009
+ const times = transferTiming(flat, asr2, result.ops);
1625
2010
  if (process.env.ALIGN_DEBUG) {
1626
2011
  console.error(
1627
- `[align] flat=${flat.length} asr=${asr.length} exact=${result.exactMatches} fuzzy=${result.fuzzyMatches} subs=${result.substitutions} ins=${result.insertions} del=${result.deletions}`
2012
+ `[align] flat=${flat.length} asr=${asr2.length} exact=${result.exactMatches} fuzzy=${result.fuzzyMatches} subs=${result.substitutions} ins=${result.insertions} del=${result.deletions}`
1628
2013
  );
1629
2014
  }
1630
2015
  const out = [];
@@ -1643,21 +2028,53 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
1643
2028
  let end;
1644
2029
  let timingSource;
1645
2030
  const confidence = tokenCount ? exact / tokenCount : 0;
1646
- if (firstTimed && lastTimed) {
2031
+ const unanchoredDrift = segOps.length === 0 && firstTimed ? Math.abs(firstTimed.start - s.startSec) : 0;
2032
+ if (firstTimed && lastTimed && unanchoredDrift <= UNANCHORED_MAX_DRIFT_SEC) {
1647
2033
  start = firstTimed.start;
1648
2034
  end = lastTimed.end;
1649
2035
  timingSource = confidence >= confThreshold ? "aligned" : "interpolated";
2036
+ if (end - start > Math.max(STRETCH_MIN_SEC, STRETCH_SEC_PER_WORD * tokenCount)) {
2037
+ const runs = [];
2038
+ for (const t of segTimes) {
2039
+ if (isNaN(t.start)) continue;
2040
+ const run2 = runs[runs.length - 1];
2041
+ if (run2 && t.start - run2.end <= MAX_INNER_GAP_SEC) {
2042
+ run2.end = Math.max(run2.end, t.end);
2043
+ if (t.matched) run2.matched++;
2044
+ } else {
2045
+ runs.push({ start: t.start, end: t.end, matched: t.matched ? 1 : 0 });
2046
+ }
2047
+ }
2048
+ const best = runs.reduce(
2049
+ (a, b) => b.matched > a.matched || b.matched === a.matched && Math.abs(b.start - s.startSec) < Math.abs(a.start - s.startSec) ? b : a
2050
+ );
2051
+ start = best.start;
2052
+ end = best.end;
2053
+ }
2054
+ const spoken = Math.max(1, SPOKEN_SEC_PER_WORD * tokenCount);
2055
+ if (exact === 0 && end - start > Math.max(UNCONFIRMED_MAX_SEC, 3 * spoken)) {
2056
+ end = start + spoken;
2057
+ }
1650
2058
  } else {
1651
2059
  start = s.startSec;
1652
2060
  end = s.endSec;
1653
2061
  timingSource = "coarse";
1654
2062
  }
1655
- const words = segTimes.map((t, idx) => ({
1656
- text: flat[range.start + idx].original,
1657
- start: isNaN(t.start) ? start : t.start,
1658
- end: isNaN(t.end) ? end : t.end,
1659
- matched: t.matched
1660
- }));
2063
+ const step = timingSource === "coarse" && tokenCount ? (end - start) / tokenCount : 0;
2064
+ const inside = (x) => Math.min(Math.max(x, start), end);
2065
+ const words = segTimes.map(
2066
+ (t, idx) => timingSource === "coarse" ? {
2067
+ text: flat[range.start + idx].original,
2068
+ start: start + step * idx,
2069
+ end: start + step * (idx + 1),
2070
+ matched: false
2071
+ } : {
2072
+ text: flat[range.start + idx].original,
2073
+ start: isNaN(t.start) ? start : inside(t.start),
2074
+ end: isNaN(t.end) ? end : inside(t.end),
2075
+ matched: t.matched
2076
+ }
2077
+ );
1661
2078
  out.push({
1662
2079
  speaker: s.speaker,
1663
2080
  start,
@@ -1672,23 +2089,90 @@ function alignSegments(llmSegments, asrWords, opts = {}) {
1672
2089
  }
1673
2090
  return out;
1674
2091
  }
2092
+ var CLOCK_ANCHOR_MIN_WORDS = 3;
2093
+ var CLOCK_ANCHOR_MIN_SHARE = 0.6;
2094
+ function toAsrClock(segments, asrWords) {
2095
+ if (!asrWords.length) return segments;
2096
+ const chunks = /* @__PURE__ */ new Map();
2097
+ for (const s of segments) {
2098
+ if (s.chunkIndex === void 0) continue;
2099
+ const group = chunks.get(s.chunkIndex);
2100
+ if (group) group.push(s);
2101
+ else chunks.set(s.chunkIndex, [s]);
2102
+ }
2103
+ const moved = /* @__PURE__ */ new Map();
2104
+ for (const group of chunks.values()) {
2105
+ const lo = Math.min(...group.map((s) => s.chunkStart ?? s.startSec)) - WINDOW_SLACK_SEC;
2106
+ const hi = Math.max(...group.map((s) => s.chunkEnd ?? s.endSec)) + WINDOW_SLACK_SEC;
2107
+ const aligned = alignSegments(
2108
+ group,
2109
+ asrWords.filter((w) => w.end >= lo && w.start <= hi)
2110
+ );
2111
+ const shifts = aligned.map(
2112
+ (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
2113
+ );
2114
+ for (let k = 0; k < aligned.length; k++) {
2115
+ let shift = shifts[k];
2116
+ for (let r = 1; shift === void 0 && r < aligned.length; r++) {
2117
+ shift = shifts[k - r] ?? shifts[k + r];
2118
+ }
2119
+ const s = group[aligned[k].sourceIndex];
2120
+ moved.set(s, {
2121
+ ...s,
2122
+ startSec: s.startSec + (shift ?? 0),
2123
+ endSec: s.endSec + (shift ?? 0)
2124
+ });
2125
+ }
2126
+ }
2127
+ return segments.map((s) => moved.get(s) ?? s);
2128
+ }
1675
2129
 
1676
2130
  // src/align/fill-gaps.ts
1677
2131
  var MIN_GAP_SEC = 0.8;
1678
2132
  var MIN_WORDS = 1;
1679
- function normSet(text) {
1680
- return new Set(tokenize(text).map((t) => t.norm));
2133
+ var HEAD_SLACK_WORDS = 5;
2134
+ function utteranceAt(utts, t) {
2135
+ let lo = 0;
2136
+ let hi = utts.length - 1;
2137
+ let found = -1;
2138
+ while (lo <= hi) {
2139
+ const mid = lo + hi >> 1;
2140
+ if (utts[mid].start <= t) {
2141
+ found = mid;
2142
+ lo = mid + 1;
2143
+ } else {
2144
+ hi = mid - 1;
2145
+ }
2146
+ }
2147
+ return found >= 0 && t <= utts[found].end ? found : -1;
2148
+ }
2149
+ function dominantSpeaker(utts, start, end) {
2150
+ let best = utts[0]?.speaker || "speaker_?";
2151
+ let bestOv = 0;
2152
+ for (const u of utts) {
2153
+ const ov = Math.max(0, Math.min(end, u.end) - Math.max(start, u.start));
2154
+ if (ov > bestOv) {
2155
+ bestOv = ov;
2156
+ best = u.speaker;
2157
+ }
2158
+ }
2159
+ return best;
1681
2160
  }
1682
2161
  function fillAsrGaps(segments, asrWords, asrUtterances) {
1683
2162
  if (!asrWords.length) return segments;
1684
2163
  const sorted = [...segments].sort((a, b) => a.start - b.start);
2164
+ const utts = [...asrUtterances].sort((a, b) => a.start - b.start);
1685
2165
  const ranges = [];
1686
- const firstStart = sorted.length ? sorted[0].start : asrWords[asrWords.length - 1].end;
1687
- if (firstStart > 0) ranges.push([0, firstStart, sorted[0]]);
1688
- for (let i = 0; i < sorted.length - 1; i++) {
1689
- const cur = sorted[i];
1690
- const next = sorted[i + 1];
1691
- if (next.start > cur.end) ranges.push([cur.end, next.start, next]);
2166
+ if (!sorted.length) {
2167
+ ranges.push([0, Infinity, void 0]);
2168
+ } else {
2169
+ if (sorted[0].start > 0) ranges.push([0, sorted[0].start, sorted[0]]);
2170
+ let coveredTo = sorted[0].end;
2171
+ for (const next of sorted.slice(1)) {
2172
+ if (next.start > coveredTo) ranges.push([coveredTo, next.start, next]);
2173
+ coveredTo = Math.max(coveredTo, next.end);
2174
+ }
2175
+ ranges.push([coveredTo, Infinity, void 0]);
1692
2176
  }
1693
2177
  const filled = [];
1694
2178
  for (const [gs, ge, following] of ranges) {
@@ -1696,38 +2180,44 @@ function fillAsrGaps(segments, asrWords, asrUtterances) {
1696
2180
  const words = asrWords.filter((w) => w.start >= gs && w.start < ge);
1697
2181
  if (words.length < MIN_WORDS) continue;
1698
2182
  if (following) {
1699
- const followingWords = normSet(following.text);
1700
- const gapNorms = words.map(
1701
- (w) => w.text.toLowerCase().replace(/^[^a-z0-9']+|[^a-z0-9']+$/gi, "")
2183
+ const gapNorms = words.map((w) => normalizeWord(w.text)).filter(Boolean);
2184
+ const head = new Set(
2185
+ tokenize(following.text).slice(0, gapNorms.length + HEAD_SLACK_WORDS).map((t) => t.norm)
1702
2186
  );
1703
- const covered = gapNorms.filter((n) => n && followingWords.has(n)).length;
1704
- if (covered / gapNorms.filter(Boolean).length >= 0.6) continue;
2187
+ const covered = gapNorms.filter((n) => head.has(n)).length;
2188
+ if (covered / gapNorms.length >= 0.6) continue;
1705
2189
  }
1706
- let bestSp = asrUtterances[0]?.speaker || "speaker_?";
1707
- let bestOv = 0;
1708
- for (const u of asrUtterances) {
1709
- const ov = Math.max(0, Math.min(ge, u.end) - Math.max(gs, u.start));
1710
- if (ov > bestOv) {
1711
- bestOv = ov;
1712
- bestSp = u.speaker;
2190
+ const runs = [];
2191
+ for (const w of words) {
2192
+ const u = utteranceAt(utts, w.start);
2193
+ const cur = runs[runs.length - 1];
2194
+ if (cur && (u === -1 || u === cur.utt || cur.utt === -1)) {
2195
+ cur.words.push(w);
2196
+ if (cur.utt === -1) cur.utt = u;
2197
+ } else {
2198
+ runs.push({ words: [w], utt: u });
1713
2199
  }
1714
2200
  }
1715
- filled.push({
1716
- speaker: bestSp,
1717
- start: words[0].start,
1718
- end: words[words.length - 1].end,
1719
- text: words.map((w) => w.text).join(" "),
1720
- tone: [],
1721
- confidence: 0,
1722
- timingSource: "timestamped",
1723
- words: words.map((w) => ({
1724
- text: w.text,
1725
- start: w.start,
1726
- end: w.end,
1727
- matched: true
1728
- })),
1729
- sourceIndex: -1
1730
- });
2201
+ for (const run2 of runs) {
2202
+ const first = run2.words[0];
2203
+ const last = run2.words[run2.words.length - 1];
2204
+ filled.push({
2205
+ speaker: run2.utt >= 0 ? utts[run2.utt].speaker : dominantSpeaker(utts, first.start, last.end),
2206
+ start: first.start,
2207
+ end: last.end,
2208
+ text: run2.words.map((w) => w.text).join(" "),
2209
+ tone: [],
2210
+ confidence: 0,
2211
+ timingSource: "timestamped",
2212
+ words: run2.words.map((w) => ({
2213
+ text: w.text,
2214
+ start: w.start,
2215
+ end: w.end,
2216
+ matched: true
2217
+ })),
2218
+ sourceIndex: -1
2219
+ });
2220
+ }
1731
2221
  }
1732
2222
  if (!filled.length) return sorted;
1733
2223
  return [...sorted, ...filled].sort((a, b) => a.start - b.start);
@@ -1979,150 +2469,31 @@ function splitMixedVoiceSegments(segments, utterances) {
1979
2469
  return out.sort((a, b) => a.start - b.start);
1980
2470
  }
1981
2471
 
1982
- // src/providers/openai-compat.ts
1983
- var PROVIDER_BASE = {
1984
- deepseek: "https://api.deepseek.com/v1",
1985
- groq: "https://api.groq.com/openai/v1",
1986
- openai: "https://api.openai.com/v1"
1987
- };
1988
- var OpenAICompatClient = class _OpenAICompatClient {
1989
- constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
1990
- this.baseUrl = baseUrl;
1991
- this.apiKey = apiKey;
1992
- this.defaultModel = defaultModel;
1993
- this.providerName = providerName;
2472
+ // src/diarize/identify.ts
2473
+ var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
2474
+ function buildTranscriptExcerpt(segments, speakers) {
2475
+ const speakerHeader = (sp) => {
2476
+ const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
2477
+ return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
2478
+ };
2479
+ const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
2480
+ if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
2481
+ const parts2 = [
2482
+ "SPEAKERS:",
2483
+ ...speakers.map((sp) => `- ${speakerHeader(sp)}`),
2484
+ "",
2485
+ "FULL TRANSCRIPT (in order):"
2486
+ ];
2487
+ for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
2488
+ return parts2.join("\n");
1994
2489
  }
1995
- baseUrl;
1996
- apiKey;
1997
- defaultModel;
1998
- providerName;
1999
- static fromProvider(provider, apiKey, defaultModel) {
2000
- const base = PROVIDER_BASE[provider] ?? provider;
2001
- return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
2002
- }
2003
- async chat(model, messages, opts = {}) {
2004
- const m = model ?? this.defaultModel;
2005
- const maxRetries = opts.maxRetries ?? 5;
2006
- const body = {
2007
- model: m,
2008
- messages,
2009
- temperature: opts.temperature ?? 0.2
2010
- };
2011
- if (opts.maxTokens) body.max_tokens = opts.maxTokens;
2012
- if (opts.responseJson) {
2013
- body.response_format = { type: "json_object" };
2014
- }
2015
- if (this.providerName === "gemini") {
2016
- body.reasoning_effort = "low";
2017
- }
2018
- let lastError;
2019
- const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
2020
- for (let attempt = 0; attempt < maxRetries; attempt++) {
2021
- const t0 = Date.now();
2022
- try {
2023
- const res = await fetch(`${this.baseUrl}/chat/completions`, {
2024
- method: "POST",
2025
- headers: {
2026
- "Content-Type": "application/json",
2027
- Authorization: `Bearer ${this.apiKey}`
2028
- },
2029
- body: JSON.stringify(body)
2030
- });
2031
- if (!res.ok) {
2032
- const txt = await res.text();
2033
- throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
2034
- }
2035
- const data = await res.json();
2036
- const text = data.choices?.[0]?.message?.content ?? "";
2037
- const usage = {
2038
- inputTokens: data.usage?.prompt_tokens ?? 0,
2039
- outputTokens: data.usage?.completion_tokens ?? 0
2040
- };
2041
- logLlmCall({
2042
- ts: new Date(t0).toISOString(),
2043
- provider: this.providerName,
2044
- model: m,
2045
- kind: opts.logKind,
2046
- prompt: promptStr,
2047
- response: text,
2048
- usage,
2049
- durationMs: Date.now() - t0,
2050
- attempt: attempt + 1
2051
- });
2052
- return { text, usage };
2053
- } catch (err) {
2054
- lastError = err instanceof Error ? err.message : String(err);
2055
- if (body.response_format && /response_format/i.test(lastError)) {
2056
- delete body.response_format;
2057
- continue;
2058
- }
2059
- if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
2060
- delete body.reasoning_effort;
2061
- continue;
2062
- }
2063
- logLlmCall({
2064
- ts: new Date(t0).toISOString(),
2065
- provider: this.providerName,
2066
- model: m,
2067
- kind: opts.logKind,
2068
- prompt: promptStr,
2069
- response: "",
2070
- durationMs: Date.now() - t0,
2071
- attempt: attempt + 1,
2072
- error: lastError
2073
- });
2074
- if (attempt < maxRetries - 1)
2075
- await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
2076
- }
2077
- }
2078
- return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
2079
- }
2080
- async chatJson(model, messages, opts = {}) {
2081
- let lastRaw = "";
2082
- let lastError;
2083
- for (let attempt = 0; attempt < 2; attempt++) {
2084
- const res = await this.chat(model, messages, { ...opts, responseJson: true });
2085
- lastRaw = res.text;
2086
- lastError = res.error;
2087
- if (res.error || !res.text) continue;
2088
- try {
2089
- let txt = res.text.trim();
2090
- const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
2091
- if (fence && fence[1]) txt = fence[1];
2092
- return { data: JSON.parse(txt), raw: res.text };
2093
- } catch (err) {
2094
- lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
2095
- }
2096
- }
2097
- return { data: null, raw: lastRaw, error: lastError };
2098
- }
2099
- };
2100
-
2101
- // src/diarize/identify.ts
2102
- var MAX_FULL_TRANSCRIPT_CHARS = 8e4;
2103
- function buildTranscriptExcerpt(segments, speakers) {
2104
- const speakerHeader = (sp) => {
2105
- const voices = sp.asrVoices && sp.asrVoices.length ? `, voices=${sp.asrVoices.join("/")}` : "";
2106
- return `${sp.id} (${sp.segmentCount || 0} turns, ~${Math.round(sp.talkTime || 0)}s talk time${voices})`;
2107
- };
2108
- const totalChars = segments.reduce((n, s) => n + s.text.length, 0);
2109
- if (totalChars <= MAX_FULL_TRANSCRIPT_CHARS) {
2110
- const parts2 = [
2111
- "SPEAKERS:",
2112
- ...speakers.map((sp) => `- ${speakerHeader(sp)}`),
2113
- "",
2114
- "FULL TRANSCRIPT (in order):"
2115
- ];
2116
- for (const s of segments) parts2.push(`[${s.speaker}] ${s.text}`);
2117
- return parts2.join("\n");
2118
- }
2119
- const bySpeaker = {};
2120
- for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
2121
- const parts = [];
2122
- for (const sp of speakers) {
2123
- const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
2124
- parts.push(`### ${speakerHeader(sp)}`);
2125
- for (const s of segs) parts.push(` ${s.text}`);
2490
+ const bySpeaker = {};
2491
+ for (const s of segments) (bySpeaker[s.speaker] ??= []).push(s);
2492
+ const parts = [];
2493
+ for (const sp of speakers) {
2494
+ const segs = (bySpeaker[sp.id] || []).sort((a, b) => b.text.length - a.text.length).slice(0, 6);
2495
+ parts.push(`### ${speakerHeader(sp)}`);
2496
+ for (const s of segs) parts.push(` ${s.text}`);
2126
2497
  }
2127
2498
  return parts.join("\n");
2128
2499
  }
@@ -2363,7 +2734,8 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
2363
2734
  wantB ? runPass(reasonerB) : Promise.resolve(void 0)
2364
2735
  ]);
2365
2736
  const passFailed = (r) => !!r && r.speakers.length === 0 && /fetch failed|HTTP \d|network|ENOTFOUND|JSON parse|no response/i.test(r.reasoning);
2366
- if (passFailed(resA) && (!wantB || passFailed(resB))) {
2737
+ const allPassesFailed = passFailed(resA) && (!wantB || passFailed(resB));
2738
+ if (allPassesFailed) {
2367
2739
  logger.warn(
2368
2740
  `identify: ALL passes failed (${resA.reasoning.slice(0, 80)}) \u2014 speakers left as generic labels. Re-run to retry naming cheaply (everything else is cached).`
2369
2741
  );
@@ -2468,10 +2840,164 @@ async function identifySpeakersV2(reasonerA, reasonerB, segments, speakers, opts
2468
2840
  decisions,
2469
2841
  tripwires,
2470
2842
  passA: { ...resA, model: reasonerA.model },
2471
- passB: resB ? { ...resB, model: reasonerB.model } : void 0
2843
+ passB: resB ? { ...resB, model: reasonerB.model } : void 0,
2844
+ allPassesFailed
2472
2845
  };
2473
2846
  }
2474
2847
 
2848
+ // src/providers/openai-compat.ts
2849
+ async function chatJsonWith(client, model, messages, opts) {
2850
+ let lastRaw = "";
2851
+ let lastError;
2852
+ for (let attempt = 0; attempt < 2; attempt++) {
2853
+ const res = await client.chat(model, messages, { ...opts, responseJson: true });
2854
+ lastRaw = res.text;
2855
+ lastError = res.error;
2856
+ if (res.error || !res.text) continue;
2857
+ try {
2858
+ let txt = res.text.trim();
2859
+ const fence = txt.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
2860
+ if (fence && fence[1]) txt = fence[1];
2861
+ return { data: JSON.parse(txt), raw: res.text };
2862
+ } catch (err) {
2863
+ lastError = `JSON parse: ${err instanceof Error ? err.message : String(err)}`;
2864
+ }
2865
+ }
2866
+ return { data: null, raw: lastRaw, error: lastError };
2867
+ }
2868
+ var PROVIDER_BASE = {
2869
+ deepseek: "https://api.deepseek.com/v1",
2870
+ groq: "https://api.groq.com/openai/v1",
2871
+ openai: "https://api.openai.com/v1"
2872
+ };
2873
+ var OpenAICompatClient = class _OpenAICompatClient {
2874
+ constructor(baseUrl, apiKey, defaultModel, providerName = "openai-compat") {
2875
+ this.baseUrl = baseUrl;
2876
+ this.apiKey = apiKey;
2877
+ this.defaultModel = defaultModel;
2878
+ this.providerName = providerName;
2879
+ }
2880
+ baseUrl;
2881
+ apiKey;
2882
+ defaultModel;
2883
+ providerName;
2884
+ static fromProvider(provider, apiKey, defaultModel) {
2885
+ const base = PROVIDER_BASE[provider] ?? provider;
2886
+ return new _OpenAICompatClient(base, apiKey, defaultModel, provider);
2887
+ }
2888
+ async chat(model, messages, opts = {}) {
2889
+ const m = model ?? this.defaultModel;
2890
+ const maxRetries = opts.maxRetries ?? 5;
2891
+ const body = {
2892
+ model: m,
2893
+ messages,
2894
+ temperature: opts.temperature ?? 0.2
2895
+ };
2896
+ if (opts.maxTokens) body.max_tokens = opts.maxTokens;
2897
+ if (opts.responseJson) {
2898
+ body.response_format = { type: "json_object" };
2899
+ }
2900
+ if (this.providerName === "gemini") {
2901
+ body.reasoning_effort = "low";
2902
+ }
2903
+ let lastError;
2904
+ const promptStr = messages.map((m2) => `${m2.role}: ${m2.content}`).join("\n");
2905
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
2906
+ const t0 = Date.now();
2907
+ try {
2908
+ const res = await fetch(`${this.baseUrl}/chat/completions`, {
2909
+ method: "POST",
2910
+ headers: {
2911
+ "Content-Type": "application/json",
2912
+ Authorization: `Bearer ${this.apiKey}`
2913
+ },
2914
+ body: JSON.stringify(body)
2915
+ });
2916
+ if (!res.ok) {
2917
+ const txt = await res.text();
2918
+ throw new Error(`HTTP ${res.status}: ${txt.slice(0, 300)}`);
2919
+ }
2920
+ const data = await res.json();
2921
+ const text = data.choices?.[0]?.message?.content ?? "";
2922
+ const usage = {
2923
+ inputTokens: data.usage?.prompt_tokens ?? 0,
2924
+ outputTokens: data.usage?.completion_tokens ?? 0
2925
+ };
2926
+ logLlmCall({
2927
+ ts: new Date(t0).toISOString(),
2928
+ provider: this.providerName,
2929
+ model: m,
2930
+ kind: opts.logKind,
2931
+ prompt: promptStr,
2932
+ response: text,
2933
+ usage,
2934
+ durationMs: Date.now() - t0,
2935
+ attempt: attempt + 1
2936
+ });
2937
+ return { text, usage };
2938
+ } catch (err) {
2939
+ lastError = err instanceof Error ? err.message : String(err);
2940
+ if (body.response_format && /response_format/i.test(lastError)) {
2941
+ delete body.response_format;
2942
+ continue;
2943
+ }
2944
+ if (body.reasoning_effort && /reasoning_effort|reasoning effort/i.test(lastError)) {
2945
+ delete body.reasoning_effort;
2946
+ continue;
2947
+ }
2948
+ logLlmCall({
2949
+ ts: new Date(t0).toISOString(),
2950
+ provider: this.providerName,
2951
+ model: m,
2952
+ kind: opts.logKind,
2953
+ prompt: promptStr,
2954
+ response: "",
2955
+ durationMs: Date.now() - t0,
2956
+ attempt: attempt + 1,
2957
+ error: lastError
2958
+ });
2959
+ if (attempt < maxRetries - 1)
2960
+ await new Promise((r) => setTimeout(r, 2e3 * 2 ** attempt));
2961
+ }
2962
+ }
2963
+ return { text: "", usage: { inputTokens: 0, outputTokens: 0 }, error: lastError };
2964
+ }
2965
+ chatJson(model, messages, opts = {}) {
2966
+ return chatJsonWith(this, model, messages, opts);
2967
+ }
2968
+ };
2969
+
2970
+ // src/providers/gemini-chat.ts
2971
+ var THINKING_HEADROOM_TOKENS = 4096;
2972
+ var GeminiChatClient = class {
2973
+ constructor(gemini, defaultModel) {
2974
+ this.gemini = gemini;
2975
+ this.defaultModel = defaultModel;
2976
+ }
2977
+ gemini;
2978
+ defaultModel;
2979
+ async chat(model, messages, opts = {}) {
2980
+ const system = messages.filter((m) => m.role === "system").map((m) => m.content);
2981
+ const prompt = messages.filter((m) => m.role !== "system").map((m) => m.content).join("\n\n");
2982
+ const r = await this.gemini.generate(model ?? this.defaultModel, prompt, [], {
2983
+ temperature: opts.temperature ?? 0.2,
2984
+ maxOutputTokens: opts.maxTokens ? opts.maxTokens + THINKING_HEADROOM_TOKENS : void 0,
2985
+ responseJson: opts.responseJson,
2986
+ systemInstruction: system.length ? system.join("\n\n") : void 0,
2987
+ maxRetries: opts.maxRetries ?? 5,
2988
+ logKind: opts.logKind
2989
+ });
2990
+ const usage = {
2991
+ inputTokens: r.usage.inputTokens,
2992
+ outputTokens: r.usage.outputTokens
2993
+ };
2994
+ return r.error ? { text: r.text, usage, error: r.error } : { text: r.text, usage };
2995
+ }
2996
+ chatJson(model, messages, opts = {}) {
2997
+ return chatJsonWith(this, model, messages, opts);
2998
+ }
2999
+ };
3000
+
2475
3001
  // src/providers/reasoner.ts
2476
3002
  var PROVIDERS = {
2477
3003
  deepseek: { baseUrl: "https://api.deepseek.com/v1", keyName: "deepseek" },
@@ -2515,34 +3041,30 @@ function reasonerKey(info, keys) {
2515
3041
  if (info.keyName === "gemini") return keys.gemini || keys.google;
2516
3042
  return keys[info.keyName];
2517
3043
  }
2518
- function resolveReasoner(spec, keys) {
3044
+ function clientFor(info, key, opts) {
3045
+ return info.provider === "gemini" ? new GeminiChatClient(
3046
+ new GeminiClient(key, { zeroStorage: opts.zeroStorage }),
3047
+ info.model
3048
+ ) : new OpenAICompatClient(info.baseUrl, key, info.model, info.provider);
3049
+ }
3050
+ function resolveReasoner(spec, keys, opts = {}) {
2519
3051
  const candidates = [spec, "deepseek-chat", "gemini-flash-latest"].filter(
2520
3052
  (s) => !!s
2521
3053
  );
2522
3054
  for (const c of candidates) {
2523
3055
  const info = resolveReasonerInfo(c);
2524
3056
  const key = reasonerKey(info, keys);
2525
- if (key) {
2526
- return {
2527
- client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2528
- info
2529
- };
2530
- }
3057
+ if (key) return { client: clientFor(info, key, opts), info };
2531
3058
  }
2532
3059
  return null;
2533
3060
  }
2534
- function resolveSecondReasoner(first, keys) {
3061
+ function resolveSecondReasoner(first, keys, opts = {}) {
2535
3062
  const candidates = ["gemini-flash-latest", "deepseek-chat", "glm-4.7", "gpt-4o-mini"];
2536
3063
  for (const c of candidates) {
2537
3064
  const info = resolveReasonerInfo(c);
2538
3065
  if (info.provider === first.provider) continue;
2539
3066
  const key = reasonerKey(info, keys);
2540
- if (key) {
2541
- return {
2542
- client: new OpenAICompatClient(info.baseUrl, key, info.model, info.provider),
2543
- info
2544
- };
2545
- }
3067
+ if (key) return { client: clientFor(info, key, opts), info };
2546
3068
  }
2547
3069
  return null;
2548
3070
  }
@@ -2557,7 +3079,6 @@ var REASONER_PRESETS = [
2557
3079
 
2558
3080
  // src/finalize/finalize.ts
2559
3081
  var MIN_DUR = 0.5;
2560
- var MAX_DUR = 7;
2561
3082
  var OVERLAP_GAP = 0.05;
2562
3083
  function textSimilarity(a, b) {
2563
3084
  const ta = new Set(tokenize(a).map((t) => t.norm));
@@ -2701,16 +3222,14 @@ function fixOverlaps(segments) {
2701
3222
  }
2702
3223
  function clampAndFix(segments) {
2703
3224
  for (const s of segments) {
2704
- const dur = s.end - s.start;
2705
- if (dur < MIN_DUR) s.end = s.start + MIN_DUR;
2706
- else if (dur > MAX_DUR) s.end = s.start + MAX_DUR;
3225
+ if (s.end - s.start < MIN_DUR) s.end = s.start + MIN_DUR;
2707
3226
  }
2708
3227
  return fixOverlaps(segments);
2709
3228
  }
2710
- function finalizeSegments(segments, opts = {}) {
2711
- const minSeg = opts.minSegmentSec ?? 0.2;
2712
- let deduped = dedupSegments(trimSeamOverlaps(segments));
2713
- deduped = deduped.filter((s) => s.end - s.start >= minSeg && s.text.trim().length > 0);
3229
+ function finalizeSegments(segments) {
3230
+ const deduped = dedupSegments(trimSeamOverlaps(segments)).filter(
3231
+ (s) => s.text.trim().length > 0
3232
+ );
2714
3233
  const out = deduped.map((s, i) => ({
2715
3234
  id: i + 1,
2716
3235
  start: s.start,
@@ -2790,9 +3309,9 @@ function splitByChars(seg) {
2790
3309
  const blocks = [];
2791
3310
  let t = seg.start;
2792
3311
  for (const line of lines) {
2793
- const span = line.length / total * dur;
2794
- blocks.push({ start: t, end: Math.min(seg.end, t + span), text: line });
2795
- t += span;
3312
+ const span2 = line.length / total * dur;
3313
+ blocks.push({ start: t, end: Math.min(seg.end, t + span2), text: line });
3314
+ t += span2;
2796
3315
  }
2797
3316
  return blocks;
2798
3317
  }
@@ -3038,9 +3557,10 @@ async function summarizeTranscript(client, model, result, instructions) {
3038
3557
 
3039
3558
  // src/core/pipeline.ts
3040
3559
  import { basename as basename3, resolve as resolve2 } from "path";
3560
+ import { createHash as createHash3 } from "crypto";
3041
3561
  var JSON_OPTS = { encoding: "utf-8" };
3042
3562
  function readJson(p) {
3043
- if (!existsSync3(p)) return null;
3563
+ if (!existsSync4(p)) return null;
3044
3564
  try {
3045
3565
  return JSON.parse(readFileSync2(p, JSON_OPTS));
3046
3566
  } catch {
@@ -3066,6 +3586,12 @@ async function mapPool(items, limit, fn) {
3066
3586
  function has(passes, p) {
3067
3587
  return passes.includes(p);
3068
3588
  }
3589
+ var ASR_NAMES = {
3590
+ assemblyai: "AssemblyAI",
3591
+ elevenlabs: "ElevenLabs Scribe",
3592
+ "whisper-groq": "Groq Whisper",
3593
+ none: "none"
3594
+ };
3069
3595
  function stageTag(name) {
3070
3596
  return (err) => {
3071
3597
  const msg = err instanceof Error ? err.message : String(err);
@@ -3075,6 +3601,37 @@ function stageTag(name) {
3075
3601
  throw e;
3076
3602
  };
3077
3603
  }
3604
+ async function preflight(opts) {
3605
+ const options = resolveOptions(opts);
3606
+ const keys = resolveKeys(options.apiKeys);
3607
+ if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
3608
+ if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
3609
+ if (!has(options.passes, "timestamped") && !has(options.passes, "align")) return;
3610
+ const tsProvider = options.timestampedProvider ?? "assemblyai";
3611
+ if (tsProvider === "assemblyai" && !keys.assemblyai) {
3612
+ throw new Error(
3613
+ "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
3614
+ );
3615
+ }
3616
+ if (tsProvider === "whisper-groq" && !keys.groq) {
3617
+ throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
3618
+ }
3619
+ if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
3620
+ throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3621
+ }
3622
+ }
3623
+ function estimateRun(opts, durationSec) {
3624
+ const options = resolveOptions(opts);
3625
+ return estimateRunCost({
3626
+ durationSec,
3627
+ model: options.model ?? DEFAULT_TRANSCRIBE_MODEL,
3628
+ reasoner: options.reasoner ?? DEFAULT_REASONER_MODEL,
3629
+ tsProvider: options.timestampedProvider ?? "assemblyai",
3630
+ chunkSec: options.chunkDurationSec,
3631
+ overlapSec: options.chunkOverlapSec,
3632
+ identify: options.diarizationLevel >= 3 && has(options.passes, "identify")
3633
+ });
3634
+ }
3078
3635
  async function transcribe(opts) {
3079
3636
  if (!opts || typeof opts.input !== "string" || opts.input.length === 0) {
3080
3637
  throw new Error(
@@ -3084,7 +3641,7 @@ async function transcribe(opts) {
3084
3641
  const options = resolveOptions(opts);
3085
3642
  const keys = resolveKeys(options.apiKeys);
3086
3643
  logger.setLevel(options.logLevel);
3087
- if (!existsSync3(options.input)) {
3644
+ if (!existsSync4(options.input)) {
3088
3645
  throw new Error(`Input file not found: ${options.input}`);
3089
3646
  }
3090
3647
  mkdirSync2(options.intermediatesDir, { recursive: true });
@@ -3127,23 +3684,11 @@ async function transcribe(opts) {
3127
3684
  const checkAbort = () => {
3128
3685
  options.signal?.throwIfAborted();
3129
3686
  };
3130
- if (!await checkFfmpeg()) throw new Error("ffmpeg/ffprobe not found in PATH");
3131
- if (!keys.gemini) throw new Error("GEMINI_API_KEY (or GOOGLE_API_KEY) is required");
3687
+ const emit = (event) => emitTo(options.onProgress, event);
3688
+ const geminiOpts = { zeroStorage: options.zeroStorage };
3689
+ await preflight(opts);
3132
3690
  const tsProvider = options.timestampedProvider ?? "assemblyai";
3133
3691
  const willTimestamp = has(passes, "timestamped") || has(passes, "align");
3134
- if (willTimestamp) {
3135
- if (tsProvider === "assemblyai" && !keys.assemblyai) {
3136
- throw new Error(
3137
- "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped elevenlabs / whisper-groq)"
3138
- );
3139
- }
3140
- if (tsProvider === "whisper-groq" && !keys.groq) {
3141
- throw new Error("GROQ_API_KEY is required for --timestamped whisper-groq");
3142
- }
3143
- if (tsProvider === "elevenlabs" && !keys.elevenlabs) {
3144
- throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3145
- }
3146
- }
3147
3692
  let probeInfo = null;
3148
3693
  const AUDIO_OPTS = { format: "mp3", bitrate: "64k" };
3149
3694
  const audioPath = `${options.intermediatesDir}/audio.mp3`;
@@ -3151,12 +3696,13 @@ async function transcribe(opts) {
3151
3696
  if (has(passes, "preprocess")) {
3152
3697
  checkAbort();
3153
3698
  logger.info("=== preprocess ===");
3699
+ emit({ type: "stage", stage: "preprocess", state: "start" });
3154
3700
  probeInfo = forceAll ? null : readJson(probePath);
3155
3701
  if (!probeInfo) {
3156
3702
  probeInfo = await probe(options.input).catch(stageTag("preprocess"));
3157
3703
  writeJson(probePath, probeInfo);
3158
3704
  }
3159
- if (!existsSync3(audioPath) || forceAll) {
3705
+ if (!existsSync4(audioPath) || forceAll) {
3160
3706
  logger.info("extracting audio (mono 16kHz mp3)...");
3161
3707
  await extractAudio(options.input, audioPath, AUDIO_OPTS).catch(
3162
3708
  stageTag("preprocess")
@@ -3164,7 +3710,7 @@ async function transcribe(opts) {
3164
3710
  }
3165
3711
  if (probeInfo.hasVideo) {
3166
3712
  const kfDir = `${options.intermediatesDir}/keyframes`;
3167
- if (!existsSync3(kfDir) || forceAll) {
3713
+ if (!existsSync4(kfDir) || forceAll) {
3168
3714
  logger.info("extracting keyframes...");
3169
3715
  await extractKeyframes(options.input, kfDir, options.screenshotCount).catch(
3170
3716
  (err) => {
@@ -3180,50 +3726,148 @@ async function transcribe(opts) {
3180
3726
  }
3181
3727
  if (!probeInfo) throw new Error("probe info missing (run preprocess)");
3182
3728
  const duration = probeInfo.duration;
3183
- const estimate = estimateRunCost({
3184
- durationSec: duration,
3185
- model: models.transcribe,
3186
- reasoner: models.reasoner,
3187
- tsProvider,
3188
- chunkSec: options.chunkDurationSec,
3189
- overlapSec: options.chunkOverlapSec,
3190
- identify: options.diarizationLevel >= 3 && has(passes, "identify")
3191
- });
3729
+ const estimate = estimateRun(opts, duration);
3192
3730
  logger.info(
3193
3731
  `estimated cost ~$${estimate.totalUsd.toFixed(2)}${estimate.incomplete ? " (+unpriced parts)" : ""} [${estimate.lines.join(" \xB7 ")}]`
3194
3732
  );
3195
- let description = null;
3196
- if (has(passes, "describe")) {
3197
- const descPath = `${options.intermediatesDir}/description.json`;
3198
- description = forceAll ? null : readJson(descPath);
3199
- if (!description) {
3200
- checkAbort();
3201
- logger.info("=== describe ===");
3202
- const client = new GeminiClient(keys.gemini);
3203
- const sampleSpans = duration <= 360 ? [[0, duration]] : [
3204
- [0, 150],
3205
- [Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
3206
- [Math.max(0, duration - 120), duration]
3207
- ];
3208
- const files = [];
3209
- for (let i = 0; i < sampleSpans.length; i++) {
3210
- const [s, e] = sampleSpans[i];
3211
- const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
3212
- if (!existsSync3(samplePath) || forceAll) {
3213
- await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
3214
- }
3215
- files.push({ path: samplePath });
3216
- }
3217
- const audioSampleCount = files.length;
3218
- const kfDir = `${options.intermediatesDir}/keyframes`;
3219
- if (existsSync3(kfDir)) {
3220
- for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
3221
- const p = `${kfDir}/${f}`;
3222
- if (existsSync3(p)) files.push({ path: p });
3223
- }
3224
- }
3225
- description = await describeMeeting(
3226
- client,
3733
+ const naming = options.diarizationLevel >= 3 && has(passes, "identify");
3734
+ const reasonerA = naming || options.summary ? resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys, geminiOpts) : null;
3735
+ const reasonerB = naming && reasonerA && options.identifyMode === "dual" ? resolveSecondReasoner(reasonerA.info, keys, geminiOpts) : null;
3736
+ const asksAssemblyAI = willTimestamp && tsProvider === "assemblyai";
3737
+ const notAsked = options.zeroStorage ? [
3738
+ ...willTimestamp && (tsProvider === "elevenlabs" || tsProvider === "whisper-groq") ? [{ name: ASR_NAMES[tsProvider], role: "timing" }] : [],
3739
+ ...[reasonerA, reasonerB].flatMap(
3740
+ (r) => r && r.info.provider !== "gemini" ? [{ name: r.info.model, role: "text" }] : []
3741
+ )
3742
+ ] : [];
3743
+ if (options.zeroStorage) {
3744
+ logger.info(
3745
+ `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` : ""}`
3746
+ );
3747
+ }
3748
+ emit({
3749
+ type: "plan",
3750
+ durationSec: duration,
3751
+ model: models.transcribe,
3752
+ asr: ASR_NAMES[tsProvider],
3753
+ estimateUsd: estimate.totalUsd,
3754
+ zeroStorage: options.zeroStorage,
3755
+ notAsked
3756
+ });
3757
+ const runTimestamped = async () => {
3758
+ if (!has(passes, "timestamped") && !has(passes, "align")) {
3759
+ const cached = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
3760
+ return { result: cached, billed: false };
3761
+ }
3762
+ checkAbort();
3763
+ if (tsProvider === "none") {
3764
+ logger.info("=== timestamped: none (the LLM's own timestamps are used) ===");
3765
+ return { result: null, billed: false };
3766
+ }
3767
+ if (tsProvider === "whisper-groq") {
3768
+ logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
3769
+ if (!existsSync4(audioPath))
3770
+ await extractAudio(options.input, audioPath, AUDIO_OPTS);
3771
+ const groq = new WhisperGroqClient(keys.groq);
3772
+ const result3 = await groq.transcribe(await readFile2(audioPath), { language: options.language }).catch(stageTag("asr"));
3773
+ writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
3774
+ return { result: result3, billed: true };
3775
+ }
3776
+ if (tsProvider === "elevenlabs") {
3777
+ logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
3778
+ const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs${options.language ? `-${options.language}` : ""}.json`;
3779
+ let result3 = forceAll ? null : readJson(cachePath);
3780
+ let billed = false;
3781
+ if (!result3) {
3782
+ const el = new ElevenLabsClient(keys.elevenlabs);
3783
+ result3 = await el.transcribe(await readFile2(audioPath), { languageCode: options.language }).catch(stageTag("asr"));
3784
+ billed = true;
3785
+ writeJson(cachePath, result3);
3786
+ } else {
3787
+ logger.info("[elevenlabs] cache hit");
3788
+ }
3789
+ writeJson(`${options.intermediatesDir}/timestamped.json`, result3);
3790
+ logger.info(
3791
+ `[elevenlabs] ${result3.utterances.length} utterances, ${result3.words.length} words`
3792
+ );
3793
+ return { result: result3, billed };
3794
+ }
3795
+ logger.info("=== timestamped (AssemblyAI) ===");
3796
+ const aai = new AssemblyAIProvider({
3797
+ apiKey: keys.assemblyai,
3798
+ cacheDir: `${options.intermediatesDir}/assemblyai`,
3799
+ language: options.language,
3800
+ zeroStorage: options.zeroStorage
3801
+ });
3802
+ const result2 = await aai.transcribe(audioPath).catch(stageTag("asr"));
3803
+ writeJson(`${options.intermediatesDir}/timestamped.json`, result2);
3804
+ return { result: result2, billed: !aai.lastFromCache };
3805
+ };
3806
+ const asrName = ASR_NAMES[tsProvider];
3807
+ if (willTimestamp && tsProvider !== "none") {
3808
+ emit({ type: "asr", provider: asrName, state: "start" });
3809
+ }
3810
+ const asrRun = runTimestamped().then(
3811
+ (r) => {
3812
+ if (willTimestamp && r.result) {
3813
+ const speakers2 = new Set(r.result.utterances.map((u) => u.speaker)).size;
3814
+ emit({
3815
+ type: "asr",
3816
+ provider: asrName,
3817
+ state: r.billed ? "done" : "cached",
3818
+ words: r.result.words.length,
3819
+ speakers: speakers2 || void 0,
3820
+ language: r.result.languageCode
3821
+ });
3822
+ }
3823
+ return r;
3824
+ },
3825
+ (err) => {
3826
+ emit({
3827
+ type: "asr",
3828
+ provider: asrName,
3829
+ state: "failed",
3830
+ error: err instanceof Error ? err.message : String(err)
3831
+ });
3832
+ throw err;
3833
+ }
3834
+ );
3835
+ asrRun.catch(() => void 0);
3836
+ let description = null;
3837
+ if (has(passes, "describe")) {
3838
+ const descPath = `${options.intermediatesDir}/description.json`;
3839
+ description = forceAll ? null : readJson(descPath);
3840
+ if (description) {
3841
+ emit({ type: "stage", stage: "describe", state: "cached" });
3842
+ } else {
3843
+ checkAbort();
3844
+ logger.info("=== describe ===");
3845
+ emit({ type: "stage", stage: "describe", state: "start" });
3846
+ const client = new GeminiClient(keys.gemini, geminiOpts);
3847
+ const sampleSpans = duration <= 360 ? [[0, duration]] : [
3848
+ [0, 150],
3849
+ [Math.max(0, duration / 2 - 60), Math.min(duration, duration / 2 + 60)],
3850
+ [Math.max(0, duration - 120), duration]
3851
+ ];
3852
+ const files = [];
3853
+ for (let i = 0; i < sampleSpans.length; i++) {
3854
+ const [s, e] = sampleSpans[i];
3855
+ const samplePath = `${options.intermediatesDir}/sample_${i}.mp3`;
3856
+ if (!existsSync4(samplePath) || forceAll) {
3857
+ await extractChunk(audioPath, samplePath, s, e, AUDIO_OPTS);
3858
+ }
3859
+ files.push({ path: samplePath });
3860
+ }
3861
+ const audioSampleCount = files.length;
3862
+ const kfDir = `${options.intermediatesDir}/keyframes`;
3863
+ if (existsSync4(kfDir)) {
3864
+ for (const f of ["keyframe_000.jpg", "keyframe_001.jpg", "keyframe_002.jpg"]) {
3865
+ const p = `${kfDir}/${f}`;
3866
+ if (existsSync4(p)) files.push({ path: p });
3867
+ }
3868
+ }
3869
+ description = await describeMeeting(
3870
+ client,
3227
3871
  models.transcribe,
3228
3872
  files,
3229
3873
  basename3(options.input),
@@ -3248,14 +3892,14 @@ async function transcribe(opts) {
3248
3892
  }
3249
3893
  chunks = planChunks(duration, options.chunkDurationSec, options.chunkOverlapSec);
3250
3894
  if (silences.length > 3) {
3251
- chunks = chunks.map((c) => {
3252
- const snapped = snapToSilence(
3895
+ chunks = chunks.map((c) => ({
3896
+ ...c,
3897
+ start: snapToSilence(
3253
3898
  c.start,
3254
3899
  silences,
3255
3900
  Math.min(10, options.chunkOverlapSec / 2)
3256
- );
3257
- return { ...c, start: snapped, trustedStart: snapped + c.overlapWithPrevious };
3258
- });
3901
+ )
3902
+ }));
3259
3903
  }
3260
3904
  }
3261
3905
  const tagWith = (r, chunk) => ({
@@ -3263,20 +3907,25 @@ async function transcribe(opts) {
3263
3907
  segments: r.segments.map((s) => ({
3264
3908
  ...s,
3265
3909
  chunkIndex: chunk.index,
3266
- trustedStart: chunk.trustedStart
3910
+ trustedStart: chunk.trustedStart,
3911
+ chunkStart: chunk.start,
3912
+ chunkEnd: chunk.end
3267
3913
  }))
3268
3914
  });
3915
+ const llmDir = `${options.intermediatesDir}/llm`;
3269
3916
  let llmChunkResults = [];
3917
+ let llmChunkPlans = [];
3270
3918
  if (has(passes, "llm-transcribe")) {
3271
3919
  logger.info("=== llm-transcribe ===");
3920
+ emit({ type: "stage", stage: "transcribe", state: "start" });
3272
3921
  let runChunks = chunks;
3273
3922
  if (options.onlyChunk !== void 0)
3274
3923
  runChunks = chunks.filter((c) => c.index === options.onlyChunk);
3275
3924
  logger.info(
3276
3925
  `${runChunks.length} chunks (${options.chunkDurationSec}s, ${options.chunkOverlapSec}s overlap)`
3277
3926
  );
3278
- const client = new GeminiClient(keys.gemini);
3279
- const llmDir = `${options.intermediatesDir}/llm`;
3927
+ emit({ type: "chunks", total: runChunks.length, chunkSec: options.chunkDurationSec });
3928
+ const client = new GeminiClient(keys.gemini, geminiOpts);
3280
3929
  mkdirSync2(llmDir, { recursive: true });
3281
3930
  const partialPath = `${options.outputDir}/${basename3(options.input, ext(options.input))}.partial.md`;
3282
3931
  const completed = [];
@@ -3305,25 +3954,23 @@ ${lines.join("\n\n")}
3305
3954
  const cached = forceAll ? null : readJson(parsedPath);
3306
3955
  if (cached && cached.segments.length > 0) {
3307
3956
  logger.info(`chunk ${chunk.index}: cached (${cached.segments.length} segments)`);
3957
+ emit({
3958
+ type: "chunk",
3959
+ index: chunk.index,
3960
+ state: "cached",
3961
+ segments: cached.segments.length
3962
+ });
3308
3963
  completed.push(cached);
3309
3964
  return tagWith(cached, chunk);
3310
3965
  }
3311
3966
  const chunkPath = `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}.mp3`;
3312
- if (!existsSync3(chunkPath) || forceAll) {
3967
+ if (!existsSync4(chunkPath) || forceAll) {
3313
3968
  await extractChunk(audioPath, chunkPath, chunk.start, chunk.end, AUDIO_OPTS);
3314
3969
  }
3315
- let previousTail;
3316
- if (chunk.index > 0) {
3317
- const prev = readJson(
3318
- `${llmDir}/chunk_${String(chunk.index - 1).padStart(2, "0")}_parsed.json`
3319
- );
3320
- if (prev && prev.segments.length) {
3321
- previousTail = prev.segments.slice(-6).map((s) => `${s.speaker}: ${s.text}`).join("\n");
3322
- }
3323
- }
3324
3970
  logger.info(
3325
3971
  `chunk ${chunk.index}: transcribing [${chunk.start.toFixed(0)}-${chunk.end.toFixed(0)}]s...`
3326
3972
  );
3973
+ emit({ type: "chunk", index: chunk.index, state: "running" });
3327
3974
  const result2 = await transcribeChunk(
3328
3975
  client,
3329
3976
  models.transcribe,
@@ -3334,12 +3981,19 @@ ${lines.join("\n\n")}
3334
3981
  total: runChunks.length,
3335
3982
  description: description?.description,
3336
3983
  roster: description?.roster,
3337
- previousTail,
3338
3984
  instructions: options.instructions
3339
3985
  },
3340
3986
  { chunkDurationSec: chunk.end - chunk.start, validationRetries: 1 }
3341
3987
  );
3342
3988
  writeJson(parsedPath, result2);
3989
+ emit(
3990
+ result2.error && result2.segments.length === 0 ? { type: "chunk", index: chunk.index, state: "failed", error: result2.error } : {
3991
+ type: "chunk",
3992
+ index: chunk.index,
3993
+ state: "done",
3994
+ segments: result2.segments.length
3995
+ }
3996
+ );
3343
3997
  writeFileSync2(
3344
3998
  `${llmDir}/chunk_${String(chunk.index).padStart(2, "0")}_raw.json`,
3345
3999
  result2.raw
@@ -3348,6 +4002,7 @@ ${lines.join("\n\n")}
3348
4002
  writePartial();
3349
4003
  return tagWith(result2, chunk);
3350
4004
  });
4005
+ llmChunkPlans = runChunks;
3351
4006
  const errored = llmChunkResults.filter((r) => r.error);
3352
4007
  const producedSegments = llmChunkResults.reduce((n, r) => n + r.segments.length, 0);
3353
4008
  if (llmChunkResults.length > 0 && producedSegments === 0 && errored.length === llmChunkResults.length) {
@@ -3356,16 +4011,118 @@ ${lines.join("\n\n")}
3356
4011
  );
3357
4012
  }
3358
4013
  } else {
3359
- const llmDir = `${options.intermediatesDir}/llm`;
3360
- if (!forceAll && existsSync3(llmDir)) {
3361
- const files = (await import("fs/promises").then((m) => m.readdir(llmDir))).filter((f) => f.endsWith("_parsed.json")).sort();
3362
- llmChunkResults = files.map((f, i) => {
3363
- const r = readJson(`${llmDir}/${f}`);
3364
- return r && chunks[i] ? tagWith(r, chunks[i]) : r;
3365
- }).filter(Boolean);
4014
+ if (!forceAll && existsSync4(llmDir)) {
4015
+ for (const f of readdirSync(llmDir).sort()) {
4016
+ const m = /^chunk_(\d+)_parsed\.json$/.exec(f);
4017
+ const plan = m ? chunks.find((c) => c.index === Number(m[1])) : void 0;
4018
+ const r = plan ? readJson(`${llmDir}/${f}`) : null;
4019
+ if (r && plan) {
4020
+ llmChunkResults.push(tagWith(r, plan));
4021
+ llmChunkPlans.push(plan);
4022
+ }
4023
+ }
3366
4024
  }
3367
4025
  }
4026
+ const { result: asrResult, billed: asrBilled } = await asrRun;
4027
+ const quality = [];
4028
+ if (asrResult?.words.length) {
4029
+ let client;
4030
+ for (let i = 0; i < llmChunkResults.length; i++) {
4031
+ const plan = llmChunkPlans[i];
4032
+ const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
4033
+ let cov = chunkCoverage(
4034
+ llmChunkResults[i].segments,
4035
+ asrResult.words,
4036
+ plan.start,
4037
+ plan.end
4038
+ );
4039
+ let status = cov.low ? "low-coverage" : "ok";
4040
+ if (cov.low) {
4041
+ const retryPath = `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}_retry_parsed.json`;
4042
+ let retry = forceAll ? null : readJson(retryPath);
4043
+ const span2 = { index: plan.index, startSec: plan.start, endSec: plan.end };
4044
+ if (!retry && has(passes, "llm-transcribe")) {
4045
+ checkAbort();
4046
+ logger.warn(
4047
+ `${where}: ${cov.llmWords} words transcribed where the ASR heard ${cov.asrWords} \u2014 transcribing it again in two halves`
4048
+ );
4049
+ emit({
4050
+ type: "guard",
4051
+ ...span2,
4052
+ state: "retrying",
4053
+ llmWords: cov.llmWords,
4054
+ asrWords: cov.asrWords
4055
+ });
4056
+ client ??= new GeminiClient(keys.gemini, geminiOpts);
4057
+ retry = await transcribeInHalves({
4058
+ client,
4059
+ model: models.transcribe,
4060
+ audioPath,
4061
+ chunk: plan,
4062
+ pathPrefix: `${llmDir}/chunk_${String(plan.index).padStart(2, "0")}`,
4063
+ ctx: {
4064
+ index: plan.index + 1,
4065
+ total: chunks.length,
4066
+ description: description?.description,
4067
+ roster: description?.roster,
4068
+ instructions: options.instructions
4069
+ },
4070
+ audioOpts: AUDIO_OPTS
4071
+ }).catch(stageTag("llm-transcribe"));
4072
+ writeJson(retryPath, retry);
4073
+ }
4074
+ if (retry) {
4075
+ const again = chunkCoverage(
4076
+ retry.segments,
4077
+ asrResult.words,
4078
+ plan.start,
4079
+ plan.end
4080
+ );
4081
+ logger.info(
4082
+ `${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"}`
4083
+ );
4084
+ const kept = again.ratio > cov.ratio;
4085
+ emit({
4086
+ type: "guard",
4087
+ ...span2,
4088
+ state: kept ? "recovered" : "unchanged",
4089
+ llmWords: cov.llmWords,
4090
+ asrWords: cov.asrWords,
4091
+ retryWords: again.llmWords
4092
+ });
4093
+ if (kept) {
4094
+ llmChunkResults[i] = tagWith(retry, plan);
4095
+ cov = again;
4096
+ status = again.low ? "low-coverage" : "retried";
4097
+ }
4098
+ }
4099
+ }
4100
+ quality.push({
4101
+ chunk: plan.index,
4102
+ start: plan.start,
4103
+ end: plan.end,
4104
+ status,
4105
+ llmWords: cov.llmWords,
4106
+ asrWords: cov.asrWords,
4107
+ coverage: Number.isFinite(cov.ratio) ? Number(cov.ratio.toFixed(2)) : null
4108
+ });
4109
+ }
4110
+ }
4111
+ const whole = asrResult?.words.length ? chunkCoverage(
4112
+ llmChunkResults.flatMap((r) => r.segments),
4113
+ asrResult.words,
4114
+ 0,
4115
+ Infinity
4116
+ ) : null;
4117
+ const asrMissedSpeech = !!whole && whole.llmWords >= 200 && whole.ratio > 3;
4118
+ if (asrMissedSpeech) {
4119
+ logger.warn(
4120
+ `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)`
4121
+ );
4122
+ }
3368
4123
  let allLlmSegments = llmChunkResults.flatMap((r) => r.segments);
4124
+ const timingWords = asrMissedSpeech ? [] : asrResult?.words ?? [];
4125
+ allLlmSegments = toAsrClock(allLlmSegments, timingWords);
3369
4126
  const beforePart = allLlmSegments.length;
3370
4127
  allLlmSegments = partitionByOwnership(allLlmSegments);
3371
4128
  if (beforePart !== allLlmSegments.length) {
@@ -3374,81 +4131,68 @@ ${lines.join("\n\n")}
3374
4131
  );
3375
4132
  }
3376
4133
  logger.info(`total LLM segments: ${allLlmSegments.length}`);
3377
- let asrResult = null;
3378
- if (has(passes, "timestamped") || has(passes, "align")) {
3379
- checkAbort();
3380
- const provider = options.timestampedProvider ?? "assemblyai";
3381
- if (provider === "whisper-groq") {
3382
- logger.info("=== timestamped (Groq Whisper \u2014 no diarization) ===");
3383
- if (!keys.groq) throw new Error("GROQ_API_KEY is required for whisper-groq");
3384
- if (!existsSync3(audioPath) || forceAll) {
3385
- await extractAudio(options.input, audioPath, AUDIO_OPTS);
4134
+ if (asrResult?.words.length && (has(passes, "align") || has(passes, "consistency"))) {
4135
+ const dropped = /* @__PURE__ */ new Set();
4136
+ for (let i = 0; i < llmChunkResults.length; i++) {
4137
+ const r = llmChunkResults[i];
4138
+ const plan = llmChunkPlans[i];
4139
+ const q = quality.find((x) => x.chunk === plan.index);
4140
+ const where = `chunk ${plan.index} [${plan.start.toFixed(0)}-${plan.end.toFixed(0)}]s`;
4141
+ const compression = maxCompressionRatio(r.segments.map((s) => s.text).join(" "));
4142
+ if (compression > DEGENERATE_COMPRESSION_RATIO) {
4143
+ dropped.add(plan.index);
4144
+ if (q) q.status = "dropped-loop";
4145
+ logger.warn(
4146
+ `${where}: dropping repetition-loop text (compression ratio ${compression.toFixed(1)}) \u2014 ASR will fill this range`
4147
+ );
4148
+ continue;
3386
4149
  }
3387
- const { readFile: readFile2 } = await import("fs/promises");
3388
- const buf = await readFile2(audioPath);
3389
- const groq = new WhisperGroqClient(keys.groq);
3390
- asrResult = await groq.transcribe(buf).catch(stageTag("asr"));
3391
- writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3392
- } else if (provider === "elevenlabs") {
3393
- logger.info("=== timestamped (ElevenLabs Scribe v2) ===");
3394
- if (!keys.elevenlabs)
3395
- throw new Error("ELEVENLABS_API_KEY is required for --timestamped elevenlabs");
3396
- const cachePath = `${options.intermediatesDir}/timestamped-elevenlabs.json`;
3397
- asrResult = forceAll ? null : readJson(cachePath);
3398
- if (!asrResult) {
3399
- const { readFile: readFile2 } = await import("fs/promises");
3400
- const buf = await readFile2(audioPath);
3401
- const el = new ElevenLabsClient(keys.elevenlabs);
3402
- asrResult = await el.transcribe(buf).catch(stageTag("asr"));
3403
- writeJson(cachePath, asrResult);
3404
- } else {
3405
- logger.info("[elevenlabs] cache hit");
4150
+ const g = chunkGrounding(r.segments, asrResult.words, plan.start, plan.end);
4151
+ if (!g.grounded) {
4152
+ if (q) q.ungrounded = true;
4153
+ logger.warn(
4154
+ `${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)`
4155
+ );
3406
4156
  }
3407
- writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3408
- logger.info(
3409
- `[elevenlabs] ${asrResult.utterances.length} utterances, ${asrResult.words.length} words, ${asrResult.speakers?.length ?? "?"} speakers`
4157
+ }
4158
+ if (dropped.size) {
4159
+ allLlmSegments = allLlmSegments.filter(
4160
+ (s) => s.chunkIndex === void 0 || !dropped.has(s.chunkIndex)
3410
4161
  );
3411
- } else {
3412
- logger.info("=== timestamped (AssemblyAI) ===");
3413
- if (!keys.assemblyai)
3414
- throw new Error(
3415
- "ASSEMBLYAI_API_KEY is required for the timestamped pass (or use --timestamped whisper-groq)"
3416
- );
3417
- const aai = new AssemblyAIProvider({
3418
- apiKey: keys.assemblyai,
3419
- cacheDir: `${options.intermediatesDir}/assemblyai`
3420
- });
3421
- asrResult = await aai.transcribe(audioPath).catch(stageTag("asr"));
3422
- writeJson(`${options.intermediatesDir}/timestamped.json`, asrResult);
3423
4162
  }
3424
- } else {
3425
- asrResult = forceAll ? null : readJson(`${options.intermediatesDir}/timestamped.json`);
3426
4163
  }
3427
4164
  let aligned = [];
3428
- if (has(passes, "align") && asrResult) {
4165
+ if (has(passes, "align") && (asrResult || tsProvider === "none")) {
3429
4166
  logger.info("=== align ===");
3430
- aligned = alignSegments(allLlmSegments, asrResult.words, { timeMarginSec: 30 });
4167
+ emit({ type: "stage", stage: "align", state: "start" });
4168
+ aligned = alignSegments(allLlmSegments, timingWords, { timeMarginSec: 30 });
3431
4169
  writeJson(`${options.intermediatesDir}/aligned.json`, aligned);
3432
4170
  } else {
3433
4171
  aligned = (forceAll ? null : readJson(`${options.intermediatesDir}/aligned.json`)) ?? [];
3434
4172
  }
3435
4173
  const alignedOk = aligned.filter((a) => a.timingSource !== "coarse").length;
3436
4174
  logger.info(`aligned: ${alignedOk}/${aligned.length} with ASR timing`);
3437
- if (asrResult && (has(passes, "align") || has(passes, "consistency"))) {
3438
- const before = aligned.length;
4175
+ let gapFilledWords = 0;
4176
+ if (asrResult && !asrMissedSpeech && (has(passes, "align") || has(passes, "consistency"))) {
3439
4177
  aligned = fillAsrGaps(aligned, asrResult.words, asrResult.utterances);
3440
- const added = aligned.length - before;
3441
- if (added) logger.info(`gap-filled ${added} ASR fallback segment(s)`);
4178
+ const added = aligned.filter((a) => a.timingSource === "timestamped");
4179
+ gapFilledWords = added.reduce((n, a) => n + a.words.length, 0);
4180
+ if (added.length) {
4181
+ logger.info(
4182
+ `gap-filled ${added.length} ASR fallback segment(s) (${gapFilledWords} words)`
4183
+ );
4184
+ }
3442
4185
  }
3443
4186
  if (asrResult && (asrResult.hasDiarization ?? true) && (has(passes, "align") || has(passes, "consistency"))) {
3444
4187
  aligned = splitMixedVoiceSegments(aligned, asrResult.utterances);
3445
4188
  }
3446
4189
  let segments = aligned;
3447
4190
  let speakers = [];
3448
- if (has(passes, "consistency") && asrResult) {
4191
+ if (has(passes, "consistency") && (asrResult || tsProvider === "none")) {
3449
4192
  logger.info("=== consistency ===");
3450
- const cons = assignGlobalSpeakers(aligned, asrResult.utterances, {
3451
- hasDiarization: asrResult.hasDiarization ?? true
4193
+ emit({ type: "stage", stage: "speakers", state: "start" });
4194
+ const cons = assignGlobalSpeakers(aligned, asrResult?.utterances ?? [], {
4195
+ hasDiarization: asrResult ? asrResult.hasDiarization ?? true : false
3452
4196
  });
3453
4197
  segments = cons.segments;
3454
4198
  speakers = cons.speakers;
@@ -3470,19 +4214,22 @@ ${lines.join("\n\n")}
3470
4214
  (s) => s.speakerName !== s.speaker ? { ...s, speakerName: s.speaker } : s
3471
4215
  );
3472
4216
  speakers = speakers.map((sp) => sp.name !== sp.id ? { ...sp, name: sp.id } : sp);
3473
- if (options.diarizationLevel >= 3 && has(passes, "identify")) {
3474
- const reasonerA = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
4217
+ if (naming) {
3475
4218
  if (!reasonerA) {
3476
4219
  logger.warn(
3477
4220
  "identify: no reasoner-capable API key found (DEEPSEEK/GEMINI/OPENAI/\u2026) \u2014 skipping speaker naming"
3478
4221
  );
3479
4222
  } else {
3480
4223
  const mode = options.identifyMode;
3481
- const reasonerB = mode === "dual" ? resolveSecondReasoner(reasonerA.info, keys) : null;
3482
4224
  const idConfig = {
3483
4225
  mode,
3484
4226
  reasonerA: reasonerA.info.model,
3485
- reasonerB: reasonerB?.info.model ?? null
4227
+ reasonerB: reasonerB?.info.model ?? null,
4228
+ knownSpeakers: options.knownSpeakers ?? [],
4229
+ // What the naming step reads. If a re-run changes the transcript (a re-transcribed
4230
+ // chunk can reorder speakers by talk time), "Speaker A" may now be the other voice,
4231
+ // and the cached names must not be applied to it.
4232
+ inputs: createHash3("sha1").update(JSON.stringify(segments.map((s) => [s.speaker, s.text]))).update(JSON.stringify(speakers.map((sp) => sp.id))).digest("hex")
3486
4233
  };
3487
4234
  const idCachePath = `${options.intermediatesDir}/identified.json`;
3488
4235
  const cachedId = forceAll ? null : readJson(
@@ -3492,11 +4239,18 @@ ${lines.join("\n\n")}
3492
4239
  let nameMap = null;
3493
4240
  if (idConfigMatches && cachedId?.nameMap && Object.keys(cachedId.nameMap).length > 0) {
3494
4241
  logger.info("=== identify (cached) ===");
4242
+ emit({ type: "stage", stage: "identify", state: "cached" });
3495
4243
  nameMap = cachedId.nameMap;
3496
4244
  } else {
3497
4245
  logger.info(
3498
4246
  `=== identify (${reasonerA.info.model}${reasonerB ? ` + ${reasonerB.info.model} second opinion` : ""}) ===`
3499
4247
  );
4248
+ emit({
4249
+ type: "stage",
4250
+ stage: "identify",
4251
+ state: "start",
4252
+ detail: reasonerB ? `${reasonerA.info.model} + ${reasonerB.info.model}` : reasonerA.info.model
4253
+ });
3500
4254
  checkAbort();
3501
4255
  const id = await identifySpeakersV2(
3502
4256
  {
@@ -3521,11 +4275,14 @@ ${lines.join("\n\n")}
3521
4275
  ).catch(stageTag("identify"));
3522
4276
  writeJson(idCachePath, { ...id, config: idConfig });
3523
4277
  nameMap = id.nameMap;
4278
+ if (id.allPassesFailed)
4279
+ emit({ type: "stage", stage: "identify", state: "failed" });
3524
4280
  }
3525
4281
  logger.info(
3526
4282
  `identified ${Object.keys(nameMap).length} speakers: ${JSON.stringify(nameMap)}`
3527
4283
  );
3528
4284
  const nm = nameMap;
4285
+ emit({ type: "names", names: nm });
3529
4286
  segments = segments.map(
3530
4287
  (s) => nm[s.speaker] ? { ...s, speakerName: nm[s.speaker] } : s
3531
4288
  );
@@ -3535,13 +4292,14 @@ ${lines.join("\n\n")}
3535
4292
  let finalSegments = [];
3536
4293
  if (has(passes, "finalize")) {
3537
4294
  logger.info("=== finalize ===");
4295
+ emit({ type: "stage", stage: "finalize", state: "start" });
3538
4296
  finalSegments = finalizeSegments(segments);
3539
4297
  writeJson(`${options.intermediatesDir}/final.json`, finalSegments);
3540
4298
  } else {
3541
4299
  finalSegments = (forceAll ? null : readJson(`${options.intermediatesDir}/final.json`)) ?? [];
3542
4300
  }
3543
4301
  logger.info(`final segments: ${finalSegments.length}`);
3544
- const receipt = computeReceipt(getLlmUsage(), tsProvider, duration);
4302
+ const receipt = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
3545
4303
  const wallMs = Date.now() - runStartedAt;
3546
4304
  const metadata = {
3547
4305
  sourceFile: options.input,
@@ -3561,86 +4319,103 @@ ${lines.join("\n\n")}
3561
4319
  llmCalls: receipt.totals.calls,
3562
4320
  inputTokens: receipt.totals.inputTokens,
3563
4321
  outputTokens: receipt.totals.outputTokens
3564
- }
4322
+ },
4323
+ ...asrResult ? { quality: { chunks: quality, gapFilledWords, asrMissedSpeech } } : {},
4324
+ zeroStorage: options.zeroStorage
3565
4325
  };
4326
+ const degraded = quality.filter((q) => q.status !== "ok");
4327
+ if (degraded.length || asrMissedSpeech) {
4328
+ logger.warn(
4329
+ `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`
4330
+ );
4331
+ }
3566
4332
  const result = { segments: finalSegments, speakers, metadata };
3567
4333
  writeJson(`${options.intermediatesDir}/result.json`, result);
4334
+ const base = basename3(options.input, ext(options.input));
4335
+ const written = [];
4336
+ const write = (name, content) => {
4337
+ const path = `${options.outputDir}/${name}`;
4338
+ writeFileSync2(path, content);
4339
+ written.push(resolve2(path));
4340
+ };
3568
4341
  for (const fmt of options.formats) {
3569
- const base = basename3(options.input, ext(options.input));
3570
- if (fmt === "srt")
3571
- writeFileSync2(
3572
- `${options.outputDir}/${base}.srt`,
3573
- formatSrt(result, { title: base })
3574
- );
4342
+ if (fmt === "srt") write(`${base}.srt`, formatSrt(result, { title: base }));
3575
4343
  if (fmt === "md")
3576
- writeFileSync2(
3577
- `${options.outputDir}/${base}.md`,
4344
+ write(
4345
+ `${base}.md`,
3578
4346
  formatMarkdown(result, { title: base, mdStyle: options.mdStyle })
3579
4347
  );
3580
- if (fmt === "txt")
3581
- writeFileSync2(
3582
- `${options.outputDir}/${base}.txt`,
3583
- formatText(result, { title: base })
3584
- );
3585
- if (fmt === "html")
3586
- writeFileSync2(
3587
- `${options.outputDir}/${base}.html`,
3588
- formatHtml(result, { title: base })
3589
- );
3590
- if (fmt === "json")
3591
- writeFileSync2(`${options.outputDir}/${base}.json`, formatJson(result));
4348
+ if (fmt === "txt") write(`${base}.txt`, formatText(result, { title: base }));
4349
+ if (fmt === "html") write(`${base}.html`, formatHtml(result, { title: base }));
4350
+ if (fmt === "json") write(`${base}.json`, formatJson(result));
3592
4351
  }
3593
4352
  if (options.summary && finalSegments.length > 0) {
3594
- const reasoner = resolveReasoner(options.reasoner ?? DEFAULT_REASONER_MODEL, keys);
3595
- if (!reasoner) {
4353
+ if (!reasonerA) {
3596
4354
  logger.warn("summary: no reasoner-capable key \u2014 skipping");
3597
4355
  } else {
3598
- logger.info(`=== summary (${reasoner.info.model}) ===`);
4356
+ logger.info(`=== summary (${reasonerA.info.model}) ===`);
4357
+ emit({
4358
+ type: "stage",
4359
+ stage: "summary",
4360
+ state: "start",
4361
+ detail: reasonerA.info.model
4362
+ });
3599
4363
  try {
3600
4364
  const summary = await summarizeTranscript(
3601
- reasoner.client,
3602
- reasoner.info.model,
4365
+ reasonerA.client,
4366
+ reasonerA.info.model,
3603
4367
  result,
3604
4368
  options.instructions
3605
4369
  );
3606
- const base = basename3(options.input, ext(options.input));
3607
- writeFileSync2(`${options.outputDir}/${base}.summary.md`, summary);
4370
+ write(`${base}.summary.md`, summary);
3608
4371
  logger.info(`summary written to ${base}.summary.md`);
3609
4372
  } catch (err) {
3610
4373
  logger.warn(`summary failed: ${err instanceof Error ? err.message : err}`);
4374
+ emit({ type: "stage", stage: "summary", state: "failed" });
3611
4375
  }
3612
4376
  }
3613
4377
  }
3614
4378
  try {
3615
- const base = basename3(options.input, ext(options.input));
3616
4379
  const partial = `${options.outputDir}/${base}.partial.md`;
3617
- if (existsSync3(partial)) (await import("fs/promises")).unlink(partial);
4380
+ if (existsSync4(partial)) (await import("fs/promises")).unlink(partial);
3618
4381
  } catch {
3619
4382
  }
3620
4383
  logger.info(`outputs written to ${options.outputDir}`);
3621
- const mins = Math.floor(wallMs / 6e4);
3622
- const secs = Math.round(wallMs % 6e4 / 1e3);
4384
+ const spent = computeReceipt(getLlmUsage(), tsProvider, duration, asrBilled);
4385
+ const runMs = Date.now() - runStartedAt;
4386
+ const mins = Math.floor(runMs / 6e4);
4387
+ const secs = Math.round(runMs % 6e4 / 1e3);
3623
4388
  logger.info(
3624
- `receipt: ${receipt.totals.calls} LLM calls \xB7 ${(receipt.totals.inputTokens / 1e3).toFixed(0)}k in / ${(receipt.totals.outputTokens / 1e3).toFixed(0)}k out \xB7 ~$${receipt.totalUsd.toFixed(2)}${receipt.incomplete ? " (+unpriced)" : ""} \xB7 ${mins ? `${mins}m` : ""}${secs}s`
4389
+ `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`
3625
4390
  );
3626
- for (const line of receipt.lines) logger.info(` ${line}`);
4391
+ for (const line of spent.lines) logger.info(` ${line}`);
3627
4392
  recordRun(
3628
4393
  {
3629
4394
  ts: (/* @__PURE__ */ new Date()).toISOString(),
3630
4395
  input: basename3(options.input),
3631
4396
  durationSec: duration,
3632
- wallMs,
4397
+ wallMs: runMs,
3633
4398
  models: metadata.models,
3634
4399
  segments: finalSegments.length,
3635
4400
  characters: finalSegments.reduce((n, s) => n + s.text.length, 0),
3636
4401
  speakers: speakers.length,
3637
- llmCalls: receipt.totals.calls,
3638
- inputTokens: receipt.totals.inputTokens,
3639
- outputTokens: receipt.totals.outputTokens,
3640
- costUsd: receipt.totalUsd
4402
+ llmCalls: spent.totals.calls,
4403
+ inputTokens: spent.totals.inputTokens,
4404
+ outputTokens: spent.totals.outputTokens,
4405
+ costUsd: spent.totalUsd
3641
4406
  },
3642
- receipt.perModel
4407
+ spent.perModel
3643
4408
  );
4409
+ emit({
4410
+ type: "done",
4411
+ segments: finalSegments.length,
4412
+ speakers: speakers.length,
4413
+ durationSec: duration,
4414
+ costUsd: spent.totalUsd,
4415
+ wallMs: runMs,
4416
+ retriedChunks: quality.filter((q) => q.status === "retried").length,
4417
+ outputs: written
4418
+ });
3644
4419
  return result;
3645
4420
  }
3646
4421
  function ext(p) {
@@ -3648,14 +4423,85 @@ function ext(p) {
3648
4423
  return i >= 0 ? p.slice(i) : "";
3649
4424
  }
3650
4425
 
4426
+ // src/commands/inputs.ts
4427
+ import { readdirSync as readdirSync2, statSync as statSync2 } from "fs";
4428
+ import { basename as basename4, dirname as dirname4, extname, join as join3, resolve as resolve3 } from "path";
4429
+ var MEDIA_EXTS = /* @__PURE__ */ new Set([
4430
+ ".mp4",
4431
+ ".mov",
4432
+ ".mkv",
4433
+ ".webm",
4434
+ ".avi",
4435
+ ".m4a",
4436
+ ".mp3",
4437
+ ".wav",
4438
+ ".aac",
4439
+ ".flac",
4440
+ ".ogg",
4441
+ ".opus",
4442
+ ".wma"
4443
+ ]);
4444
+ var byName = new Intl.Collator(void 0, { numeric: true, sensitivity: "base" }).compare;
4445
+ function expandInputs(paths) {
4446
+ const files = [];
4447
+ const missing = [];
4448
+ const empty = [];
4449
+ const seen = /* @__PURE__ */ new Set();
4450
+ const add = (file) => {
4451
+ const key = resolve3(file);
4452
+ if (seen.has(key)) return;
4453
+ seen.add(key);
4454
+ files.push(file);
4455
+ };
4456
+ for (const path of paths) {
4457
+ let isDir;
4458
+ try {
4459
+ isDir = statSync2(path).isDirectory();
4460
+ } catch {
4461
+ missing.push(path);
4462
+ continue;
4463
+ }
4464
+ if (!isDir) {
4465
+ add(path);
4466
+ continue;
4467
+ }
4468
+ const media = readdirSync2(path, { withFileTypes: true }).filter(
4469
+ (e) => e.isFile() && !e.name.startsWith(".") && MEDIA_EXTS.has(extname(e.name).toLowerCase())
4470
+ ).map((e) => e.name).sort(byName);
4471
+ if (media.length === 0) empty.push(path);
4472
+ for (const name of media) add(join3(path, name));
4473
+ }
4474
+ return { files, missing, empty };
4475
+ }
4476
+ function outputClashes(files, outputDir) {
4477
+ const byOutput = /* @__PURE__ */ new Map();
4478
+ const clashes = [];
4479
+ for (const file of files) {
4480
+ const dir = resolve3(outputDir ?? dirname4(file));
4481
+ const key = join3(dir, basename4(file, extname(file))).toLowerCase();
4482
+ const first = byOutput.get(key);
4483
+ if (first) clashes.push([first, file]);
4484
+ else byOutput.set(key, file);
4485
+ }
4486
+ return clashes;
4487
+ }
4488
+
3651
4489
  // src/commands/models.ts
3652
4490
  var TRANSCRIBE_PRESETS = [
3653
- { model: "gemini-3.1-pro-preview", note: "default \u2014 best diarization/tone" },
3654
- { model: "gemini-3.5-flash", note: "fast/cheap \u2014 great daily driver" },
3655
- { model: "gemini-flash-latest", note: "moving alias, stays current" },
3656
- { model: "gemini-3-pro-preview", note: "" },
3657
- { model: "gemini-2.5-pro", note: "" },
3658
- { model: "gemini-2.5-flash", note: "" }
4491
+ {
4492
+ model: DEFAULT_TRANSCRIBE_MODEL,
4493
+ note: "kept 96.6% of the speech on hard chunks, $0.74/hour"
4494
+ },
4495
+ {
4496
+ model: PRO_TRANSCRIBE_MODEL,
4497
+ note: "--pro \xB7 kept the most (97.3%), slower, ~2\xD7 from 1 Dec"
4498
+ },
4499
+ { model: "gemini-3.8-flash", note: "about a third of the cost until 1 Jan 2027" },
4500
+ {
4501
+ model: "gemini-3.1-pro-preview",
4502
+ note: "the 0.1.x default; dropped whole chunks on hard audio"
4503
+ },
4504
+ { model: "gemini-flash-latest", note: "moving alias, stays current" }
3659
4505
  ];
3660
4506
  var TIMESTAMPED_PRESETS = [
3661
4507
  {
@@ -3706,6 +4552,14 @@ async function runModels() {
3706
4552
  lines.push('(e.g. "zai:glm-4.7") works for --reasoner. Keys come from the environment');
3707
4553
  lines.push("or can be injected via the library API.");
3708
4554
  lines.push("");
4555
+ lines.push(
4556
+ "Zero storage (on by default) asks Gemini and AssemblyAI to keep nothing. The other"
4557
+ );
4558
+ lines.push(
4559
+ "providers have no way to be asked; each run's plan line names the ones it uses."
4560
+ );
4561
+ lines.push("--no-zero-storage leaves every provider to its own retention.");
4562
+ lines.push("");
3709
4563
  console.log(lines.join("\n"));
3710
4564
  }
3711
4565
 
@@ -3740,6 +4594,22 @@ function providerChecks(keys) {
3740
4594
  {}
3741
4595
  )
3742
4596
  );
4597
+ for (const [model, role] of [
4598
+ [DEFAULT_TRANSCRIBE_MODEL, "default"],
4599
+ [PRO_TRANSCRIBE_MODEL, "--pro"]
4600
+ ]) {
4601
+ checks.push({
4602
+ name: `${model} (${role})`,
4603
+ run: async () => {
4604
+ if (!keys.gemini) throw new Error("no key in environment");
4605
+ await ping(
4606
+ `https://generativelanguage.googleapis.com/v1beta/models/${model}?key=${keys.gemini}`,
4607
+ {}
4608
+ );
4609
+ return "available to this key";
4610
+ }
4611
+ });
4612
+ }
3743
4613
  add(
3744
4614
  "assemblyai (timestamped)",
3745
4615
  keys.assemblyai,
@@ -3809,7 +4679,9 @@ async function runDoctor() {
3809
4679
  const okByName = (needle) => checks.some(
3810
4680
  (c, i) => c.name.startsWith(needle) && results[i]?.status === "fulfilled"
3811
4681
  );
3812
- const geminiOk = okByName("gemini");
4682
+ const keyOk = okByName("gemini (transcribe)");
4683
+ const modelOk = okByName(`${DEFAULT_TRANSCRIBE_MODEL} (default)`);
4684
+ const geminiOk = keyOk && modelOk;
3813
4685
  const assemblyOk = okByName("assemblyai");
3814
4686
  const elevenOk = okByName("elevenlabs");
3815
4687
  const groqOk = okByName("groq");
@@ -3824,10 +4696,14 @@ async function runDoctor() {
3824
4696
  `);
3825
4697
  } else {
3826
4698
  if (!ff) console.log(" Blocked: install ffmpeg (e.g. `brew install ffmpeg`).");
3827
- if (!geminiOk)
4699
+ if (!keyOk)
3828
4700
  console.log(
3829
4701
  " Blocked: set GEMINI_API_KEY (or GOOGLE_API_KEY) \u2014 required for transcription."
3830
4702
  );
4703
+ else if (!modelOk)
4704
+ console.log(
4705
+ ` Blocked: this key can't use ${DEFAULT_TRANSCRIBE_MODEL}, the default \u2014 pass --model with one it can (\`offmute-v2 models\` lists them).`
4706
+ );
3831
4707
  if (!assemblyOk && !elevenOk && !groqOk)
3832
4708
  console.log(
3833
4709
  " Degraded: no timestamped provider (ASSEMBLYAI/ELEVENLABS/GROQ key) \u2014 timestamps will be coarse."
@@ -3874,22 +4750,22 @@ No runs recorded yet (stats live in ${statsDir()}).
3874
4750
  }
3875
4751
 
3876
4752
  // src/commands/rename.ts
3877
- import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
3878
- import { basename as basename4, dirname as dirname4, join as join2, resolve as resolve3 } from "path";
4753
+ import { existsSync as existsSync5, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
4754
+ import { basename as basename5, dirname as dirname5, join as join4, resolve as resolve4 } from "path";
3879
4755
  function loadSource(path, opts) {
3880
4756
  if (path.endsWith(".json")) {
3881
4757
  return {
3882
4758
  result: JSON.parse(readFileSync3(path, "utf-8")),
3883
- outDir: opts.output ?? dirname4(resolve3(path)),
3884
- base: basename4(path, ".json"),
4759
+ outDir: opts.output ?? dirname5(resolve4(path)),
4760
+ base: basename5(path, ".json"),
3885
4761
  jsonPath: path
3886
4762
  };
3887
4763
  }
3888
4764
  const cacheDir = opts.intermediates ?? deriveIntermediatesDir(path);
3889
- const resultPath = join2(cacheDir, "result.json");
3890
- const sourcePath = join2(cacheDir, "source.json");
3891
- if (!existsSync4(resultPath)) {
3892
- console.error(`\u2717 no cached transcript found for ${basename4(path)}`);
4765
+ const resultPath = join4(cacheDir, "result.json");
4766
+ const sourcePath = join4(cacheDir, "source.json");
4767
+ if (!existsSync5(resultPath)) {
4768
+ console.error(`\u2717 no cached transcript found for ${basename5(path)}`);
3893
4769
  console.error(
3894
4770
  ` the cache lives in the OS temp dir and may have been cleaned up.
3895
4771
  re-run first: offmute-v2 "${path}" (then rename again \u2014 naming is cached)`
@@ -3900,7 +4776,7 @@ function loadSource(path, opts) {
3900
4776
  const src = JSON.parse(readFileSync3(sourcePath, "utf-8"));
3901
4777
  if (src.signature && src.signature !== inputSignature(path)) {
3902
4778
  console.error(
3903
- `\u2717 the cached transcript is from an older version of ${basename4(path)}`
4779
+ `\u2717 the cached transcript is from an older version of ${basename5(path)}`
3904
4780
  );
3905
4781
  console.error(` re-run first: offmute-v2 "${path}"`);
3906
4782
  process.exit(1);
@@ -3910,8 +4786,8 @@ function loadSource(path, opts) {
3910
4786
  const ext2 = path.slice(path.lastIndexOf("."));
3911
4787
  return {
3912
4788
  result: JSON.parse(readFileSync3(resultPath, "utf-8")),
3913
- outDir: opts.output ?? dirname4(resolve3(path)),
3914
- base: basename4(path, ext2),
4789
+ outDir: opts.output ?? dirname5(resolve4(path)),
4790
+ base: basename5(path, ext2),
3915
4791
  jsonPath: resultPath
3916
4792
  };
3917
4793
  }
@@ -3961,8 +4837,8 @@ function runRename(path, mappings, opts) {
3961
4837
  process.exit(1);
3962
4838
  }
3963
4839
  writeFileSync3(jsonPath, JSON.stringify(result, null, 2));
3964
- const idPath = join2(dirname4(jsonPath), "identified.json");
3965
- if (basename4(jsonPath) === "result.json" && existsSync4(idPath)) {
4840
+ const idPath = join4(dirname5(jsonPath), "identified.json");
4841
+ if (basename5(jsonPath) === "result.json" && existsSync5(idPath)) {
3966
4842
  try {
3967
4843
  const id = JSON.parse(readFileSync3(idPath, "utf-8"));
3968
4844
  id.nameMap ??= {};
@@ -3976,7 +4852,7 @@ function runRename(path, mappings, opts) {
3976
4852
  const formats = opts.formats.split(",").map((f) => f.trim());
3977
4853
  const written = [];
3978
4854
  const write = (name, contents) => {
3979
- const p = join2(outDir, name);
4855
+ const p = join4(outDir, name);
3980
4856
  writeFileSync3(p, contents);
3981
4857
  written.push(p);
3982
4858
  };
@@ -3986,7 +4862,7 @@ function runRename(path, mappings, opts) {
3986
4862
  if (formats.includes("txt")) write(`${base}.txt`, formatText(result, { title: base }));
3987
4863
  if (formats.includes("html"))
3988
4864
  write(`${base}.html`, formatHtml(result, { title: base }));
3989
- if (formats.includes("json") && jsonPath !== join2(outDir, `${base}.json`)) {
4865
+ if (formats.includes("json") && jsonPath !== join4(outDir, `${base}.json`)) {
3990
4866
  write(`${base}.json`, JSON.stringify(result, null, 2));
3991
4867
  }
3992
4868
  console.log(`Renamed ${applied.size} speaker(s).`);
@@ -3995,16 +4871,16 @@ function runRename(path, mappings, opts) {
3995
4871
 
3996
4872
  // src/commands/watch.ts
3997
4873
  import {
3998
- existsSync as existsSync5,
4874
+ existsSync as existsSync6,
3999
4875
  mkdirSync as mkdirSync3,
4000
4876
  readFileSync as readFileSync4,
4001
4877
  writeFileSync as writeFileSync4,
4002
4878
  appendFileSync as appendFileSync3,
4003
4879
  watch as fsWatch,
4004
- statSync as statSync2,
4005
- readdirSync
4880
+ statSync as statSync3,
4881
+ readdirSync as readdirSync3
4006
4882
  } from "fs";
4007
- import { join as join3, extname, basename as basename5 } from "path";
4883
+ import { join as join5, extname as extname2, basename as basename6 } from "path";
4008
4884
 
4009
4885
  // src/utils/notify.ts
4010
4886
  import { execFile } from "child_process";
@@ -4030,36 +4906,21 @@ function notify(title, message) {
4030
4906
  }
4031
4907
 
4032
4908
  // src/commands/watch.ts
4033
- var MEDIA_EXTS = /* @__PURE__ */ new Set([
4034
- ".mp4",
4035
- ".mov",
4036
- ".mkv",
4037
- ".webm",
4038
- ".avi",
4039
- ".m4a",
4040
- ".mp3",
4041
- ".wav",
4042
- ".aac",
4043
- ".flac",
4044
- ".ogg",
4045
- ".opus",
4046
- ".wma"
4047
- ]);
4048
4909
  var POLL_MS = 5e3;
4049
4910
  function ts() {
4050
4911
  return (/* @__PURE__ */ new Date()).toTimeString().slice(0, 8);
4051
4912
  }
4052
4913
  async function runWatch(dir, opts) {
4053
- if (!existsSync5(dir) || !statSync2(dir).isDirectory()) {
4914
+ if (!existsSync6(dir) || !statSync3(dir).isDirectory()) {
4054
4915
  console.error(`\u2717 not a directory: ${dir}`);
4055
4916
  process.exit(1);
4056
4917
  }
4057
- const stateDir = join3(dir, ".offmute");
4918
+ const stateDir = join5(dir, ".offmute");
4058
4919
  mkdirSync3(stateDir, { recursive: true });
4059
- const statePath = join3(stateDir, "state.json");
4060
- const logPath2 = join3(stateDir, "daemon.log");
4920
+ const statePath = join5(stateDir, "state.json");
4921
+ const logPath2 = join5(stateDir, "daemon.log");
4061
4922
  let state = { done: {} };
4062
- if (existsSync5(statePath)) {
4923
+ if (existsSync6(statePath)) {
4063
4924
  try {
4064
4925
  const parsed = JSON.parse(readFileSync4(statePath, "utf-8"));
4065
4926
  state = { done: parsed.done ?? {} };
@@ -4084,7 +4945,7 @@ async function runWatch(dir, opts) {
4084
4945
  let processed = 0;
4085
4946
  const listCandidates = () => {
4086
4947
  try {
4087
- return readdirSync(dir).filter((f) => !f.startsWith(".")).filter((f) => matchExts.has(extname(f).toLowerCase())).map((f) => join3(dir, f));
4948
+ return readdirSync3(dir).filter((f) => !f.startsWith(".")).filter((f) => matchExts.has(extname2(f).toLowerCase())).map((f) => join5(dir, f));
4088
4949
  } catch {
4089
4950
  return [];
4090
4951
  }
@@ -4095,7 +4956,7 @@ async function runWatch(dir, opts) {
4095
4956
  if (queued.has(file) || failedThisSession.has(file)) continue;
4096
4957
  let st;
4097
4958
  try {
4098
- st = statSync2(file);
4959
+ st = statSync3(file);
4099
4960
  } catch {
4100
4961
  continue;
4101
4962
  }
@@ -4105,7 +4966,7 @@ async function runWatch(dir, opts) {
4105
4966
  if (isFirst && !opts.backlog) {
4106
4967
  if (!record || record.error) {
4107
4968
  state.done[sig] = {
4108
- file: basename5(file),
4969
+ file: basename6(file),
4109
4970
  finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
4110
4971
  skipped: true
4111
4972
  };
@@ -4115,7 +4976,7 @@ async function runWatch(dir, opts) {
4115
4976
  if (isFirst && record?.error) {
4116
4977
  delete state.done[sig];
4117
4978
  record = void 0;
4118
- log2(`retrying ${basename5(file)} (failed last session)`);
4979
+ log2(`retrying ${basename6(file)} (failed last session)`);
4119
4980
  }
4120
4981
  if (record) continue;
4121
4982
  const prev = seenSizes.get(file);
@@ -4123,7 +4984,7 @@ async function runWatch(dir, opts) {
4123
4984
  queued.add(file);
4124
4985
  queue.push(file);
4125
4986
  log2(
4126
- `queued ${basename5(file)} (${(st.size / 1e6).toFixed(0)}MB, queue: ${queue.length})`
4987
+ `queued ${basename6(file)} (${(st.size / 1e6).toFixed(0)}MB, queue: ${queue.length})`
4127
4988
  );
4128
4989
  } else {
4129
4990
  seenSizes.set(file, { size: st.size, mtimeMs: st.mtimeMs });
@@ -4146,7 +5007,7 @@ async function runWatch(dir, opts) {
4146
5007
  }
4147
5008
  };
4148
5009
  const runJob = async (file) => {
4149
- const name = basename5(file);
5010
+ const name = basename6(file);
4150
5011
  const abort = new AbortController();
4151
5012
  activeControllers.add(abort);
4152
5013
  log2(`start ${name}`);
@@ -4239,175 +5100,402 @@ async function runWatch(dir, opts) {
4239
5100
 
4240
5101
  // src/utils/ui.ts
4241
5102
  import chalk from "chalk";
4242
- var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
5103
+ import { stripVTControlCharacters } from "util";
5104
+ import { basename as basename7 } from "path";
4243
5105
  var TICK = chalk.green("\u2713");
4244
5106
  var WARN = chalk.yellow("\u25B2");
4245
5107
  var FAIL = chalk.red("\u2717");
4246
- var SHIMMER_SPEED_CELLS_PER_S = 25;
5108
+ var DOT = chalk.dim(" \xB7 ");
5109
+ var STAGES = {
5110
+ preprocess: { doing: "preparing the media", done: "prepared the media" },
5111
+ describe: { doing: "listening for who's there", done: "listened for who's there" },
5112
+ transcribe: { doing: "transcribing", done: "transcribed" },
5113
+ align: {
5114
+ doing: "matching lines to the word times",
5115
+ done: "matched lines to the word times"
5116
+ },
5117
+ speakers: { doing: "telling the voices apart", done: "told the voices apart" },
5118
+ identify: { doing: "naming the speakers", done: "named the speakers" },
5119
+ finalize: { doing: "finishing", done: "finished" },
5120
+ summary: { doing: "writing the summary", done: "wrote the summary" }
5121
+ };
5122
+ var BARS = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";
5123
+ function meter(now, phase, paint) {
5124
+ let bars = "";
5125
+ for (let i = 0; i < 3; i++) {
5126
+ const level = 0.5 + 0.5 * Math.sin(now / 150 + phase + i * 2.1) * Math.sin(now / 420 + i * 1.3);
5127
+ bars += BARS.charAt(Math.round(level * 7));
5128
+ }
5129
+ return paint(bars);
5130
+ }
5131
+ var SHIMMER_CELLS_PER_S = 25;
4247
5132
  var SHIMMER_PADDING = 8;
4248
5133
  var SHIMMER_HALF_WIDTH = 5;
4249
5134
  function shimmer(text, now) {
4250
5135
  const chars = [...text];
4251
5136
  const period = chars.length + SHIMMER_PADDING * 2;
4252
- const pos = now / 1e3 * SHIMMER_SPEED_CELLS_PER_S % period;
5137
+ const crest = now / 1e3 * SHIMMER_CELLS_PER_S % period;
4253
5138
  let out = "";
4254
- let runTier = -1;
4255
5139
  let run2 = "";
5140
+ let runTier = -1;
4256
5141
  const flush = () => {
4257
- if (!run2) return;
4258
- out += runTier === 2 ? chalk.bold.whiteBright(run2) : runTier === 1 ? chalk.white(run2) : chalk.dim(run2);
5142
+ if (run2)
5143
+ out += runTier === 2 ? chalk.bold(run2) : runTier === 1 ? run2 : chalk.dim(run2);
4259
5144
  run2 = "";
4260
5145
  };
4261
- for (let i = 0; i < chars.length; i++) {
4262
- const dist = Math.abs(i + SHIMMER_PADDING - pos);
5146
+ chars.forEach((ch, i) => {
5147
+ const dist = Math.abs(i + SHIMMER_PADDING - crest);
4263
5148
  const intensity = dist >= SHIMMER_HALF_WIDTH ? 0 : 0.5 * (1 + Math.cos(Math.PI * dist / SHIMMER_HALF_WIDTH));
4264
5149
  const tier = intensity >= 0.65 ? 2 : intensity >= 0.2 ? 1 : 0;
4265
5150
  if (tier !== runTier) {
4266
5151
  flush();
4267
5152
  runTier = tier;
4268
5153
  }
4269
- run2 += chars[i];
4270
- }
5154
+ run2 += ch;
5155
+ });
4271
5156
  flush();
4272
5157
  return out;
4273
5158
  }
4274
- var STAGE_LABELS = {
4275
- preprocess: "preparing media",
4276
- describe: "listening for context",
4277
- "llm-transcribe": "transcribing",
4278
- align: "aligning timestamps",
4279
- consistency: "resolving speakers",
4280
- finalize: "finalizing",
4281
- summary: "summarizing"
4282
- };
4283
- function stageLabel(raw) {
4284
- if (raw.startsWith("timestamped")) return raw.replace("timestamped", "timestamps");
4285
- if (raw.startsWith("identify")) return raw.replace("identify", "naming speakers");
4286
- return STAGE_LABELS[raw] ?? raw;
5159
+ function wordmark() {
5160
+ const letters = [..."offmute"];
5161
+ return letters.map((ch, i) => {
5162
+ const t = i / (letters.length - 1);
5163
+ return chalk.bold.rgb(
5164
+ Math.round(20 + 81 * t),
5165
+ Math.round(184 - 21 * t),
5166
+ Math.round(166 - 153 * t)
5167
+ )(ch);
5168
+ }).join("");
4287
5169
  }
5170
+ var breathe = (now, i) => Math.sin(now / 130 - i * 0.8) > 0;
5171
+ var CELLS = {
5172
+ pending: () => chalk.dim("\u25B1"),
5173
+ running: (now, i) => breathe(now, i) ? chalk.cyan("\u25B0") : chalk.cyan("\u25B1"),
5174
+ done: () => chalk.green("\u25B0"),
5175
+ cached: () => chalk.green.dim("\u25B0"),
5176
+ failed: () => chalk.red("\u25B0"),
5177
+ retrying: (now, i) => breathe(now, i) ? chalk.yellow("\u25B0") : chalk.yellow("\u25B1"),
5178
+ recovered: () => chalk.yellow("\u25B0"),
5179
+ unchanged: () => chalk.red("\u25B0")
5180
+ };
5181
+ var MAX_CELLS = 48;
4288
5182
  var active = false;
4289
- var timer = null;
4290
- var frame = 0;
4291
- var stage = null;
4292
- var lineDirty = false;
4293
- function fmtElapsed(ms) {
5183
+ var timer;
5184
+ var liveRows = 0;
5185
+ var lane = null;
5186
+ var asr = null;
5187
+ var clockName = "the timing ASR";
5188
+ var cellsTotal = 0;
5189
+ var cells = /* @__PURE__ */ new Map();
5190
+ var redone = 0;
5191
+ var many = false;
5192
+ var storageShown = "";
5193
+ var restoreConsole = [];
5194
+ function cellWidth(cp) {
5195
+ if (cp >= 768 && cp <= 879 || cp >= 8203 && cp <= 8207 || cp >= 65024 && cp <= 65039) {
5196
+ return 0;
5197
+ }
5198
+ const wide = cp >= 4352 && cp <= 4447 || cp >= 11904 && cp <= 42191 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65072 && cp <= 65103 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791 || cp >= 131072 && cp <= 262141;
5199
+ return wide ? 2 : 1;
5200
+ }
5201
+ function columnsOf(text) {
5202
+ let n = 0;
5203
+ for (const ch of stripVTControlCharacters(text)) n += cellWidth(ch.codePointAt(0));
5204
+ return n;
5205
+ }
5206
+ var ESCAPE_AT = /\x1b\[[0-9;?]*[A-Za-z]/y;
5207
+ function fit(line, max) {
5208
+ if (columnsOf(line) < max) return line;
5209
+ let out = "";
5210
+ let used = 0;
5211
+ for (let i = 0; i < line.length; ) {
5212
+ ESCAPE_AT.lastIndex = i;
5213
+ const escape = ESCAPE_AT.exec(line);
5214
+ if (escape) {
5215
+ out += escape[0];
5216
+ i = ESCAPE_AT.lastIndex;
5217
+ continue;
5218
+ }
5219
+ const ch = String.fromCodePoint(line.codePointAt(i));
5220
+ const w = cellWidth(ch.codePointAt(0));
5221
+ if (used + w > max - 2) break;
5222
+ out += ch;
5223
+ used += w;
5224
+ i += ch.length;
5225
+ }
5226
+ return `${out}\x1B[0m${chalk.dim("\u2026")}`;
5227
+ }
5228
+ var columns = () => Math.max(20, process.stdout.columns || 100);
5229
+ function eraseLive() {
5230
+ if (liveRows === 0) return "";
5231
+ const up = liveRows > 1 ? `\x1B[${liveRows - 1}A` : "";
5232
+ liveRows = 0;
5233
+ return `${up}\r\x1B[0J`;
5234
+ }
5235
+ function draw() {
5236
+ if (!active) return;
5237
+ const lines = liveLines(Date.now()).map((l) => fit(l, columns()));
5238
+ process.stdout.write(eraseLive() + lines.join("\n"));
5239
+ liveRows = lines.length;
5240
+ }
5241
+ function println(text = "") {
5242
+ process.stdout.write(`${eraseLive()}${text}
5243
+ `);
5244
+ draw();
5245
+ }
5246
+ function elapsed(ms) {
4294
5247
  const s = Math.floor(ms / 1e3);
4295
- return s >= 60 ? `${Math.floor(s / 60)}m${(s % 60).toString().padStart(2, "0")}s` : `${s}s`;
5248
+ return s >= 60 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s` : `${s}s`;
5249
+ }
5250
+ function audioLength(sec) {
5251
+ if (sec < 60) return `${Math.round(sec)}s`;
5252
+ if (sec < 3600) return `${Math.round(sec / 60)} min`;
5253
+ return `${Math.floor(sec / 3600)}h ${String(Math.round(sec % 3600 / 60)).padStart(2, "0")}m`;
4296
5254
  }
4297
- function clearLine() {
4298
- if (lineDirty) {
4299
- process.stdout.write("\r\x1B[2K");
4300
- lineDirty = false;
5255
+ var count = (n) => n.toLocaleString("en-US");
5256
+ function languageName(code) {
5257
+ if (!code) return void 0;
5258
+ try {
5259
+ return new Intl.DisplayNames(["en"], { type: "language" }).of(code) ?? code;
5260
+ } catch {
5261
+ return code;
4301
5262
  }
4302
5263
  }
4303
- function drawSpinner() {
4304
- if (!stage) return;
4305
- const now = Date.now();
4306
- const f = chalk.cyan(FRAMES[frame % FRAMES.length]);
4307
- frame++;
4308
- const elapsed = chalk.dim(fmtElapsed(now - stage.startedAt));
4309
- const chunks = stage.chunksTotal !== void 0 ? chalk.dim(` ${stage.chunksDone ?? 0}/${stage.chunksTotal} chunks`) : "";
4310
- const detail = stage.detail ? chalk.dim(` \xB7 ${stage.detail}`) : "";
4311
- const line = `${f} ${shimmer(stage.label, now)}${chunks}${detail} ${elapsed}`;
4312
- process.stdout.write(`\r\x1B[2K${line}`);
4313
- lineDirty = true;
5264
+ function strip(now) {
5265
+ if (cellsTotal === 0 || cellsTotal > MAX_CELLS) return "";
5266
+ let out = "";
5267
+ for (let i = 0; i < cellsTotal; i++) out += CELLS[cells.get(i) ?? "pending"](now, i);
5268
+ return ` ${out}`;
5269
+ }
5270
+ function chunkTally() {
5271
+ const states = [...cells.values()];
5272
+ const working = states.filter((c) => c === "running" || c === "retrying").length;
5273
+ return chalk.dim(
5274
+ ` ${states.length - working}/${cellsTotal} chunk${cellsTotal === 1 ? "" : "s"}${working ? ` \xB7 ${working} running` : ""}`
5275
+ );
4314
5276
  }
4315
- function println(text = "") {
4316
- clearLine();
4317
- process.stdout.write(text + "\n");
4318
- if (active && stage) drawSpinner();
4319
- }
4320
- function completeStage() {
4321
- if (!stage) return;
4322
- const dur = fmtElapsed(Date.now() - stage.startedAt);
4323
- const chunks = stage.chunksTotal !== void 0 ? chalk.dim(` \xB7 ${stage.chunksTotal} chunk${stage.chunksTotal === 1 ? "" : "s"}`) : "";
4324
- const detail = stage.detail ? chalk.dim(` \xB7 ${stage.detail}`) : "";
4325
- clearLine();
4326
- process.stdout.write(`${TICK} ${stage.label}${chunks}${detail} ${chalk.dim(dur)}
4327
- `);
4328
- stage = null;
5277
+ function liveLines(now) {
5278
+ const lines = [];
5279
+ if (lane) {
5280
+ const mid = lane.stage === "transcribe" && cellsTotal > 0 ? `${strip(now)}${chunkTally()}` : lane.status || lane.detail ? chalk.dim(` \xB7 ${lane.status || lane.detail}`) : "";
5281
+ lines.push(
5282
+ `${meter(now, 0, chalk.cyan)} ${shimmer(STAGES[lane.stage].doing, now)}${mid} ${chalk.dim(elapsed(now - lane.startedAt))}`
5283
+ );
5284
+ }
5285
+ if (asr) {
5286
+ lines.push(
5287
+ `${meter(now, 1.7, chalk.magenta)} ${chalk.dim(`timing every word \xB7 ${asr.provider} ${elapsed(now - asr.startedAt)}`)}`
5288
+ );
5289
+ }
5290
+ return lines;
4329
5291
  }
4330
- function startStage(rawName) {
4331
- completeStage();
4332
- stage = { label: stageLabel(rawName), startedAt: Date.now(), detail: "" };
4333
- drawSpinner();
5292
+ function completeLane() {
5293
+ if (!lane) return;
5294
+ const now = Date.now();
5295
+ const { stage, startedAt, detail } = lane;
5296
+ lane = null;
5297
+ let mid = detail ? chalk.dim(` \xB7 ${detail}`) : "";
5298
+ if (stage === "transcribe" && cellsTotal > 0) {
5299
+ mid = `${strip(now)}${chalk.dim(
5300
+ ` ${cellsTotal} chunk${cellsTotal === 1 ? "" : "s"}${redone ? ` \xB7 ${redone} redone in halves` : ""}`
5301
+ )}`;
5302
+ }
5303
+ println(`${TICK} ${STAGES[stage].done}${mid} ${chalk.dim(elapsed(now - startedAt))}`);
5304
+ }
5305
+ var span = (startSec, endSec) => `${compactTime(startSec)}\u2013${compactTime(endSec)}`;
5306
+ function onProgress(e) {
5307
+ if (!active) return;
5308
+ switch (e.type) {
5309
+ case "plan": {
5310
+ completeLane();
5311
+ if (e.asr !== "none") clockName = e.asr;
5312
+ const bits = [
5313
+ `${chalk.bold(audioLength(e.durationSec))} of audio`,
5314
+ chalk.cyan(e.model),
5315
+ e.asr === "none" ? chalk.yellow("the LLM's own timestamps") : `timed by ${e.asr}`,
5316
+ `${chalk.yellow(`~$${e.estimateUsd.toFixed(2)}`)} estimated`
5317
+ ];
5318
+ println(` ${bits.join(DOT)}`);
5319
+ if (e.zeroStorage) {
5320
+ const unasked = e.notAsked.map((p) => p.name).join(", ");
5321
+ const line = ` ${chalk.green("zero storage")}${unasked ? chalk.dim(` \xB7 ${unasked} can't be asked to keep nothing`) : ""}`;
5322
+ if (line !== storageShown) println(line);
5323
+ storageShown = line;
5324
+ }
5325
+ println();
5326
+ return;
5327
+ }
5328
+ case "stage":
5329
+ if (e.state === "failed") {
5330
+ if (lane?.stage === e.stage) {
5331
+ const took = elapsed(Date.now() - lane.startedAt);
5332
+ lane = null;
5333
+ println(`${FAIL} ${STAGES[e.stage].doing} failed ${chalk.dim(took)}`);
5334
+ }
5335
+ return;
5336
+ }
5337
+ completeLane();
5338
+ if (e.state === "cached") {
5339
+ println(`${TICK} ${STAGES[e.stage].done}${chalk.dim(" \xB7 from the cache")}`);
5340
+ return;
5341
+ }
5342
+ lane = {
5343
+ stage: e.stage,
5344
+ startedAt: Date.now(),
5345
+ detail: e.detail ?? "",
5346
+ status: ""
5347
+ };
5348
+ draw();
5349
+ return;
5350
+ case "asr": {
5351
+ if (e.state === "start") {
5352
+ asr = { provider: e.provider, startedAt: Date.now() };
5353
+ draw();
5354
+ return;
5355
+ }
5356
+ const took = asr ? ` ${chalk.dim(elapsed(Date.now() - asr.startedAt))}` : "";
5357
+ asr = null;
5358
+ if (e.state === "failed") {
5359
+ println(
5360
+ `${FAIL} timing every word \xB7 ${e.provider} failed${chalk.dim(" \xB7 the run stops when transcription ends; finished chunks stay cached")}`
5361
+ );
5362
+ return;
5363
+ }
5364
+ const facts = [
5365
+ e.words !== void 0 && `${count(e.words)} words`,
5366
+ e.speakers && `${e.speakers} voice${e.speakers === 1 ? "" : "s"}`,
5367
+ languageName(e.language),
5368
+ e.state === "cached" && "from the cache"
5369
+ ].filter(Boolean);
5370
+ println(
5371
+ `${TICK} timed every word \xB7 ${e.provider}${chalk.dim(facts.map((f) => ` \xB7 ${f}`).join(""))}${took}`
5372
+ );
5373
+ return;
5374
+ }
5375
+ case "chunks":
5376
+ cellsTotal = e.total;
5377
+ cells.clear();
5378
+ redone = 0;
5379
+ draw();
5380
+ return;
5381
+ case "chunk":
5382
+ cells.set(e.index, e.state);
5383
+ if (e.state === "failed") {
5384
+ println(`${FAIL} chunk ${e.index + 1}: ${chalk.red(e.error ?? "failed")}`);
5385
+ }
5386
+ draw();
5387
+ return;
5388
+ case "guard": {
5389
+ const where = span(e.startSec, e.endSec);
5390
+ if (e.state === "retrying") {
5391
+ cells.set(e.index, "retrying");
5392
+ println(
5393
+ ` ${chalk.yellow("\u21BB")} ${where} came back short${chalk.dim(` \xB7 ${count(e.llmWords)} words where ${clockName} heard ${count(e.asrWords)}`)} \xB7 transcribing it again in two halves`
5394
+ );
5395
+ } else if (e.state === "recovered") {
5396
+ cells.set(e.index, "recovered");
5397
+ redone++;
5398
+ println(
5399
+ ` ${TICK} ${where} recovered${chalk.dim(` \xB7 ${count(e.retryWords ?? 0)} words`)}`
5400
+ );
5401
+ } else {
5402
+ cells.set(e.index, "unchanged");
5403
+ println(
5404
+ ` ${WARN} ${where}: the halves did no better${chalk.dim(` \xB7 kept the first attempt; ${clockName}'s words fill its gaps`)}`
5405
+ );
5406
+ }
5407
+ draw();
5408
+ return;
5409
+ }
5410
+ case "names": {
5411
+ const pairs = Object.entries(e.names);
5412
+ if (pairs.length) {
5413
+ println(
5414
+ ` ${chalk.magenta("\u25C6")} ${pairs.map(([id, name]) => `${chalk.dim(`${id} \u2192`)} ${chalk.bold(name)}`).join(DOT)}`
5415
+ );
5416
+ }
5417
+ return;
5418
+ }
5419
+ case "done":
5420
+ completeLane();
5421
+ return;
5422
+ }
4334
5423
  }
4335
5424
  function handleLine(level, msg) {
4336
- if (level === "warn") {
4337
- println(`${WARN} ${chalk.yellow(msg)}`);
4338
- return;
4339
- }
4340
5425
  if (level === "error") {
4341
5426
  println(`${FAIL} ${chalk.red(msg)}`);
4342
5427
  return;
4343
5428
  }
4344
- const stageMatch = msg.match(/^=== (.+) ===$/);
4345
- if (stageMatch) {
4346
- startStage(stageMatch[1]);
5429
+ if (level === "warn") {
5430
+ if (!msg.includes("transcribing it again in two halves")) {
5431
+ println(`${WARN} ${chalk.yellow(msg)}`);
5432
+ }
4347
5433
  return;
4348
5434
  }
4349
- const totalMatch = msg.match(/^(\d+) chunks \(/);
4350
- if (totalMatch && stage) {
4351
- stage.chunksTotal = parseInt(totalMatch[1], 10);
4352
- stage.chunksDone = 0;
5435
+ if (msg.startsWith("description:")) {
5436
+ completeLane();
5437
+ println(fit(chalk.dim(` ${msg.slice(12).trim().replace(/\s+/g, " ")}`), columns()));
4353
5438
  return;
4354
5439
  }
4355
- if (/^\[llm\] chunk \d+ ok|^chunk \d+: cached/.test(msg) && stage?.chunksTotal !== void 0) {
4356
- stage.chunksDone = (stage.chunksDone ?? 0) + 1;
4357
- drawSpinner();
5440
+ if (msg.startsWith("intermediates:")) {
5441
+ println(chalk.dim(` cache ${msg.slice(14).trim().split(" (file://")[0]}`));
4358
5442
  return;
4359
5443
  }
4360
- if (msg.startsWith("estimated cost")) {
4361
- const pretty = msg.replace(
4362
- /^estimated cost (~\$[\d.]+)(.*)$/,
4363
- (_, amt, rest) => `${chalk.bold("estimate")} ${chalk.yellow(amt)}${chalk.dim(rest)}`
4364
- );
4365
- println(` ${pretty}`);
5444
+ if (msg.startsWith("identify:")) {
5445
+ println(` ${chalk.magenta("\u25C6")} ${chalk.dim(msg.slice(9).trim())}`);
4366
5446
  return;
4367
5447
  }
4368
5448
  if (msg.startsWith("receipt:")) {
4369
- completeStage();
4370
- println(` ${chalk.bold("receipt")} ${chalk.yellow(msg.slice(9))}`);
5449
+ completeLane();
5450
+ if (!many) println(`
5451
+ ${chalk.bold("receipt")} ${chalk.yellow(msg.slice(9))}`);
4371
5452
  return;
4372
5453
  }
4373
5454
  if (msg.startsWith(" ") && /\$\d/.test(msg)) {
4374
- println(chalk.dim(` ${msg.trim()}`));
4375
- return;
4376
- }
4377
- if (msg.startsWith("identified ") || msg.startsWith("identify:")) {
4378
- println(` ${chalk.magenta("\u25C6")} ${msg}`);
5455
+ if (!many) println(chalk.dim(` ${msg.trim()}`));
4379
5456
  return;
4380
5457
  }
4381
- if (msg.startsWith("description:")) {
4382
- const text = msg.slice(12).trim().replace(/\s+/g, " ");
4383
- println(
4384
- chalk.dim(` ${text.slice(0, Math.max(40, (process.stdout.columns || 100) - 4))}`)
4385
- );
4386
- return;
4387
- }
4388
- if (msg.startsWith("intermediates:")) {
4389
- const p = msg.slice(14).trim().split(" (file://")[0];
4390
- println(chalk.dim(` cache ${p}`));
4391
- return;
4392
- }
4393
- if (msg.startsWith("outputs written")) {
4394
- return;
4395
- }
4396
- if (stage) {
4397
- stage.detail = msg.replace(/^\[[a-z-]+\]\s*/i, "").replace(/^cache hit \S+$/, "cached").replace(/\.{3}$/, "").slice(0, 60);
4398
- drawSpinner();
5458
+ if (lane?.stage === "preprocess" && msg.startsWith("extracting ")) {
5459
+ lane.status = msg.replace(/ \(.*\)/, "").replace(/\.{3}$/, "");
5460
+ draw();
4399
5461
  }
4400
5462
  }
5463
+ var showCursor = () => process.stdout.write("\x1B[?25h");
5464
+ function stopOnSignal(signal) {
5465
+ process.stdout.write(eraseLive());
5466
+ showCursor();
5467
+ process.stdout.write(
5468
+ `
5469
+ ${WARN} ${chalk.yellow("stopped")}${chalk.dim(" \xB7 what finished is cached; run the same command again to carry on")}
5470
+ `
5471
+ );
5472
+ process.exit(signal === "SIGINT" ? 130 : 143);
5473
+ }
4401
5474
  function configureUi(opts) {
4402
5475
  active = opts.enabled;
5476
+ many = opts.many ?? false;
5477
+ storageShown = "";
4403
5478
  if (!active) return;
4404
5479
  logger.setSink((level, msg) => {
4405
5480
  handleLine(level, msg);
4406
5481
  return true;
4407
5482
  });
4408
- timer = setInterval(() => {
4409
- if (stage) drawSpinner();
4410
- }, 66);
5483
+ for (const name of ["log", "info", "warn", "error"]) {
5484
+ const original = console[name];
5485
+ console[name] = (...args) => {
5486
+ process.stdout.write(eraseLive());
5487
+ original(...args);
5488
+ draw();
5489
+ };
5490
+ restoreConsole.push(() => {
5491
+ console[name] = original;
5492
+ });
5493
+ }
5494
+ process.stdout.write("\x1B[?25l");
5495
+ process.once("exit", showCursor);
5496
+ process.once("SIGINT", stopOnSignal);
5497
+ process.once("SIGTERM", stopOnSignal);
5498
+ timer = setInterval(draw, 80);
4411
5499
  timer.unref();
4412
5500
  }
4413
5501
  function uiActive() {
@@ -4415,40 +5503,78 @@ function uiActive() {
4415
5503
  }
4416
5504
  function finishUi() {
4417
5505
  if (!active) return;
4418
- completeStage();
4419
- clearLine();
4420
- if (timer) clearInterval(timer);
4421
- timer = null;
5506
+ completeLane();
5507
+ asr = null;
5508
+ process.stdout.write(eraseLive());
5509
+ clearInterval(timer);
5510
+ timer = void 0;
5511
+ for (const restore of restoreConsole.splice(0)) restore();
5512
+ process.removeListener("SIGINT", stopOnSignal);
5513
+ process.removeListener("SIGTERM", stopOnSignal);
5514
+ showCursor();
4422
5515
  active = false;
4423
5516
  logger.setSink(null);
4424
5517
  }
4425
- function banner(version, inputName) {
5518
+ function banner(version, title) {
5519
+ if (!active) return;
5520
+ println(
5521
+ `
5522
+ ${wordmark()}${chalk.dim("-v2")} ${chalk.dim(version)} ${chalk.bold(title)}`
5523
+ );
5524
+ }
5525
+ function batchPlan(audioSec, estimateUsd, unreadable) {
5526
+ if (!active) return;
5527
+ println(
5528
+ ` ${chalk.bold(audioLength(audioSec))} of audio${DOT}${chalk.yellow(`~$${estimateUsd.toFixed(2)}`)} estimated${DOT}one file at a time`
5529
+ );
5530
+ for (const name of unreadable) {
5531
+ println(
5532
+ ` ${FAIL} ${name} ${chalk.dim("has no audio offmute can read, so it's left out")}`
5533
+ );
5534
+ }
5535
+ }
5536
+ function fileHeader(index, count2, name) {
4426
5537
  if (!active) return;
5538
+ println(
5539
+ `
5540
+ ${chalk.cyan("\u258C")} ${chalk.bold(name)} ${chalk.dim(`${index} of ${count2}`)}`
5541
+ );
5542
+ }
5543
+ function batchSummary(entries, totals) {
5544
+ const ok2 = entries.filter((e) => !e.error).length;
5545
+ const all = ok2 === entries.length;
5546
+ const head = all ? `${ok2} files transcribed` : `${ok2} of ${entries.length} files transcribed`;
4427
5547
  process.stdout.write(
4428
5548
  `
4429
- ${chalk.bold.cyan("offmute")}${chalk.dim("-v2")} ${chalk.dim(version)} ${chalk.bold(inputName)}
4430
-
5549
+ ${all ? TICK : WARN} ${chalk.bold(head)}${chalk.dim(` \xB7 ${totals}`)}
4431
5550
  `
4432
5551
  );
4433
- }
4434
- function outputsBlock(files, summaryLine) {
4435
- clearLine();
4436
- process.stdout.write("\n");
4437
- for (const f of files) {
4438
- process.stdout.write(` ${chalk.green("\u2192")} ${f}
5552
+ const width = Math.max(...entries.map((e) => columnsOf(e.name)));
5553
+ for (const e of entries) {
5554
+ const name = e.name + " ".repeat(width - columnsOf(e.name));
5555
+ const outcome = e.error ? chalk.red(e.error.split("\n")[0].slice(0, 100)) : chalk.dim(`\u2192 ${(e.outputs ?? []).map((f) => basename7(f)).join(" \xB7 ")}`);
5556
+ process.stdout.write(` ${e.error ? FAIL : TICK} ${name} ${outcome}
4439
5557
  `);
4440
5558
  }
5559
+ }
5560
+ function outputsBlock(files, summaryLine) {
4441
5561
  process.stdout.write(`
4442
- ${chalk.bold(summaryLine)}
5562
+ ${TICK} ${chalk.bold(summaryLine)}
5563
+
4443
5564
  `);
5565
+ for (const f of files) {
5566
+ const slash = f.lastIndexOf("/");
5567
+ process.stdout.write(
5568
+ ` ${chalk.green("\u2192")} ${chalk.dim(f.slice(0, slash + 1))}${chalk.bold(f.slice(slash + 1))}
5569
+ `
5570
+ );
5571
+ }
4444
5572
  }
4445
5573
  function tipsBlock(tips) {
4446
5574
  if (tips.length === 0) return;
4447
5575
  process.stdout.write("\n");
4448
- for (const t of tips) {
4449
- process.stdout.write(chalk.dim(` tip: ${t}
4450
- `));
4451
- }
5576
+ for (const t of tips) process.stdout.write(` ${chalk.cyan("tip")} ${chalk.dim(t)}
5577
+ `);
4452
5578
  }
4453
5579
  function starFooter() {
4454
5580
  process.stdout.write(
@@ -4460,15 +5586,15 @@ function starFooter() {
4460
5586
  );
4461
5587
  }
4462
5588
  function errorBlock(message, hint) {
4463
- clearLine();
4464
- if (timer) clearInterval(timer);
4465
- if (stage) {
5589
+ process.stdout.write(eraseLive());
5590
+ if (lane) {
4466
5591
  process.stderr.write(
4467
- `${FAIL} ${stage.label} ${chalk.dim(fmtElapsed(Date.now() - stage.startedAt))}
5592
+ `${FAIL} ${STAGES[lane.stage].doing} ${chalk.dim(elapsed(Date.now() - lane.startedAt))}
4468
5593
  `
4469
5594
  );
4470
- stage = null;
5595
+ lane = null;
4471
5596
  }
5597
+ asr = null;
4472
5598
  process.stderr.write(`
4473
5599
  ${FAIL} ${chalk.red(message)}
4474
5600
  `);
@@ -4477,15 +5603,30 @@ ${FAIL} ${chalk.red(message)}
4477
5603
  }
4478
5604
 
4479
5605
  // src/commands/first-run.ts
4480
- import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "fs";
4481
- import { join as join4 } from "path";
5606
+ import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "fs";
5607
+ import { join as join6 } from "path";
4482
5608
  import chalk2 from "chalk";
5609
+ var WHATS_NEW = {
5610
+ "0.3.0": "several files in one call: offmute-v2 a.mp4 b.m4a, or a folder (offmute-v2 ~/Recordings), one after another",
5611
+ "0.2.0": `transcribes with ${DEFAULT_TRANSCRIBE_MODEL} (--pro: ${PRO_TRANSCRIBE_MODEL}), asks providers to keep nothing (--no-zero-storage turns that off), and a stopped run picks up where it left off`
5612
+ };
5613
+ function isNewer(a, b) {
5614
+ const [x, y] = [a, b].map((v) => v.split("-")[0].split(".").map(Number));
5615
+ for (let i = 0; i < 3; i++) {
5616
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
5617
+ if (d !== 0) return d > 0;
5618
+ }
5619
+ return false;
5620
+ }
5621
+ function newsSince(last, version) {
5622
+ return Object.entries(WHATS_NEW).filter(([v]) => !isNewer(v, version) && (last ? isNewer(v, last) : v === version)).sort(([a], [b]) => isNewer(a, b) ? -1 : 1);
5623
+ }
4483
5624
  function maybeFirstRunCheck(version) {
4484
5625
  let last = null;
4485
5626
  const dir = statsDir();
4486
- const path = join4(dir, "last-version");
5627
+ const path = join6(dir, "last-version");
4487
5628
  try {
4488
- if (existsSync6(path)) last = readFileSync5(path, "utf-8").trim();
5629
+ if (existsSync7(path)) last = readFileSync5(path, "utf-8").trim();
4489
5630
  } catch {
4490
5631
  }
4491
5632
  if (last === version) return false;
@@ -4502,6 +5643,9 @@ function maybeFirstRunCheck(version) {
4502
5643
  `first run of ${chalk2.reset.bold(version)}${chalk2.dim(" \u2014 checking your setup (offline; `offmute-v2 doctor` pings live)")}`
4503
5644
  )
4504
5645
  );
5646
+ for (const [v, text] of newsSince(last, version)) {
5647
+ lines.push(` ${chalk2.cyan(`new in ${v}`)} ${chalk2.dim(text)}`);
5648
+ }
4505
5649
  lines.push(
4506
5650
  ` ${have(keys.gemini)} GEMINI_API_KEY ${chalk2.dim("transcription \u2014 required")}`
4507
5651
  );
@@ -4531,7 +5675,9 @@ function maybeFirstRunCheck(version) {
4531
5675
  "add ELEVENLABS_API_KEY to try Scribe v2 \u2014 the sharpest speaker separation we've tested on conversational audio"
4532
5676
  );
4533
5677
  if (!keys.deepseek)
4534
- unlocks.push("add DEEPSEEK_API_KEY so speaker naming costs ~$0.003 a run");
5678
+ unlocks.push(
5679
+ "add DEEPSEEK_API_KEY so speaker naming costs ~$0.003 a run (DeepSeek can't be asked to keep nothing)"
5680
+ );
4535
5681
  for (const u of unlocks.slice(0, 2)) lines.push(chalk2.dim(` unlock: ${u}`));
4536
5682
  process.stdout.write(lines.join("\n") + "\n\n");
4537
5683
  return true;
@@ -4540,8 +5686,8 @@ function maybeFirstRunCheck(version) {
4540
5686
  // src/cli.ts
4541
5687
  var packageVersion = "0.0.0";
4542
5688
  try {
4543
- const here = dirname5(fileURLToPath(import.meta.url));
4544
- const pkg = JSON.parse(readFileSync6(join5(here, "..", "package.json"), "utf-8"));
5689
+ const here = dirname6(fileURLToPath(import.meta.url));
5690
+ const pkg = JSON.parse(readFileSync6(join7(here, "..", "package.json"), "utf-8"));
4545
5691
  packageVersion = pkg.version;
4546
5692
  } catch {
4547
5693
  }
@@ -4549,19 +5695,26 @@ var program = new Command();
4549
5695
  program.name("offmute-v2").description(
4550
5696
  "Diarized meeting transcription with multimodal LLMs + timestamped alignment."
4551
5697
  ).version(packageVersion);
4552
- function buildTips(result, opts, input) {
5698
+ var isGeneric = (sp) => !sp.name || /^Speaker [A-Z]$/.test(sp.name);
5699
+ function buildTips(runs, opts, plan) {
4553
5700
  const tips = [];
4554
- const genericSpeakers = result.speakers.filter(
4555
- (sp) => !sp.name || /^Speaker [A-Z]$/.test(sp.name)
4556
- );
4557
- if (genericSpeakers.length > 0 && !opts.speakers) {
5701
+ const unnamed = runs.filter((r) => r.result.speakers.some(isGeneric));
5702
+ if (unnamed.length > 0 && !opts.speakers) {
5703
+ const first = unnamed[0];
5704
+ const generic = first.result.speakers.filter(isGeneric);
5705
+ const retcon = `offmute-v2 rename "${first.input}" "${generic[0].id}=Name"`;
4558
5706
  tips.push(
4559
- `${genericSpeakers.length} speaker(s) stayed generic \u2014 retcon instantly: offmute-v2 rename "${input}" "${genericSpeakers[0].id}=Name", or pass --speakers "Alice,Bob" next time`
5707
+ runs.length === 1 ? `${generic.length} speaker(s) stayed generic \u2014 retcon instantly: ${retcon}, or pass --speakers "Alice,Bob" next time` : `${unnamed.length} of ${runs.length} files kept generic speaker names \u2014 retcon one instantly: ${retcon}`
4560
5708
  );
4561
5709
  }
4562
- if (!opts.model && result.metadata.duration > 1500) {
5710
+ const unasked = plan?.notAsked ?? [];
5711
+ if (unasked.length > 0) {
5712
+ const fixes = [
5713
+ unasked.some((p) => p.role === "timing") && "--timestamped assemblyai",
5714
+ unasked.some((p) => p.role === "text") && "--reasoner gemini-flash-latest --identify single"
5715
+ ].filter(Boolean);
4563
5716
  tips.push(
4564
- "long file on the pro model \u2014 try --model gemini-3.5-flash for ~4\xD7 cheaper and faster (quality holds up well)"
5717
+ `zero storage can't ask ${unasked.map((p) => p.name).join(" or ")} to keep nothing; ${fixes.join(" ")} keeps the whole run on providers it can ask`
4565
5718
  );
4566
5719
  }
4567
5720
  if (!opts.formats && !opts.summary) {
@@ -4585,24 +5738,34 @@ function errorHint(msg) {
4585
5738
  return "network hiccup \u2014 just re-run; everything finished so far is cached";
4586
5739
  if (/Input file not found/.test(msg))
4587
5740
  return "check the path (tab-completion is your friend)";
5741
+ if (/no media files in/.test(msg))
5742
+ return "a folder gives offmute its audio and video files (.mp4, .mov, .m4a, .mp3, .wav\u2026); name other files directly";
5743
+ if (/write over each other's transcript/.test(msg))
5744
+ return "transcribe one of them on its own, or give it another name";
4588
5745
  return void 0;
4589
5746
  }
4590
- async function runTranscribe(input, opts) {
4591
- const passes = opts.passes?.split(",");
5747
+ function filesToTranscribe(paths, outputDir) {
5748
+ const { files, missing, empty } = expandInputs(paths);
5749
+ const problems = [
5750
+ ...missing.length > 0 ? [`Input file not found: ${missing.join(", ")}`] : [],
5751
+ ...empty.map((dir) => `no media files in ${dir}`),
5752
+ ...outputClashes(files, outputDir).map(
5753
+ ([a, b]) => `${a} and ${b} would write over each other's transcript (both are named ${basename8(a, extname3(a))})`
5754
+ )
5755
+ ];
5756
+ if (problems.length > 0) throw new Error(problems.join("\n "));
5757
+ return files;
5758
+ }
5759
+ function pipelineOptions(input, opts, many2) {
4592
5760
  let level = parseInt(opts.level, 10);
4593
5761
  if (opts.speakers && level < 3) level = 3;
4594
- const pretty = process.stdout.isTTY === true && opts.progress && opts.logLevel !== "debug";
4595
- configureUi({ enabled: pretty });
4596
- banner(packageVersion, basename6(input));
4597
- if (pretty) maybeFirstRunCheck(packageVersion);
4598
- const t0 = Date.now();
4599
- const result = await transcribe({
5762
+ return {
4600
5763
  input,
4601
5764
  outputDir: opts.output,
4602
5765
  // undefined → defaults to the input file's directory
4603
- intermediatesDir: opts.intermediates,
5766
+ intermediatesDir: many2 && opts.intermediates ? deriveIntermediatesDir(input, opts.intermediates) : opts.intermediates,
4604
5767
  instructions: opts.instructions,
4605
- passes,
5768
+ passes: opts.passes?.split(","),
4606
5769
  chunkDurationSec: parseInt(opts.chunkSeconds, 10),
4607
5770
  chunkOverlapSec: parseInt(opts.overlapSeconds, 10),
4608
5771
  concurrency: parseInt(opts.concurrency, 10),
@@ -4614,47 +5777,167 @@ async function runTranscribe(input, opts) {
4614
5777
  knownSpeakers: opts.speakers ? opts.speakers.split(",").map((s) => s.trim()).filter(Boolean) : void 0,
4615
5778
  diarizationLevel: level,
4616
5779
  identifyMode: opts.identify,
4617
- model: opts.model,
5780
+ model: opts.pro ? PRO_TRANSCRIBE_MODEL : opts.model,
4618
5781
  reasoner: opts.reasoner,
4619
5782
  timestampedProvider: opts.timestamped,
5783
+ language: opts.language,
5784
+ zeroStorage: opts.zeroStorage,
4620
5785
  force: opts.force,
4621
5786
  onlyChunk: opts.onlyChunk ? parseInt(opts.onlyChunk, 10) : void 0,
4622
5787
  saveIntermediates: opts.saveIntermediates,
4623
5788
  showProgress: opts.progress,
4624
5789
  llmLog: opts.llmLog,
4625
5790
  logLevel: opts.logLevel
4626
- });
4627
- if (uiActive()) {
5791
+ };
5792
+ }
5793
+ async function runFile(options) {
5794
+ let open = true;
5795
+ let plan;
5796
+ let done;
5797
+ try {
5798
+ const result = await transcribe({
5799
+ ...options,
5800
+ onProgress: (e) => {
5801
+ if (!open) return;
5802
+ if (e.type === "plan") plan = e;
5803
+ if (e.type === "done") done = e;
5804
+ onProgress(e);
5805
+ }
5806
+ });
5807
+ return { input: options.input, result, plan, done };
5808
+ } finally {
5809
+ open = false;
5810
+ }
5811
+ }
5812
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
5813
+ function resultLine(run2) {
5814
+ const cost = run2.done?.costUsd !== void 0 ? ` \xB7 ~$${run2.done.costUsd.toFixed(2)}` : "";
5815
+ const wall = run2.done ? ` \xB7 ${formatDuration(Math.round(run2.done.wallMs / 1e3))}` : "";
5816
+ return `${plural(run2.result.segments.length, "segment")} \xB7 ${plural(run2.result.speakers.length, "speaker")} \xB7 ${formatDuration(Math.round(run2.result.metadata.duration))} of audio${cost}${wall}`;
5817
+ }
5818
+ async function runTranscribe(paths, opts) {
5819
+ const files = filesToTranscribe(paths, opts.output);
5820
+ const pretty = process.stdout.isTTY === true && opts.progress && opts.logLevel !== "debug";
5821
+ configureUi({ enabled: pretty, many: files.length > 1 });
5822
+ if (files.length > 1) return runMany(files, opts, pretty);
5823
+ await runOne(files[0], opts, pretty);
5824
+ return 0;
5825
+ }
5826
+ async function runOne(file, opts, pretty) {
5827
+ banner(packageVersion, basename8(file));
5828
+ if (pretty) maybeFirstRunCheck(packageVersion);
5829
+ const t0 = Date.now();
5830
+ const run2 = await runFile(pipelineOptions(file, opts, false));
5831
+ if (pretty) {
4628
5832
  finishUi();
4629
- const base = basename6(input).replace(/\.[^.]+$/, "");
4630
- const outDir = resolve4(opts.output ?? (dirname5(resolve4(input)) || "."));
4631
- const formats = opts.formats ? opts.formats.split(",") : ["md"];
4632
- const files = formats.map((f) => join5(outDir, `${base}.${f.trim()}`));
4633
- if (opts.summary) files.push(join5(outDir, `${base}.summary.md`));
4634
- const cost = result.metadata.cost ? ` \xB7 ~$${result.metadata.cost.actualUsd.toFixed(2)}` : "";
4635
- const wall = result.metadata.wallMs ? ` \xB7 ${formatDuration(Math.round(result.metadata.wallMs / 1e3))}` : "";
4636
- outputsBlock(
4637
- files,
4638
- `${result.segments.length} segments \xB7 ${result.speakers.length} speakers \xB7 ${formatDuration(Math.round(result.metadata.duration))} of audio${cost}${wall}`
5833
+ outputsBlock(run2.done?.outputs ?? [], resultLine(run2));
5834
+ tipsBlock(buildTips([run2], opts, run2.plan));
5835
+ starFooter();
5836
+ process.stdout.write("\n");
5837
+ } else {
5838
+ console.log(`Done. ${run2.result.segments.length} segments.`);
5839
+ }
5840
+ if (opts.notify && Date.now() - t0 > 12e4) {
5841
+ const cost = run2.done?.costUsd !== void 0 ? ` \xB7 ~$${run2.done.costUsd.toFixed(2)}` : "";
5842
+ notify(
5843
+ "offmute-v2",
5844
+ `${basename8(file)} transcribed \u2014 ${run2.result.segments.length} segments${cost}`
4639
5845
  );
4640
- tipsBlock(buildTips(result, opts, input));
5846
+ }
5847
+ }
5848
+ async function audioLengths(files) {
5849
+ const lengths = [];
5850
+ for (let i = 0; i < files.length; i += 8) {
5851
+ const batch = files.slice(i, i + 8).map(
5852
+ (f) => probe(f).then(
5853
+ (p) => p.hasAudio && p.duration > 0 ? p.duration : null,
5854
+ () => null
5855
+ )
5856
+ );
5857
+ lengths.push(...await Promise.all(batch));
5858
+ }
5859
+ return lengths;
5860
+ }
5861
+ async function runMany(files, opts, pretty) {
5862
+ const t0 = Date.now();
5863
+ await preflight(pipelineOptions(files[0], opts, true));
5864
+ const lengths = await audioLengths(files);
5865
+ const unreadable = files.filter((_, i) => lengths[i] === null).map((f) => basename8(f));
5866
+ let estimateUsd = 0;
5867
+ let audioSec = 0;
5868
+ files.forEach((file, i) => {
5869
+ const sec = lengths[i];
5870
+ if (sec == null) return;
5871
+ audioSec += sec;
5872
+ estimateUsd += estimateRun(pipelineOptions(file, opts, true), sec).totalUsd;
5873
+ });
5874
+ banner(packageVersion, `${files.length} files`);
5875
+ if (pretty) maybeFirstRunCheck(packageVersion);
5876
+ batchPlan(audioSec, estimateUsd, unreadable);
5877
+ if (!pretty) {
5878
+ console.log(
5879
+ `${files.length} files \xB7 ${formatDuration(Math.round(audioSec))} of audio \xB7 ~$${estimateUsd.toFixed(2)} estimated${unreadable.length > 0 ? ` \xB7 no audio offmute can read, left out: ${unreadable.join(", ")}` : ""}`
5880
+ );
5881
+ }
5882
+ const entries = [];
5883
+ const transcribed = [];
5884
+ let plan;
5885
+ let spentUsd = 0;
5886
+ let transcribedSec = 0;
5887
+ const runnable = files.length - unreadable.length;
5888
+ let n = 0;
5889
+ for (const [i, file] of files.entries()) {
5890
+ const name = basename8(file);
5891
+ if (lengths[i] == null) {
5892
+ entries.push({ name, error: "has no audio offmute can read" });
5893
+ continue;
5894
+ }
5895
+ n++;
5896
+ if (pretty) fileHeader(n, runnable, name);
5897
+ else console.log(`
5898
+ [${n}/${runnable}] ${file}`);
5899
+ try {
5900
+ const run2 = await runFile(pipelineOptions(file, opts, true));
5901
+ plan ??= run2.plan;
5902
+ spentUsd += run2.done?.costUsd ?? 0;
5903
+ transcribedSec += run2.result.metadata.duration;
5904
+ transcribed.push(run2);
5905
+ entries.push({ name, outputs: run2.done?.outputs ?? [] });
5906
+ if (pretty) outputsBlock(run2.done?.outputs ?? [], resultLine(run2));
5907
+ else console.log(`Done. ${run2.result.segments.length} segments.`);
5908
+ } catch (err) {
5909
+ const msg = err instanceof Error ? err.message : String(err);
5910
+ entries.push({ name, error: msg });
5911
+ if (pretty) errorBlock(msg, errorHint(msg));
5912
+ else console.error(`\u2717 ${msg}`);
5913
+ }
5914
+ }
5915
+ finishUi();
5916
+ const failed = entries.filter((e) => e.error);
5917
+ const totals = `${formatDuration(Math.round(transcribedSec))} of audio \xB7 ~$${spentUsd.toFixed(2)} \xB7 ${formatDuration(Math.round((Date.now() - t0) / 1e3))}`;
5918
+ if (pretty) {
5919
+ batchSummary(entries, totals);
5920
+ if (transcribed.length > 0) tipsBlock(buildTips(transcribed, opts, plan));
4641
5921
  starFooter();
4642
5922
  process.stdout.write("\n");
4643
5923
  } else {
4644
- console.log(`Done. ${result.segments.length} segments.`);
5924
+ console.log(
5925
+ `
5926
+ Done: ${files.length - failed.length} of ${files.length} files transcribed (${totals})${failed.length > 0 ? `; failed: ${failed.map((e) => `${e.name} (${e.error.split("\n")[0]})`).join(", ")}` : ""}`
5927
+ );
4645
5928
  }
4646
5929
  if (opts.notify && Date.now() - t0 > 12e4) {
4647
- const cost = result.metadata.cost ? ` \xB7 ~$${result.metadata.cost.actualUsd.toFixed(2)}` : "";
4648
5930
  notify(
4649
5931
  "offmute-v2",
4650
- `${basename6(input)} transcribed \u2014 ${result.segments.length} segments${cost}`
5932
+ `${files.length - failed.length} of ${files.length} files transcribed${failed.length > 0 ? `, ${failed.length} failed` : ""} \xB7 ~$${spentUsd.toFixed(2)}`
4651
5933
  );
4652
5934
  }
5935
+ return failed.length;
4653
5936
  }
4654
5937
  function addTranscribeOptions(cmd) {
4655
5938
  return cmd.option("-o, --output <dir>", "output directory (default: next to the input file)").option(
4656
5939
  "-i, --intermediates <dir>",
4657
- "intermediates directory (default: auto-derived per input file so caches never collide)"
5940
+ "intermediates directory (default: one per input in the OS temp dir; with several files, one per file inside this folder)"
4658
5941
  ).option("--instructions <text>", "custom instructions for the LLM").option("--passes <list>", "comma-separated passes to run").option("--chunk-seconds <n>", "chunk duration in seconds", "600").option("--overlap-seconds <n>", "chunk overlap in seconds", "60").option("--concurrency <n>", "max concurrent chunk requests", "4").option("--screenshots <n>", "number of keyframes to extract (video)", "6").option("--formats <list>", "output formats: srt,md,txt,html,json (default: md)").option(
4659
5942
  "--md-style <style>",
4660
5943
  "markdown layout: merged (paragraphs) | turns",
@@ -4674,19 +5957,33 @@ function addTranscribeOptions(cmd) {
4674
5957
  "--identify <mode>",
4675
5958
  "speaker naming: dual (two reasoners, default) | single",
4676
5959
  "dual"
4677
- ).option("--model <name>", "override transcription model").option("--reasoner <name>", "override text-reasoner model (default deepseek-chat)").option(
5960
+ ).option("--model <name>", "override transcription model (default gemini-4-hydrogen)").addOption(
5961
+ new Option(
5962
+ "--pro",
5963
+ `transcribe with the pro model, ${PRO_TRANSCRIBE_MODEL}: keeps a little more speech, about 1.7\xD7 slower`
5964
+ ).conflicts("model")
5965
+ ).option("--reasoner <name>", "override text-reasoner model (default deepseek-chat)").option(
4678
5966
  "--timestamped <provider>",
4679
5967
  "timestamped provider (assemblyai|elevenlabs|whisper-groq|none)"
4680
- ).option("--force", "force reprocess cached chunk outputs", false).option("--only-chunk <n>", "process only a specific chunk index (debug)").option("--save-intermediates", "save intermediates (default true)", true).option("--no-progress", "hide progress output").option(
5968
+ ).option(
5969
+ "--language <code>",
5970
+ "spoken language for the timing ASR, e.g. ko, ml, hi (default: the ASR detects one)"
5971
+ ).option("--force", "force reprocess cached chunk outputs", false).option(
5972
+ "--no-zero-storage",
5973
+ "let providers keep requests under their own retention (by default offmute asks Gemini and AssemblyAI to keep nothing)"
5974
+ ).option("--only-chunk <n>", "process only a specific chunk index (debug)").option("--save-intermediates", "save intermediates (default true)", true).option("--no-progress", "hide progress output").option(
4681
5975
  "--no-llm-log",
4682
5976
  "disable per-call LLM logging to <intermediates>/llm-calls.jsonl"
4683
5977
  ).option("--no-notify", "skip the OS notification after long runs").option("--log-level <level>", "debug | info | warn | error", "info");
4684
5978
  }
4685
5979
  addTranscribeOptions(
4686
- program.command("transcribe <input>", { isDefault: true }).description("transcribe a video/audio file (default command)")
4687
- ).action(async (input, opts) => {
5980
+ program.command("transcribe <inputs...>", { isDefault: true }).description(
5981
+ "transcribe one or more video/audio files, or every one in a folder, one after another (default command)"
5982
+ )
5983
+ ).action(async (inputs, opts) => {
4688
5984
  try {
4689
- await runTranscribe(input, opts);
5985
+ const failed = await runTranscribe(inputs, opts);
5986
+ if (failed > 0) process.stdout.write("", () => process.exit(1));
4690
5987
  } catch (err) {
4691
5988
  const msg = err instanceof Error ? err.message : String(err);
4692
5989
  if (uiActive()) {
@@ -4710,7 +6007,15 @@ program.command("stats").description("lifetime stats: hours processed, character
4710
6007
  program.command("watch <dir>").description("daemon mode: watch a folder, transcribe media files as they appear").option("--match <exts>", "comma-separated extensions to watch (default: common media)").option("--jobs <n>", "max concurrent transcription jobs", "1").option("--no-backlog", "skip files already in the folder at startup").option("-o, --output <dir>", "write transcripts here (default: next to each input)").option("--formats <list>", "output formats: srt,md,txt,html,json (default: md)").option("--md-style <style>", "markdown layout: merged | turns", "merged").option("--summary", "also write a summary per file", false).option("--instructions <text>", "custom instructions for the LLM").option(
4711
6008
  "--speakers <names>",
4712
6009
  "known speaker names, comma-separated (implies --level 3)"
4713
- ).option("--level <1|2|3>", "diarization level", "3").option("--identify <mode>", "speaker naming: dual | single", "dual").option("--model <name>", "override transcription model").option("--reasoner <name>", "override text-reasoner model").option("--timestamped <provider>", "assemblyai|elevenlabs|whisper-groq|none").action(
6010
+ ).option("--level <1|2|3>", "diarization level", "3").option("--identify <mode>", "speaker naming: dual | single", "dual").option("--model <name>", "override transcription model (default gemini-4-hydrogen)").addOption(
6011
+ new Option(
6012
+ "--pro",
6013
+ `transcribe with the pro model, ${PRO_TRANSCRIBE_MODEL}`
6014
+ ).conflicts("model")
6015
+ ).option("--reasoner <name>", "override text-reasoner model").option("--timestamped <provider>", "assemblyai|elevenlabs|whisper-groq|none").option("--language <code>", "spoken language for the timing ASR, e.g. ko, ml, hi").option(
6016
+ "--no-zero-storage",
6017
+ "let providers keep requests under their own retention (by default offmute asks them to keep nothing)"
6018
+ ).action(
4714
6019
  async (dir, opts) => {
4715
6020
  let level = parseInt(opts.level, 10);
4716
6021
  if (opts.speakers && level < 3) level = 3;
@@ -4727,9 +6032,11 @@ program.command("watch <dir>").description("daemon mode: watch a folder, transcr
4727
6032
  knownSpeakers: opts.speakers ? opts.speakers.split(",").map((s) => s.trim()).filter(Boolean) : void 0,
4728
6033
  diarizationLevel: level,
4729
6034
  identifyMode: opts.identify,
4730
- model: opts.model,
6035
+ model: opts.pro ? PRO_TRANSCRIBE_MODEL : opts.model,
4731
6036
  reasoner: opts.reasoner,
4732
- timestampedProvider: opts.timestamped
6037
+ timestampedProvider: opts.timestamped,
6038
+ language: opts.language,
6039
+ zeroStorage: opts.zeroStorage
4733
6040
  }
4734
6041
  });
4735
6042
  }