scrybe 1.6.0

Local-first meeting recording, transcription, and notes for macOS.
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
// Copyright 2026 Mathews Tom
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//     https://www.apache.org/licenses/LICENSE-2.0

//! `scrybe record <title>` — ergonomic entry point.
//!
//! Resolves capture source, Whisper model, and LLM kind from config
//! defaults plus platform probes (see `scrybe_core::record_defaults`).
//! On macOS, `mic+system` with the Core Audio Tap backend auto-launches
//! via the `.app` bundle so `TCC`'s `AudioCapture` grant binds to the
//! responsible process. `ScreenCaptureKit` runs directly.
//!
//! Power users and CI scripts that need explicit flag control should
//! use `scrybe rec` instead; this command is the happy path for
//! end-user recording with sensible defaults.

#[cfg(all(target_os = "macos", feature = "system-capture-mac"))]
use std::path::Path;
use std::path::PathBuf;

#[cfg(all(target_os = "macos", feature = "system-capture-mac"))]
use anyhow::Context;
use anyhow::Result;
use clap::Args as ClapArgs;
use scrybe_core::config::{
    Config, RECORD_LLM_OPENAI_COMPAT, RECORD_SOURCE_MIC, RECORD_SOURCE_MIC_SYSTEM,
    RECORD_SYSTEM_BACKEND_SCK, RECORD_SYSTEM_BACKEND_TAP,
};
#[cfg(feature = "system-capture-mac")]
use scrybe_core::config::{RECORD_LLM_STUB, RECORD_SOURCE_SYNTHETIC};
use scrybe_core::record_defaults;
#[cfg(feature = "cli-shell")]
use tokio::runtime::Runtime;

use crate::commands::rec::{self, CaptureSourceArg, LlmBackendArg};
use crate::runtime::load_or_default_config;

#[derive(ClapArgs, Clone, Debug)]
pub struct Args {
    /// Session title (positional). Becomes the folder-name component
    /// and the transcript heading.
    pub title: String,

    /// Override the capture source. Defaults to `mic+system` on macOS
    /// and `mic` elsewhere; honors explicit `[record].source` from
    /// config when set to a non-synthetic value.
    #[arg(long, value_enum)]
    pub source: Option<CaptureSourceArg>,

    /// Exact macOS Core Audio input-device UID from `scrybe devices`.
    #[arg(long)]
    pub input_device: Option<String>,

    /// Override the `sck` or `tap` system-audio adapter.
    #[arg(long, value_enum)]
    pub system_backend: Option<super::rec::SystemBackendArg>,

    /// Override the Whisper model path. Defaults to the platform model when
    /// one exists. Conflicts with `--sherpa-model`.
    #[arg(long, conflicts_with = "sherpa_model")]
    pub whisper_model: Option<PathBuf>,

    /// Directory containing the pinned streaming Zipformer Sherpa-ONNX model.
    /// Conflicts with `--whisper-model`.
    #[arg(long, conflicts_with = "whisper_model")]
    pub sherpa_model: Option<PathBuf>,

    /// Override the LLM backend. Defaults to `openai-compat` if a
    /// local Ollama is reachable at `127.0.0.1:11434`, else `stub`.
    #[arg(long, value_enum)]
    pub llm: Option<LlmBackendArg>,

    /// Storage root override.
    #[arg(long)]
    pub root: Option<PathBuf>,

    /// Show native recording indicators and accept tray, floating-window,
    /// and global-hotkey stop requests.
    #[arg(long, default_value_t = false)]
    pub shell: bool,

    /// Force in-process invocation; do not auto-launch via the .app
    /// bundle for Core Audio Tap. Used for unit tests and direct
    /// troubleshooting of the legacy Tap path.
    #[arg(long, hide = true)]
    pub no_bundle: bool,
}

