1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Semantic errors and exit codes for the agent contract.
//!
//! Exit numbers are the machine-readable contract. Stderr prose is locale-only.
use std::process::ExitCode;
/// Failures that terminate a one-shot invocation.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// No audio source was named on argv, on stdin, or by the active marker.
/// Exits 64.
#[error("no audio input provided")]
NoInput,
/// Argv was rejected before any work started: exits 2 with the parser text.
#[error("usage: {0}")]
Usage(String),
/// The named audio path does not exist or cannot be reached. Exits 66.
#[error("input not found: {path}")]
InputNotFound {
/// The path that could not be opened, as the caller wrote it.
path: String,
},
/// The container opened but its samples could not be turned into PCM.
/// Exits 65.
#[error("audio decode failed: {0}")]
AudioDecode(#[source] anyhow::Error),
/// The container is one this build never handles. Exits 65.
#[error("unsupported audio format: {format}")]
UnsupportedFormat {
/// The container that was detected or declared, lowercased.
format: String,
},
/// The declared container is supported, but the bytes are not that.
///
/// Distinct from `UnsupportedFormat`, which used to answer both cases and
/// so told the operator that a listed format was unlisted.
#[error("declared format {format} does not match the input bytes")]
FormatMismatch {
/// The container the caller declared with `--input-format`.
format: String,
},
/// The helper ran over a video input but produced no usable audio track.
/// Exits 65.
#[error("video extraction failed: {path}")]
VideoExtractionFailed {
/// The video the helper was pointed at.
path: String,
},
/// A helper binary is needed for this input but none is configured.
/// Exits 69.
#[error("helper not configured")]
HelperMissing,
/// The configured helper ran and exited non-zero. Exits 69.
#[error("helper failed: {0}")]
HelperFailed(String),
/// No CUDA toolkit with `nvcc` was found on the host. Exits 69.
#[error("cuda toolkit with nvcc missing")]
ToolkitMissing,
/// No NVIDIA GPU or driver is visible to this process. Exits 70.
#[error("nvidia gpu missing")]
GpuMissing,
/// The model needs more device memory than the GPU has free. Exits 70.
#[error("vram insufficient: need {need_bytes} have {have_bytes}")]
VramInsufficient {
/// Device memory the run requires, in bytes.
need_bytes: u64,
/// Device memory reported free at the moment of the check, in bytes.
have_bytes: u64,
},
/// The driver answered, but without a free-memory figure to check against.
/// Exits 70.
#[error("free vram could not be measured")]
VramUnknown,
/// Host resident memory crossed the configured cap mid-run. Exits 70.
#[error("process memory cap exceeded")]
MemoryCap,
/// The requested model is absent from the catalog or the cache. Exits 78.
#[error("model not found: {name}")]
ModelNotFound {
/// The catalog name the caller asked for.
name: String,
},
/// The cached file is the expected size but hashes to something else, which
/// is the case that suggests tampering. Exits 78.
#[error("model digest mismatch: {name}")]
ModelDigestMismatch {
/// The catalog name whose bytes failed verification.
name: String,
},
/// Size disagreed with the catalog, so no digest was ever computed.
///
/// Kept apart from a digest mismatch because the two mean different things
/// to the operator: a wrong size is usually a stale catalog row or a
/// truncated download, while a right size with a wrong digest is the one
/// that suggests the bytes were tampered with.
#[error("model size mismatch: {name} expected {expected} bytes, found {found}")]
ModelSizeMismatch {
/// The catalog name whose file was measured.
name: String,
/// Byte length the catalog row promises.
expected: u64,
/// Byte length actually found on disk.
found: u64,
},
/// Fetching the model from its origin failed. Exits 69 and is the only
/// failure this product marks retryable.
#[error("model download failed: {0}")]
ModelDownload(#[source] anyhow::Error),
/// The catalog points at a non-https origin, which is refused before any
/// byte is fetched. Exits 78.
#[error("insecure catalog origin: {url}")]
InsecureOrigin {
/// The origin that was refused.
url: String,
},
/// The whisper engine loaded but the transcription itself failed. Exits 70.
#[error("whisper inference failed: {0}")]
WhisperInference(String),
/// This binary was built without the CUDA engine, so no run is possible.
/// Exits 70.
#[error("native engine not compiled")]
EngineUnavailable,
/// The run passed the wall-clock budget and was cut short. Exits 124.
#[error("timeout exceeded")]
Timeout,
/// SIGINT arrived and the run stopped on request. Exits 130.
#[error("interrupted")]
Interrupted,
/// SIGTERM arrived and the run was stopped by the supervisor. Exits 143.
#[error("terminated")]
Terminated,
/// The consumer closed stdout before the output finished. Exits 141.
#[error("broken pipe")]
BrokenPipe,
/// A filesystem or descriptor operation failed. Exits 74.
#[error("io error: {0}")]
Io(#[from] std::io::Error),
/// The stored configuration is unreadable or holds a rejected value.
/// Exits 78.
#[error("configuration error: {0}")]
Config(String),
/// The input is longer than the configured `max-duration`. Exits 78.
#[error("duration exceeds max-duration")]
DurationCap,
/// The requested device name is not one this host exposes. Exits 78.
#[error("unknown device: {0}")]
UnknownDevice(String),
/// `--offline` forbids the download the missing model would need. Exits 78.
#[error("offline and model is missing: {name}")]
OfflineMissingModel {
/// The catalog name that would have had to be fetched.
name: String,
},
/// A destructive verb was invoked without `--yes`. Exits 78.
#[error("confirmation required: pass --yes")]
NeedsYes,
}
impl Error {
/// Sysexits-style code the agent branches on.
pub fn exit_code(&self) -> u8 {
match self {
Self::Usage(_) => 2,
Self::NoInput => 64,
Self::AudioDecode(_)
| Self::UnsupportedFormat { .. }
| Self::FormatMismatch { .. }
| Self::VideoExtractionFailed { .. } => 65,
Self::InputNotFound { .. } => 66,
Self::HelperMissing
| Self::HelperFailed(_)
| Self::ToolkitMissing
| Self::ModelDownload(_) => 69,
Self::GpuMissing
| Self::VramInsufficient { .. }
| Self::VramUnknown
| Self::MemoryCap
| Self::WhisperInference(_)
| Self::EngineUnavailable => 70,
Self::Io(_) => 74,
Self::Config(_)
| Self::ModelNotFound { .. }
| Self::ModelDigestMismatch { .. }
| Self::ModelSizeMismatch { .. }
| Self::InsecureOrigin { .. }
| Self::DurationCap
| Self::UnknownDevice(_)
| Self::OfflineMissingModel { .. }
| Self::NeedsYes => 78,
Self::Timeout => 124,
Self::Interrupted => 130,
Self::BrokenPipe => 141,
Self::Terminated => 143,
}
}
/// Process exit wrapper.
pub fn to_exit_code(&self) -> ExitCode {
ExitCode::from(self.exit_code())
}
/// Stable English category for the error envelope.
pub fn category(&self) -> &'static str {
match self {
// `NeedsYes` exits 78, which the contract defines as config, not
// the 2 it defines as usage. Labelling it "usage" while exiting 78
// gave an agent two answers to the same question.
Self::Usage(_) | Self::NoInput => "usage",
Self::InputNotFound { .. } => "input",
Self::AudioDecode(_)
| Self::UnsupportedFormat { .. }
| Self::FormatMismatch { .. }
| Self::VideoExtractionFailed { .. } => "data",
Self::HelperMissing
| Self::HelperFailed(_)
| Self::ToolkitMissing
| Self::ModelDownload(_) => "service",
Self::GpuMissing
| Self::VramInsufficient { .. }
| Self::VramUnknown
| Self::MemoryCap
| Self::WhisperInference(_)
| Self::EngineUnavailable => "resource",
Self::Config(_)
| Self::ModelNotFound { .. }
| Self::ModelDigestMismatch { .. }
| Self::ModelSizeMismatch { .. }
| Self::InsecureOrigin { .. }
| Self::DurationCap
| Self::UnknownDevice(_)
| Self::OfflineMissingModel { .. }
| Self::NeedsYes => "config",
Self::Timeout => "timeout",
Self::Interrupted | Self::Terminated | Self::BrokenPipe => "signal",
Self::Io(_) => "io",
}
}
/// Only transient download failures retry.
pub fn retryable(&self) -> bool {
matches!(self, Self::ModelDownload(_))
}
/// Whether a second decoder could plausibly answer this failure.
///
/// The external helper answers exactly one question — "I cannot read these
/// bytes" — and it answers it by spawning a process that reads the file
/// again. Every other failure is a verdict on the invocation rather than on
/// the container, and retrying one buys a second decode to reach the same
/// answer at twice the cost.
///
/// Measured on a twenty minute wav under a 20 MiB cap: the decode hit the
/// cap, the retry launched the helper anyway, and peak RSS across the
/// process tree went from under the ceiling to 64 MiB. The guard that
/// exists to protect the host was breached by the rescue path itself.
///
/// This lives on the error rather than at the call sites because both the
/// transcription route and `inspect` ask the same question, and a rule
/// copied into two places is a rule that will disagree with itself.
pub fn is_decode_fault(&self) -> bool {
matches!(
self,
Self::AudioDecode(_) | Self::UnsupportedFormat { .. } | Self::FormatMismatch { .. }
)
}
/// Hint for the next agent action.
pub fn hint(&self) -> Option<&'static str> {
match self {
Self::NoInput => Some("pass --file PATH, --stdin, or --use-active"),
// No `--json`: stdout is always JSON, so the flag does not exist.
// The hint used to name it, which made every usage error advise a
// command that produced the same usage error — an agent that
// follows its hints loops. A hint that cannot be run is worse than
// no hint, because it looks actionable.
Self::Usage(_) => Some("run whisper-nvidia-cli commands"),
Self::InputNotFound { .. } => Some("check the file path"),
Self::AudioDecode(_) => Some("use a listed audio format or configure helper"),
Self::UnsupportedFormat { .. } => {
Some("supported: ogg mp3 wav flac plus video with helper")
}
Self::FormatMismatch { .. } => {
Some("drop --input-format and let the container be detected")
}
Self::VideoExtractionFailed { .. } | Self::HelperMissing => {
Some("config set helper /absolute/path")
}
Self::ToolkitMissing => Some("install the CUDA toolkit with nvcc"),
Self::GpuMissing => Some("attach an NVIDIA GPU and driver"),
Self::VramInsufficient { .. } => Some("use --model small or lower concurrency"),
Self::VramUnknown => Some("check the driver: nvidia-smi did not report free memory"),
Self::ModelNotFound { .. } => Some("run models list then models download NAME"),
Self::ModelDigestMismatch { .. } => Some("delete the file and download again"),
Self::ModelSizeMismatch { .. } => {
Some("the catalog row may be stale, or the download was truncated")
}
Self::InsecureOrigin { .. } => Some("catalog origin must be https"),
Self::EngineUnavailable => Some("rebuild with --features cuda"),
Self::OfflineMissingModel { .. } => Some("download the model before --offline"),
Self::NeedsYes => Some("repeat the verb with --yes"),
Self::DurationCap => Some("config set max-duration SECONDS"),
// Everything below reached the caller as `hint: null` under a
// catch-all arm. FR-041 says a failure carries "código categoria
// dica e id", and the arm quietly exempted twelve variants from the
// last of those — including `ModelDownload`, the only retryable
// failure the product has, where knowing what to do next matters
// most. The catch-all is gone on purpose: a new variant now fails
// to compile until someone decides what its hint should be, which
// is the only way this list stays complete.
Self::HelperFailed(_) => Some("check the helper path with doctor"),
Self::MemoryCap => Some("raise --max-memory or lower --concurrency"),
Self::ModelDownload(_) => {
Some("retry, or check the network and the origin with doctor")
}
Self::WhisperInference(_) => Some("retry with --beam 1, or a smaller model"),
Self::UnknownDevice(_) => Some("run doctor to list the devices this host has"),
Self::Timeout => Some("raise --timeout, or use a smaller model"),
Self::Interrupted => Some("the run stopped on request: nothing was left behind"),
Self::Terminated => Some("the run was terminated: nothing was left behind"),
Self::BrokenPipe => Some("the consumer closed stdout before the output ended"),
Self::Io(_) => {
Some("check permissions and free space on the config and cache directories")
}
Self::Config(_) => Some("run config path, then check that file"),
}
}
/// Localised stderr hint key for this failure.
///
/// The JSON contract stays English; only the prose a human reads is
/// translated, which is what keeps FR-055 and FR-026 from conflicting.
///
/// The match is exhaustive on purpose. It used to name five variants and
/// send the other twenty-six through a `_ => None` arm, so `--lang pt-BR`
/// answered in Portuguese for five failures and said nothing at all for the
/// rest: the translation layer existed but almost nothing was wired into
/// it. With the catch-all gone, a new variant fails to compile until
/// someone decides what its stderr prose should be.
///
/// The return type stays `Option` because the call sites branch on it, and
/// because a future variant may legitimately carry no prose; every variant
/// that exists today answers `Some`.
pub fn i18n_key(&self) -> Option<&'static str> {
match self {
Self::NoInput => Some("no_input"),
Self::Usage(_) => Some("usage_invalid"),
Self::InputNotFound { .. } => Some("input_not_found"),
Self::AudioDecode(_) => Some("audio_decode"),
Self::UnsupportedFormat { .. } => Some("unsupported_format"),
Self::FormatMismatch { .. } => Some("format_mismatch"),
Self::VideoExtractionFailed { .. } => Some("video_extraction_failed"),
Self::HelperMissing => Some("helper_missing"),
Self::HelperFailed(_) => Some("helper_failed"),
Self::ToolkitMissing => Some("kit_missing"),
Self::GpuMissing => Some("gpu_missing"),
Self::VramInsufficient { .. } => Some("vram_insufficient"),
Self::VramUnknown => Some("vram_unknown"),
Self::MemoryCap => Some("memory_cap"),
Self::ModelNotFound { .. } => Some("hint_download"),
Self::ModelDigestMismatch { .. } => Some("model_digest_mismatch"),
Self::ModelSizeMismatch { .. } => Some("model_size_mismatch"),
Self::ModelDownload(_) => Some("model_download"),
Self::InsecureOrigin { .. } => Some("insecure_origin"),
Self::OfflineMissingModel { .. } => Some("offline_missing_model"),
Self::WhisperInference(_) => Some("whisper_inference"),
Self::EngineUnavailable => Some("engine_unavailable"),
Self::Timeout => Some("timeout_exceeded"),
Self::Interrupted => Some("interrupted"),
Self::Terminated => Some("terminated"),
Self::BrokenPipe => Some("broken_pipe"),
Self::Io(_) => Some("io_error"),
Self::Config(_) => Some("config_error"),
Self::DurationCap => Some("duration_cap"),
Self::UnknownDevice(_) => Some("unknown_device"),
Self::NeedsYes => Some("need_yes"),
}
}
/// JSON error envelope. Keys stay English.
///
/// `target` carries the argv slot the failing verb was aimed at. It is
/// `None` for verbs that take no target, and both keys are then omitted
/// rather than emitted as nulls, so a consumer can distinguish "this verb
/// has no target" from "the target was not resolved".
pub fn to_json(
&self,
correlation_id: &str,
target: Option<TargetRef<'_>>,
) -> serde_json::Value {
let mut value = serde_json::json!({
"schema_version": env!("CARGO_PKG_VERSION"),
"error": true,
"ok": false,
"code": self.exit_code(),
"message": self.to_string(),
"category": self.category(),
"retryable": self.retryable(),
"hint": self.hint(),
"correlation_id": correlation_id,
});
if let Some(t) = target {
if let Some(map) = value.as_object_mut() {
map.insert("target_resolved".into(), t.resolved.into());
map.insert("target_source".into(), t.source.into());
}
}
value
}
}
/// The argv target a failing verb was aimed at.
///
/// Borrowed rather than owned because the envelope is built once, at the exit
/// boundary, from values the parsed CLI already holds.
#[derive(Debug, Clone, Copy)]
pub struct TargetRef<'a> {
/// The resolved target, as the agent named it.
pub resolved: &'a str,
/// Where the target came from: `argv`, `stdin`, or `active_marker`.
pub source: &'a str,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_file_is_66() {
let err = Error::InputNotFound { path: "x".into() };
assert_eq!(err.exit_code(), 66);
assert_eq!(err.category(), "input");
}
#[test]
fn gpu_is_70() {
assert_eq!(Error::GpuMissing.exit_code(), 70);
assert_eq!(Error::EngineUnavailable.exit_code(), 70);
}
#[test]
fn toolkit_is_69() {
assert_eq!(Error::ToolkitMissing.exit_code(), 69);
}
#[test]
fn only_download_retries() {
assert!(Error::ModelDownload(anyhow::anyhow!("x")).retryable());
assert!(!Error::AudioDecode(anyhow::anyhow!("x")).retryable());
}
/// Every variant names a key, and every key resolves to prose in both
/// locales.
///
/// The list is written out rather than derived so that a new variant breaks
/// this test the same way it breaks the `match`: someone has to decide what
/// the operator should read before the variant can ship.
#[test]
fn every_variant_has_prose_in_both_locales() {
use crate::i18n::{tr, UiLang};
let all = [
Error::NoInput,
Error::Usage("x".into()),
Error::InputNotFound { path: "x".into() },
Error::AudioDecode(anyhow::anyhow!("x")),
Error::UnsupportedFormat { format: "x".into() },
Error::FormatMismatch { format: "x".into() },
Error::VideoExtractionFailed { path: "x".into() },
Error::HelperMissing,
Error::HelperFailed("x".into()),
Error::ToolkitMissing,
Error::GpuMissing,
Error::VramInsufficient {
need_bytes: 1,
have_bytes: 0,
},
Error::VramUnknown,
Error::MemoryCap,
Error::ModelNotFound { name: "x".into() },
Error::ModelDigestMismatch { name: "x".into() },
Error::ModelSizeMismatch {
name: "x".into(),
expected: 1,
found: 0,
},
Error::ModelDownload(anyhow::anyhow!("x")),
Error::InsecureOrigin { url: "x".into() },
Error::OfflineMissingModel { name: "x".into() },
Error::WhisperInference("x".into()),
Error::EngineUnavailable,
Error::Timeout,
Error::Interrupted,
Error::Terminated,
Error::BrokenPipe,
Error::Io(std::io::Error::other("x")),
Error::Config("x".into()),
Error::DurationCap,
Error::UnknownDevice("x".into()),
Error::NeedsYes,
];
assert_eq!(all.len(), 31, "every variant must appear in this list");
for err in &all {
let key = err
.i18n_key()
.unwrap_or_else(|| panic!("{err} carries no i18n key"));
for lang in [UiLang::En, UiLang::PtBr] {
// `tr` echoes the key when no message exists, so a key that
// comes back unchanged is a key missing from that `.ftl`.
assert_ne!(tr(lang, key), key, "{} is missing `{key}`", lang.tag());
}
}
}
}