Skip to main content

whisper_nvidia_cli/
lib.rs

1//! `whisper-nvidia-cli` — one-shot local NVIDIA speech-to-text for agents.
2//!
3//! The process is born, executes one verb, prints compact JSON, and dies.
4//! Logs stay on stderr. Product environment variables are ignored.
5
6pub mod audio;
7pub mod catalog;
8pub mod cli;
9pub mod commands;
10pub mod config;
11pub mod engine;
12pub mod error;
13pub mod gpu;
14pub mod i18n;
15pub mod media_helper;
16pub mod model;
17pub mod output;
18pub mod paths;
19pub mod schema;
20pub mod signal;
21pub mod surface;
22pub mod transcribe;
23pub mod verbs;
24
25// libc signal restore is the only unsafe call and lives in signal.rs
26// behind an explicit allow on that function.
27
28use std::io::Write;
29use std::process::ExitCode;
30
31use clap::{CommandFactory, Parser};
32use tracing::level_filters::LevelFilter;
33
34use crate::cli::{Cli, Commands};
35use crate::commands::Ctx;
36use crate::error::Error;
37use crate::i18n::UiLang;
38use crate::paths::AppPaths;
39
40/// Removes every tracked temporary on the way out, whichever way that is.
41///
42/// `cleanup_temps` used to be reachable only from the forced-exit path, so it
43/// ran when a signal arrived and never when a verb simply failed. Each callsite
44/// paired `register_temp` with a `release_temp` placed AFTER the work, which
45/// means any early return between the two left the directory on disk. FR-039
46/// asks for no residue without qualifying how the run ended, so tying the
47/// cleanup to one exit route could only ever satisfy part of it.
48///
49/// A destructor covers every route the type system knows about — `?`, an early
50/// `return`, or a panic that unwinds — which is why this is a guard and not a
51/// call placed at the end of `run`.
52struct TempGuard;
53
54impl Drop for TempGuard {
55    fn drop(&mut self) {
56        signal::cleanup_temps();
57    }
58}
59
60/// Parse argv, run one verb, die with a semantic exit code.
61pub fn run() -> ExitCode {
62    signal::reset_sigpipe();
63    signal::install_handlers();
64    // Held for the whole invocation: dropped last, after every verb returned.
65    let _temps = TempGuard;
66
67    let cli = match Cli::try_parse() {
68        Ok(c) => c,
69        Err(e) => {
70            // Help and version are a successful request for information,
71            // not an argv fault, and they must not land on stdout.
72            let informational = matches!(
73                e.kind(),
74                clap::error::ErrorKind::DisplayHelp
75                    | clap::error::ErrorKind::DisplayVersion
76                    | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
77            );
78            let rendered = e.render().to_string();
79            let _ = std::io::stderr().write_all(rendered.as_bytes());
80            if informational {
81                return ExitCode::SUCCESS;
82            }
83            // An argv fault caught by clap is still an argv fault, and the
84            // contract says every failure reaches stdout as an envelope. A
85            // value rejected here used to leave stdout empty while a value
86            // rejected one layer deeper produced JSON, so the same class of
87            // mistake had two different shapes depending on who caught it.
88            //
89            // The rendered help stays on stderr for a human; the envelope
90            // carries the first line, which is the diagnosis without the
91            // usage block.
92            let summary = rendered
93                .lines()
94                .find(|l| !l.trim().is_empty())
95                .unwrap_or("invalid arguments")
96                .trim_start_matches("error: ")
97                .to_string();
98            let err = Error::Usage(summary);
99            // No target: argv did not parse, so no slot was ever resolved.
100            let _ = output::write_error(
101                &err,
102                &commands::new_correlation_id(),
103                &surface::Surface::default(),
104                None,
105            );
106            return err.to_exit_code();
107        }
108    };
109
110    let correlation_id = commands::new_correlation_id();
111    let surface = cli.surface();
112
113    let ui = match UiLang::resolve(cli.lang.as_deref()) {
114        Ok(l) => l,
115        Err(err) => return fail(&err, &correlation_id, &surface, None),
116    };
117
118    if cli.print_schema {
119        let paths = match AppPaths::resolve(cli.config_dir.as_deref(), cli.cache_dir.as_deref()) {
120            Ok(p) => p,
121            Err(err) => return fail(&err, &correlation_id, &surface, None),
122        };
123        let store = match commands::load_store(&paths) {
124            Ok(s) => s,
125            Err(err) => return fail(&err, &correlation_id, &surface, None),
126        };
127        init_tracing(cli.quiet, cli.verbose, Some(&store));
128        let mut ctx = Ctx {
129            paths: &paths,
130            store,
131            surface: &surface,
132            correlation_id: &correlation_id,
133            ui,
134            no_input: cli.no_input,
135            offline: cli.offline,
136            timeout: cli.timeout,
137            error_reported: false,
138        };
139        return match commands::dispatch(Commands::Schema { name: None }, &mut ctx) {
140            Ok(()) => ExitCode::SUCCESS,
141            Err(err) => fail(&err, &correlation_id, &surface, None),
142        };
143    }
144
145    let Some(command) = cli.command else {
146        let mut buf = Vec::new();
147        let _ = Cli::command().write_help(&mut buf);
148        let _ = std::io::stderr().write_all(&buf);
149        return ExitCode::from(2);
150    };
151
152    // Completions emit a script, not JSON.
153    if matches!(command, Commands::Completions { .. }) {
154        init_tracing(cli.quiet, cli.verbose, None);
155        return match commands::dispatch(
156            command,
157            &mut Ctx {
158                paths: &AppPaths {
159                    config_dir: std::path::PathBuf::from("."),
160                    cache_dir: std::path::PathBuf::from("."),
161                    state_dir: std::path::PathBuf::from("."),
162                },
163                store: config::Store::default(),
164                surface: &surface,
165                correlation_id: &correlation_id,
166                ui,
167                no_input: cli.no_input,
168                offline: cli.offline,
169                timeout: cli.timeout,
170                error_reported: false,
171            },
172        ) {
173            Ok(()) => ExitCode::SUCCESS,
174            Err(err) => fail(&err, &correlation_id, &surface, None),
175        };
176    }
177
178    // Resolve the argv target once, before `command` is moved into dispatch,
179    // so every failure below this line echoes the slot it was aimed at. A
180    // caller that fired several named targets can then tell which one failed
181    // instead of getting a bare exit code.
182    let designated = command.target();
183    let target = designated
184        .as_ref()
185        .map(|(resolved, source)| error::TargetRef { resolved, source });
186
187    let paths = match AppPaths::resolve(cli.config_dir.as_deref(), cli.cache_dir.as_deref()) {
188        Ok(p) => p,
189        Err(err) => return fail(&err, &correlation_id, &surface, target),
190    };
191    if let Err(err) = paths.ensure() {
192        return fail(&err, &correlation_id, &surface, target);
193    }
194    let store = match commands::load_store(&paths) {
195        Ok(s) => s,
196        Err(err) => return fail(&err, &correlation_id, &surface, target),
197    };
198    init_tracing(cli.quiet, cli.verbose, Some(&store));
199    // Published before dispatch, because the reduction that reads it runs deep
200    // inside the recursive walk over the envelope.
201    surface::publish_content_keys(
202        store
203            .effective()
204            .content_keys
205            .or(config::Store::seeds().content_keys)
206            .unwrap_or_default(),
207    );
208    let ui = match UiLang::resolve(cli.lang.as_deref().or(store.locale.as_deref())) {
209        Ok(l) => l,
210        Err(err) => return fail(&err, &correlation_id, &surface, target),
211    };
212
213    let mut ctx = Ctx {
214        paths: &paths,
215        store,
216        surface: &surface,
217        correlation_id: &correlation_id,
218        ui,
219        no_input: cli.no_input,
220        offline: cli.offline,
221        timeout: cli.timeout,
222        error_reported: false,
223    };
224
225    match commands::dispatch(command, &mut ctx) {
226        Ok(()) => ExitCode::SUCCESS,
227        // A verb that already wrote the envelope for this failure only owes the
228        // exit code. Writing it again put an error after the NDJSON summary,
229        // where an agent reading the last line expects the tally.
230        Err(err) if ctx.error_reported => {
231            if !cli.quiet {
232                if let Some(key) = err.i18n_key() {
233                    eprintln!("{}", i18n::tr(ui, key));
234                }
235            }
236            err.to_exit_code()
237        }
238        Err(err) => fail_localised(&err, &correlation_id, &surface, ui, cli.quiet, target),
239    }
240}
241
242fn fail(
243    err: &Error,
244    correlation_id: &str,
245    surface: &surface::Surface,
246    target: Option<error::TargetRef<'_>>,
247) -> ExitCode {
248    let _ = output::write_error(err, correlation_id, surface, target);
249    err.to_exit_code()
250}
251
252/// Emit the machine envelope on stdout and the localised hint on stderr.
253fn fail_localised(
254    err: &Error,
255    correlation_id: &str,
256    surface: &surface::Surface,
257    ui: UiLang,
258    quiet: bool,
259    target: Option<error::TargetRef<'_>>,
260) -> ExitCode {
261    if !quiet {
262        if let Some(key) = err.i18n_key() {
263            eprintln!("{}", i18n::tr(ui, key));
264        }
265    }
266    fail(err, correlation_id, surface, target)
267}
268
269/// Install the stderr subscriber at the level the flags ask for.
270///
271/// `--quiet` is `OFF`, not `ERROR`. Mapping it to `ERROR` reads as "still show
272/// me errors", but the events at that level are not this product's: the decode
273/// libraries log there too, so `-q` on an undecodable file still printed
274/// `ERROR symphonia_core::probe: probe reach EOF at 54 bytes.` — a line in a
275/// foreign format, in one language regardless of `--lang`, from a crate the
276/// caller never invoked. The flag says "Suppress stderr", and a caller who asks
277/// for silence and gets a stack trace from a dependency has been told nothing
278/// useful and given something to filter.
279///
280/// This product's own prose does not travel through tracing: it is written with
281/// `eprintln!` behind an explicit `if !quiet`, so turning the subscriber off
282/// silences the dependencies without silencing the localised hints.
283///
284/// `store` carries the persisted `log-level`, `log-format` and `log-timestamps`
285/// keys. The flags still win: `-q` and `-v` are what the operator typed for
286/// THIS run, while the configuration is the standing preference. Without the
287/// keys there was no standing preference at all, and the JSON writer that
288/// `tracing-subscriber` was already compiled with could never be reached.
289///
290/// This runs after the store is loaded rather than before, because a default
291/// that lives in the configuration cannot be honoured by a subscriber that was
292/// installed before the configuration was read. Nothing of this product's own
293/// prose is lost by the move: it never travelled through tracing.
294fn init_tracing(quiet: bool, verbose: u8, store: Option<&config::Store>) {
295    let configured = store
296        .map(config::Store::effective)
297        .and_then(|e| e.log_level.or(config::Store::seeds().log_level))
298        .and_then(|name| match name.as_str() {
299            "off" => Some(LevelFilter::OFF),
300            "error" => Some(LevelFilter::ERROR),
301            "warn" => Some(LevelFilter::WARN),
302            "info" => Some(LevelFilter::INFO),
303            "debug" => Some(LevelFilter::DEBUG),
304            "trace" => Some(LevelFilter::TRACE),
305            _ => None,
306        });
307    let level = if quiet {
308        LevelFilter::OFF
309    } else {
310        match verbose {
311            0 => configured.unwrap_or(LevelFilter::WARN),
312            1 => LevelFilter::INFO,
313            2 => LevelFilter::DEBUG,
314            _ => LevelFilter::TRACE,
315        }
316    };
317    let effective = store.map(config::Store::effective);
318    let seeds = config::Store::seeds();
319    let json = effective
320        .as_ref()
321        .and_then(|e| e.log_format.clone())
322        .or(seeds.log_format)
323        .is_some_and(|f| f == "json");
324    let timestamps = effective
325        .as_ref()
326        .and_then(|e| e.log_timestamps)
327        .or(seeds.log_timestamps)
328        .unwrap_or(false);
329
330    // Four shapes, and the builder types differ, so each one is built whole.
331    // `without_time` and `.json()` both change the type, which is why this is
332    // a match on two booleans rather than a chain of conditional calls.
333    let _ = match (json, timestamps) {
334        (true, true) => tracing_subscriber::fmt()
335            .json()
336            .with_max_level(level)
337            .with_writer(std::io::stderr)
338            .with_ansi(false)
339            .try_init(),
340        (true, false) => tracing_subscriber::fmt()
341            .json()
342            .with_max_level(level)
343            .with_writer(std::io::stderr)
344            .with_ansi(false)
345            .without_time()
346            .try_init(),
347        (false, true) => tracing_subscriber::fmt()
348            .with_max_level(level)
349            .with_writer(std::io::stderr)
350            .with_ansi(false)
351            .try_init(),
352        (false, false) => tracing_subscriber::fmt()
353            .with_max_level(level)
354            .with_writer(std::io::stderr)
355            .with_ansi(false)
356            .without_time()
357            .try_init(),
358    };
359}