/// Dispatch the ergonomic record subcommand.
///
/// # Errors
///
/// Surfaces config-load errors, bundle-launch errors, and the
/// underlying `rec::run` errors verbatim.
pub async fn run(args: Args) -> Result<()> {
    let cfg = load_or_default_config()?;
    let resolved = resolve(&cfg, &args);

    if should_use_bundle(&resolved, &args) {
        #[cfg(all(target_os = "macos", feature = "system-capture-mac"))]
        {
            let bundle = crate::macos_bundle::find_existing_bundle()
                .context("no scrybe.app bundle found; install one or pass `--no-bundle`")?;
            let session_root = effective_session_root(&cfg, args.root.as_deref());
            let rec_argv = build_rec_argv(&resolved, false);
            return crate::bundle_launcher::launch_via_bundle(&bundle, &rec_argv, &session_root)
                .await;
        }
        #[cfg(not(all(target_os = "macos", feature = "system-capture-mac")))]
        {
            anyhow::bail!(
                "bundle auto-launch requires the `system-capture-mac` feature (needed for \
                 the mic+system TCC grant); rebuild with `--features system-capture-mac` or \
                 pass `--no-bundle`"
            );
        }
    }
    rec::run(resolved.into_rec_args(false)).await
}

/// Dispatch the ergonomic record subcommand through the native shell.
///
/// # Errors
///
/// Surfaces config, bundle-launch, native-surface, and recording errors.
#[cfg(feature = "cli-shell")]
pub fn run_with_shell(args: &Args, runtime: &Runtime) -> Result<()> {
    let cfg = load_or_default_config()?;
    let resolved = resolve(&cfg, args);

    #[cfg(all(target_os = "macos", feature = "system-capture-mac"))]
    if should_use_bundle(&resolved, args) {
        let bundle = crate::macos_bundle::find_existing_bundle()
            .context("no scrybe.app bundle found; install one or pass `--no-bundle`")?;
        let session_root = effective_session_root(&cfg, args.root.as_deref());
        let rec_argv = build_rec_argv(&resolved, true);
        return runtime.block_on(crate::bundle_launcher::launch_via_bundle(
            &bundle,
            &rec_argv,
            &session_root,
        ));
    }

    crate::shell::run_record_with_shell(resolved.into_rec_args(true), runtime)
}

#[derive(Clone, Debug)]
struct Resolved {
    title: String,
    source: CaptureSourceArg,
    system_backend: super::rec::SystemBackendArg,
    whisper_model: Option<PathBuf>,
    sherpa_model: Option<PathBuf>,
    llm: LlmBackendArg,
    root: Option<PathBuf>,
    input_device: Option<String>,
}

impl Resolved {
    fn into_rec_args(self, shell: bool) -> rec::Args {
        rec::Args {
            title: Some(self.title),
            root: self.root,
            yes: true,
            consent: None,
            synthetic_secs: 5,
            source: Some(self.source),
            system_backend: Some(self.system_backend),
            whisper_model: self.whisper_model,
            sherpa_model: self.sherpa_model,
            llm: Some(self.llm),
            input_device: self.input_device,
            shell,
        }
    }
}

fn resolve(cfg: &Config, args: &Args) -> Resolved {
    let source = args.source.unwrap_or_else(|| {
        capture_source_arg_from_str(record_defaults::ergonomic_source(&cfg.record))
    });
    let system_backend = args.system_backend.unwrap_or_else(|| {
        system_backend_arg_from_str(
            cfg.record
                .validated_system_backend()
                .unwrap_or(RECORD_SYSTEM_BACKEND_SCK),
        )
    });
    let sherpa_model = args.sherpa_model.clone();
    let whisper_model = sherpa_model.as_ref().map_or_else(
        || {
            args.whisper_model
                .clone()
                .or_else(|| record_defaults::ergonomic_whisper_model(&cfg.record, &cfg.stt))
        },
        |_| None,
    );
    let llm = args
        .llm
        .unwrap_or_else(|| llm_backend_arg_from_str(record_defaults::ergonomic_llm(&cfg.record)));
    Resolved {
        title: args.title.clone(),
        source,
        system_backend,
        whisper_model,
        sherpa_model,
        llm,
        input_device: args.input_device.clone(),
        root: args.root.clone(),
    }
}

// Calls `current_exe` when the macOS system-capture feature is enabled.
#[allow(clippy::missing_const_for_fn)]
fn should_use_bundle(resolved: &Resolved, args: &Args) -> bool {
    if args.no_bundle || !cfg!(target_os = "macos") {
        return false;
    }
    let uses_tap = matches!(resolved.source, CaptureSourceArg::MicSystem)
        && matches!(resolved.system_backend, super::rec::SystemBackendArg::Tap);
    if !uses_tap {
        return false;
    }
    #[cfg(all(target_os = "macos", feature = "system-capture-mac"))]
    {
        !crate::macos_bundle::already_inside_bundle()
    }
    #[cfg(not(all(target_os = "macos", feature = "system-capture-mac")))]
    {
        false
    }
}

#[cfg(all(target_os = "macos", feature = "system-capture-mac"))]
fn effective_session_root(cfg: &Config, override_root: Option<&Path>) -> PathBuf {
    if let Some(root) = override_root {
        return crate::runtime::expand_root(root);
    }
    crate::runtime::expand_root(Path::new(&cfg.storage.root))
}

#[cfg(feature = "system-capture-mac")]
fn build_rec_argv(resolved: &Resolved, shell: bool) -> Vec<String> {
    let mut argv = vec!["--title".to_string(), resolved.title.clone()];
    argv.push("--source".to_string());
    argv.push(capture_source_arg_to_str(resolved.source).to_string());
    argv.push("--llm".to_string());
    argv.push(llm_backend_arg_to_str(resolved.llm).to_string());
    if let Some(model) = &resolved.whisper_model {
        argv.push("--whisper-model".to_string());
        argv.push(model.to_string_lossy().into_owned());
    }
    if let Some(model) = &resolved.sherpa_model {
        argv.push("--sherpa-model".to_string());
        argv.push(model.to_string_lossy().into_owned());
    }
    argv.push("--system-backend".to_string());
    argv.push(system_backend_arg_to_str(resolved.system_backend).to_string());
    if let Some(input_device) = &resolved.input_device {
        argv.push("--input-device".to_string());
        argv.push(input_device.clone());
    }
    if let Some(root) = &resolved.root {
        argv.push("--root".to_string());
        argv.push(root.to_string_lossy().into_owned());
    }
    argv.push("--yes".to_string());
    if shell {
        argv.push("--shell".to_string());
    }
    argv
}

fn capture_source_arg_from_str(s: &str) -> CaptureSourceArg {
    match s {
        RECORD_SOURCE_MIC => CaptureSourceArg::Mic,
        RECORD_SOURCE_MIC_SYSTEM => CaptureSourceArg::MicSystem,
        _ => CaptureSourceArg::Synthetic,
    }
}

fn system_backend_arg_from_str(s: &str) -> super::rec::SystemBackendArg {
    match s {
        RECORD_SYSTEM_BACKEND_TAP => super::rec::SystemBackendArg::Tap,
        _ => super::rec::SystemBackendArg::Sck,
    }
}

#[cfg(feature = "system-capture-mac")]
const fn system_backend_arg_to_str(arg: super::rec::SystemBackendArg) -> &'static str {
    match arg {
        super::rec::SystemBackendArg::Sck => RECORD_SYSTEM_BACKEND_SCK,
        super::rec::SystemBackendArg::Tap => RECORD_SYSTEM_BACKEND_TAP,
    }
}

#[cfg(feature = "system-capture-mac")]
const fn capture_source_arg_to_str(arg: CaptureSourceArg) -> &'static str {
    match arg {
        CaptureSourceArg::Synthetic => RECORD_SOURCE_SYNTHETIC,
        CaptureSourceArg::Mic => RECORD_SOURCE_MIC,
        CaptureSourceArg::MicSystem => RECORD_SOURCE_MIC_SYSTEM,
    }
}

fn llm_backend_arg_from_str(s: &str) -> LlmBackendArg {
    if s == RECORD_LLM_OPENAI_COMPAT {
        LlmBackendArg::OpenAiCompat
    } else {
        LlmBackendArg::Stub
    }
}

#[cfg(feature = "system-capture-mac")]
const fn llm_backend_arg_to_str(arg: LlmBackendArg) -> &'static str {
    match arg {
        LlmBackendArg::Stub => RECORD_LLM_STUB,
        LlmBackendArg::OpenAiCompat => RECORD_LLM_OPENAI_COMPAT,
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use scrybe_core::config::Config;

    fn args_with_title(title: &str) -> Args {
        Args {
            title: title.to_string(),
            source: None,
            input_device: None,
            system_backend: None,
            whisper_model: None,
            sherpa_model: None,
            llm: None,
            root: None,
            shell: false,
            no_bundle: false,
        }
    }

    #[test]
    fn test_resolve_uses_explicit_overrides_when_provided() {
        let cfg = Config::default();
        let mut args = args_with_title("explicit");
        args.source = Some(CaptureSourceArg::Mic);
        args.llm = Some(LlmBackendArg::Stub);
        args.whisper_model = Some(PathBuf::from("/explicit/model.bin"));
        let resolved = resolve(&cfg, &args);
        assert_eq!(resolved.source, CaptureSourceArg::Mic);
        assert_eq!(resolved.llm, LlmBackendArg::Stub);
        assert_eq!(
            resolved.whisper_model,
            Some(PathBuf::from("/explicit/model.bin"))
        );
        assert_eq!(resolved.title, "explicit");
    }

    #[test]
    fn test_resolve_explicit_sherpa_model_suppresses_whisper_default() {
        let mut cfg = Config::default();
        cfg.record.whisper_model = Some(PathBuf::from("/configured/whisper.bin"));
        let mut args = args_with_title("sherpa");
        args.sherpa_model = Some(PathBuf::from("/explicit/sherpa"));

        let resolved = resolve(&cfg, &args);

        assert_eq!(
            resolved.sherpa_model,
            Some(PathBuf::from("/explicit/sherpa"))
        );
        assert_eq!(resolved.whisper_model, None);
    }

    #[test]
    fn test_should_use_bundle_returns_false_when_no_bundle_set() {
        let resolved = Resolved {
            title: "t".into(),
            source: CaptureSourceArg::MicSystem,
            system_backend: super::rec::SystemBackendArg::Sck,
            whisper_model: None,
            sherpa_model: None,
            llm: LlmBackendArg::Stub,
            root: None,
            input_device: None,
        };
        let mut args = args_with_title("t");
        args.no_bundle = true;
        assert!(!should_use_bundle(&resolved, &args));
    }

    #[test]
    fn test_should_use_bundle_returns_false_for_non_system_source() {
        let resolved = Resolved {
            title: "t".into(),
            source: CaptureSourceArg::Mic,
            system_backend: super::rec::SystemBackendArg::Sck,
            whisper_model: None,
            sherpa_model: None,
            llm: LlmBackendArg::Stub,
            root: None,
            input_device: None,
        };
        let args = args_with_title("t");
        assert!(!should_use_bundle(&resolved, &args));
    }

    #[cfg(feature = "system-capture-mac")]
    #[test]
    fn test_capture_source_arg_round_trip_via_strings() {
        for arg in [
            CaptureSourceArg::Synthetic,
            CaptureSourceArg::Mic,
            CaptureSourceArg::MicSystem,
        ] {
            let s = capture_source_arg_to_str(arg);
            assert_eq!(capture_source_arg_from_str(s), arg);
        }
    }

    #[cfg(feature = "system-capture-mac")]
    #[test]
    fn test_llm_backend_arg_round_trip_via_strings() {
        for arg in [LlmBackendArg::Stub, LlmBackendArg::OpenAiCompat] {
            let s = llm_backend_arg_to_str(arg);
            assert_eq!(llm_backend_arg_from_str(s), arg);
        }
    }

    #[cfg(feature = "system-capture-mac")]
    #[test]
    fn test_build_rec_argv_emits_required_flags_in_canonical_order() {
        let resolved = Resolved {
            title: "client-call".into(),
            source: CaptureSourceArg::MicSystem,
            system_backend: super::rec::SystemBackendArg::Sck,
            whisper_model: Some(PathBuf::from("/m.bin")),
            sherpa_model: None,
            llm: LlmBackendArg::OpenAiCompat,
            root: None,
            input_device: None,
        };
        let argv = build_rec_argv(&resolved, false);
        assert_eq!(argv[0], "--title");
        assert_eq!(argv[1], "client-call");
        assert!(argv.iter().any(|a| a == "--source"));
        assert!(argv.iter().any(|a| a == "mic+system"));
        assert!(argv.iter().any(|a| a == "--llm"));
        assert!(argv.iter().any(|a| a == "openai-compat"));
        assert!(argv.iter().any(|a| a == "--whisper-model"));
        assert!(argv.iter().any(|a| a == "/m.bin"));
        assert!(argv.iter().any(|a| a == "--yes"));
        assert!(!argv.iter().any(|arg| arg == "--shell"));
        assert!(build_rec_argv(&resolved, true)
            .iter()
            .any(|arg| arg == "--shell"));
    }
}