Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(cli): add subcommands, JSON output, and agent help
Richie McIlroyb8f0ac63f706
diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.tomlindex 0b3fdf924..aa5b8365c 100644--- a/apps/cli/Cargo.toml+++ b/apps/cli/Cargo.toml@@ -5,28 +5,38 @@ edition = "2024"[dependencies]clap = { version = "4.5.23", features = ["derive"] }-cap-utils = { path = "../../crates/utils" }+clap_complete = "4.5.38"cap-project = { path = "../../crates/project" }-cap-rendering = { path = "../../crates/rendering" }-cap-editor = { path = "../../crates/editor" }-cap-media = { path = "../../crates/media" }-cap-flags = { path = "../../crates/flags" }cap-recording = { path = "../../crates/recording" }cap-export = { path = "../../crates/export" }cap-camera = { path = "../../crates/camera" }+cap-cli-install = { path = "../../crates/cli-install" }scap-targets = { path = "../../crates/scap-targets" }serde = { workspace = true }serde_json = "1.0.133"-tokio.workspace = true+tokio = { workspace = true, features = ["signal"] }+tokio-util = { version = "0.7", features = ["io"] }uuid = { version = "1.11.1", features = ["v4"] }ffmpeg = { workspace = true }+reqwest = { version = "0.12.24", features = ["json", "stream"] }+kameo = "0.17.2"+flume = { workspace = true }+futures = { workspace = true }+dirs = "6.0.0"+image = "0.25.2"tracing.workspace = truetracing-subscriber = "0.3.19"-flume.workspace = trueworkspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }+[target.'cfg(unix)'.dependencies]+libc = "0.2"+[target.'cfg(target_os = "macos")'.dependencies]cidre = { workspace = true }+scap-screencapturekit = { path = "../../crates/scap-screencapturekit" }++[dev-dependencies]+tempfile = "3"[lints]workspace = truediff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rsindex 7ddded8b0..6a44257ce 100644--- a/apps/cli/src/main.rs+++ b/apps/cli/src/main.rs@@ -1,37 +1,130 @@+mod credentials;+mod doctor;+mod export;+mod guide;+mod project;mod record;+mod recordings;+mod screenshot;+mod session;+mod targets;+mod upload;use std::{io::{Write, stderr, stdout},path::PathBuf,- sync::{Arc, Mutex},};-use cap_export::{ExporterBase, make_cursor_only_project};-use cap_project::RecordingMeta;-use cap_project::XY;-use clap::{Args, Parser, Subcommand};+use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};+use export::{Export, ExportPreview};use record::RecordStart;-use serde::{Deserialize, Serialize};-use serde_json::json;-use tracing::*;+use serde::Serialize;use tracing_subscriber::{filter::LevelFilter, layer::SubscriberExt, util::SubscriberInitExt};const TOKIO_WORKER_THREAD_STACK_SIZE: usize = 16 * 1024 * 1024;+/// Long-form help epilogue. Agents read `cap --help` before doing anything, so the conventions they+/// need to drive the CLI correctly (JSON on stdout, env vars, the canonical workflow) live here.+const AGENT_HELP: &str = "\+OUTPUT+ Pass --json (global) for machine-readable JSON on stdout; stderr stays human-readable.+ stdout is the authoritative result. On failure the process exits non-zero and, in --json+ mode, prints a final object/event containing an \"error\" field. Streaming commands (record,+ export) emit newline-delimited JSON (NDJSON) events. Run `cap guide --json` for the full+ machine-readable capability + schema manifest.++AUTH+ `cap upload` authenticates automatically by reusing the login Cap Desktop already stored — no+ key to copy when you are signed in there. Check with `cap auth status --json`. For headless/CI,+ set CAP_API_KEY to a Cap auth key (Settings) to override.++ENVIRONMENT+ CAP_API_KEY Overrides auth for `cap upload` (Cap auth key from Settings); optional when+ signed into Cap Desktop.+ CAP_SERVER_URL Cap server base URL; defaults to Cap Desktop's server, else https://cap.so.+ CAP_NO_MODIFY_PATH Set to skip editing shell profiles during `cap desktop install-cli`.++TYPICAL AGENT WORKFLOW+ cap doctor --json # verify permissions & capture readiness+ cap targets --json # discover screens/windows/cameras/mics+ cap record start --screen <id> --json # start in background -> {recordingId, pid, path}+ cap record stop --id <recordingId> --json # finalize the .cap recording+ cap project validate <path.cap> --json # confirm the recording is complete+ cap export <path.cap> --output out.mp4 --json+ cap upload out.mp4 --json # get a shareable link (needs CAP_API_KEY)";+#[derive(Parser)]+#[command(+ name = "cap",+ version,+ about = "Cap screen recording from the command line",+ long_about = "Cap screen recording from the command line.\n\nDesigned to be driven by automation and AI agents: add --json to any command for \+machine-readable output. See the sections below for the JSON convention, environment variables, and \+the canonical record -> export -> upload workflow.",+ after_help = AGENT_HELP,+ after_long_help = AGENT_HELP+)]struct Cli {+ #[arg(long, value_enum, global = true, default_value_t = CliLogLevel::Warn)]+ log_level: CliLogLevel,+ /// Emit machine-readable JSON to stdout (overrides each command's --format)+ #[arg(long, global = true)]+ json: bool,#[command(subcommand)]command: Commands,}+#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]+enum CliLogLevel {+ Trace,+ Debug,+ Info,+ Warn,+ Error,+}++impl CliLogLevel {+ fn level_filter(self) -> LevelFilter {+ match self {+ Self::Trace => LevelFilter::TRACE,+ Self::Debug => LevelFilter::DEBUG,+ Self::Info => LevelFilter::INFO,+ Self::Warn => LevelFilter::WARN,+ Self::Error => LevelFilter::ERROR,+ }+ }+}+#[derive(Subcommand)]enum Commands {- /// Export a '.cap' project to an mp4 file+ /// Export a '.cap' project to a video fileExport(Export),/// Render an export preview frameExportPreview(ExportPreview),+ /// Inspect or validate a '.cap' project+ Project(ProjectArgs),/// Start a recording or list available capture targets and devicesRecord(RecordArgs),+ /// Capture a still screenshot of a screen or window+ Screenshot(screenshot::Screenshot),+ /// List recordings discovered in the desktop library (or a custom directory)+ Recordings(RecordingsArgs),+ /// Upload a recording or video file and get a shareable link+ Upload(upload::UploadArgs),+ /// Show how `cap upload` will authenticate (env key or Cap Desktop login)+ Auth(AuthArgs),+ /// List available capture targets and devices+ Targets(TargetsArgs),+ /// Report CLI environment and capture-readiness diagnostics+ Doctor(FormatArgs),+ /// Print CLI version and execution context+ Version(FormatArgs),+ /// Inspect or manage the desktop-installed `cap` shim+ Desktop(DesktopArgs),+ /// Print the machine-readable capability & JSON-schema manifest for agents+ Guide(FormatArgs),+ /// Generate shell completion scripts+ Completions(CompletionsArgs),}impl Commands {@@ -42,7 +135,6 @@ impl Commands {#[derive(Args)]#[command(args_conflicts_with_subcommands = true)]-// #[command(flatten_help = true)]struct RecordArgs {#[command(subcommand)]command: Option<RecordCommands>,@@ -53,30 +145,174 @@ struct RecordArgs {#[derive(Subcommand)]enum RecordCommands {+ /// Start a recording (use --detach to run in the background and stop later)+ Start(RecordStart),+ /// Stop a detached recording started with `cap record start --detach`+ Stop(record::RecordStopArgs),+ /// List active and recent detached recording sessions+ Status(FormatArgs),+ /// Internal: background worker for detached recordings (do not call directly)+ #[command(name = "__session-run", hide = true)]+ SessionRun(record::SessionRunArgs),/// List screens available for capturing- Screens,+ Screens(FormatArgs),/// List windows available for capturing- Windows,+ Windows(FormatArgs),/// List cameras available for capturing- Cameras,- // Mics,+ Cameras(FormatArgs),+ /// List microphones available for capturing+ Mics(FormatArgs),}-fn main() -> Result<(), String> {- // let (layer, handle) = tracing_subscriber::reload::Layer::new(None::<DynLoggingLayer>);+#[derive(Args)]+#[command(args_conflicts_with_subcommands = true)]+struct TargetsArgs {+ #[command(subcommand)]+ command: Option<TargetCommands>,+ #[arg(long, value_enum, default_value_t = OutputFormat::Text)]+ format: OutputFormat,+}- let level_filter = if cfg!(debug_assertions) {- LevelFilter::TRACE- } else {- LevelFilter::WARN- };+#[derive(Subcommand)]+enum TargetCommands {+ /// List screens available for capturing+ Screens(FormatArgs),+ /// List windows available for capturing+ Windows(FormatArgs),+ /// List cameras available for capturing+ Cameras(FormatArgs),+ /// List microphones available for capturing+ Mics(FormatArgs),+}++#[derive(Args)]+struct FormatArgs {+ #[arg(long, value_enum, default_value_t = OutputFormat::Text)]+ format: OutputFormat,+}++#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]+pub enum OutputFormat {+ Text,+ Json,+}++#[derive(Args)]+struct ProjectArgs {+ #[command(subcommand)]+ command: ProjectCommands,+}++#[derive(Subcommand)]+enum ProjectCommands {+ /// Print project metadata and editor configuration+ Inspect(ProjectTarget),+ /// Verify a project's metadata and expected media files exist+ Validate(ProjectTarget),+ /// Read or write a project's editor configuration (project-config.json)+ Config(ProjectConfigArgs),+}++#[derive(Args)]+struct ProjectTarget {+ project_path: PathBuf,+ #[arg(long, value_enum, default_value_t = OutputFormat::Text)]+ format: OutputFormat,+}++#[derive(Args)]+struct ProjectConfigArgs {+ #[command(subcommand)]+ command: ProjectConfigCommands,+}++#[derive(Subcommand)]+enum ProjectConfigCommands {+ /// Print the project's editor configuration as JSON+ Get(ProjectTarget),+ /// Replace the project's editor configuration from a full JSON document+ Set(ProjectConfigSet),+}++#[derive(Args)]+struct ProjectConfigSet {+ project_path: PathBuf,+ /// Full ProjectConfiguration as a JSON string (camelCase keys); omitted fields reset to defaults+ #[arg(long)]+ settings_json: String,+ #[arg(long, value_enum, default_value_t = OutputFormat::Text)]+ format: OutputFormat,+}++#[derive(Args)]+struct RecordingsArgs {+ #[command(subcommand)]+ command: RecordingsCommands,+}++#[derive(Subcommand)]+enum RecordingsCommands {+ /// List '.cap' recordings discovered on disk+ List(RecordingsListArgs),+}++#[derive(Args)]+struct RecordingsListArgs {+ /// Directory to scan (defaults to the desktop recordings library)+ #[arg(long)]+ dir: Option<PathBuf>,+ #[arg(long, value_enum, default_value_t = OutputFormat::Text)]+ format: OutputFormat,+}++#[derive(Args)]+struct DesktopArgs {+ #[command(subcommand)]+ command: DesktopCommands,+}++#[derive(Subcommand)]+enum DesktopCommands {+ /// Show whether the `cap` shim is installed and on PATH+ Status(FormatArgs),+ /// Install the `cap` shim onto your PATH+ InstallCli(FormatArgs),+ /// Remove the `cap` shim from your PATH+ UninstallCli(FormatArgs),+}++#[derive(Args)]+struct AuthArgs {+ #[command(subcommand)]+ command: AuthCommands,+}++#[derive(Subcommand)]+enum AuthCommands {+ /// Report whether a credential is available and where it comes from (never prints the secret)+ Status(FormatArgs),+}++#[derive(Args)]+struct CompletionsArgs {+ #[arg(value_enum)]+ shell: clap_complete::Shell,+}++fn main() {+ let cli = Cli::parse();+ let level_filter = cli.log_level.level_filter();let registry = tracing_subscriber::registry().with(tracing_subscriber::filter::filter_fn(- (|v| v.target().starts_with("cap_")) as fn(&tracing::Metadata) -> bool,+ // The binary crate is named `cap`, so its own spans/events have target `cap`/`cap::…`,+ // which a bare `cap_` prefix excludes — keep those alongside the `cap_*` library crates.+ (|v| {+ let target = v.target();+ target == "cap" || target.starts_with("cap::") || target.starts_with("cap_")+ }) as fn(&tracing::Metadata) -> bool,));registry- // .with(layer).with(level_filter).with(tracing_subscriber::fmt::layer()@@ -86,16 +322,15 @@ fn main() -> Result<(), String> {).init();- let cli = Cli::parse();let exit_after_success = cli.command.exit_after_success();// Windows export exercises deep WGPU/MediaFoundation/FFmpeg stacks. Running the CLI runtime// on an explicitly large stack is what stopped the export worker from overflowing before// the first frame; keep the sidecar and desktop runtimes in sync.- std::thread::Builder::new()+ let runtime_thread = std::thread::Builder::new().name("cap-cli-runtime".to_string()).stack_size(TOKIO_WORKER_THREAD_STACK_SIZE)- .spawn(move || {+ .spawn(move || -> Result<(), String> {let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().thread_stack_size(TOKIO_WORKER_THREAD_STACK_SIZE)@@ -113,315 +348,258 @@ fn main() -> Result<(), String> {}result- })- .map_err(|e| format!("Failed to spawn CLI runtime thread: {e}"))?- .join()- .map_err(|_| "CLI runtime thread panicked".to_string())?+ });++ // Surface failures as a clean, unquoted `error: ...` line on stderr (the default+ // `Result`-returning main prints `Error: "debug-quoted"`, which is noisy for humans and brittle+ // for agents scraping stderr). clap already exits 2 for usage/parse errors before we get here.+ let outcome = match runtime_thread {+ Ok(handle) => handle.join(),+ Err(e) => {+ eprintln!("error: Failed to spawn CLI runtime thread: {e}");+ std::process::exit(1);+ }+ };++ match outcome {+ Ok(Ok(())) => {}+ Ok(Err(message)) => {+ eprintln!("error: {message}");+ std::process::exit(1);+ }+ Err(_) => {+ eprintln!("error: CLI runtime thread panicked");+ std::process::exit(1);+ }+ }}async fn run(cli: Cli) -> Result<(), String> {+ let json = cli.json;match cli.command {- Commands::Export(e) => {- e.run().await?;- }- Commands::ExportPreview(e) => {- e.run().await?;- }+ Commands::Export(e) => e.run(json).await,+ Commands::ExportPreview(e) => e.run().await,+ Commands::Project(args) => args.run(json),Commands::Record(RecordArgs { command, args }) => match command {- Some(RecordCommands::Screens) => {- let screens = cap_recording::screen_capture::list_displays();-- for (i, (screen, target)) in screens.iter().enumerate() {- println!(- "-screen {}:- id: {}- name: {}- fps: {}",- i,- screen.id,- screen.name,- target.refresh_rate()- );- }+ Some(RecordCommands::Start(args)) => args.run(json).await,+ Some(RecordCommands::Stop(args)) => args.run(json).await,+ Some(RecordCommands::Status(args)) => {+ let format = resolve_format(json, args.format);+ finish_json(format, record::status(format))}- Some(RecordCommands::Windows) => {- let windows = cap_recording::screen_capture::list_windows();-- for (i, (window, target)) in windows.iter().enumerate() {- println!(- "-window {}:- id: {}- name: {}- fps: {}",- i,- window.id,- window.name,- target.display().unwrap().refresh_rate()- );- }+ Some(RecordCommands::SessionRun(args)) => args.run().await,+ Some(RecordCommands::Screens(args)) => {+ let format = resolve_format(json, args.format);+ finish_json(format, targets::print_screens(format))}- Some(RecordCommands::Cameras) => {- let cameras = cap_camera::list_cameras().collect::<Vec<_>>();-- let mut info = vec![];- for camera_info in cameras {- // let format = RequestedFormat::new::<RgbAFormat>(- // RequestedFormatType::AbsoluteHighestFrameRate,- // );-- // let Ok(mut camera) = Camera::new(camera_info.index().clone(), format) else {- // continue;- // };-- info.push(json!({- // "model_id": camera_info.model_id().to_string(),- "display_name": camera_info.display_name()- // "index": camera_info.index().to_string(),- // "name": camera_info.human_name(),- // "pixel_format": camera.frame_format(),- // "formats": camera- // .compatible_camera_formats()- // .unwrap()- // .into_iter()- // .map(|f| format!("{}x{}@{}fps", f.resolution().x(), f.resolution().y(), f.frame_rate()))- // .collect::<Vec<_>>()- }));- }-- println!("{}", serde_json::to_string_pretty(&info).unwrap());+ Some(RecordCommands::Windows(args)) => {+ let format = resolve_format(json, args.format);+ finish_json(format, targets::print_windows(format))}- None => {- args.run().await?;+ Some(RecordCommands::Cameras(args)) => {+ let format = resolve_format(json, args.format);+ finish_json(format, targets::print_cameras(format))+ }+ Some(RecordCommands::Mics(args)) => {+ let format = resolve_format(json, args.format);+ finish_json(format, targets::print_mics(format))}+ None => args.run(json).await,},+ Commands::Screenshot(s) => s.run(json).await,+ Commands::Recordings(args) => args.run(json),+ Commands::Upload(args) => args.run(json).await,+ Commands::Auth(args) => match args.command {+ AuthCommands::Status(args) => {+ let format = resolve_format(json, args.format);+ finish_json(format, credentials::status(format))+ }+ },+ Commands::Targets(args) => args.run(json),+ Commands::Doctor(args) => doctor::run_doctor(resolve_format(json, args.format)),+ Commands::Version(args) => {+ let format = resolve_format(json, args.format);+ finish_json(format, doctor::run_version(format))+ }+ Commands::Desktop(args) => args.run(json),+ Commands::Guide(args) => {+ let format = resolve_format(json, args.format);+ finish_json(format, guide::run(format))+ }+ Commands::Completions(args) => {+ args.run();+ Ok(())+ }}-- Ok(())}-#[derive(Args)]-struct Export {- project_path: PathBuf,- output_path: Option<PathBuf>,- #[arg(long)]- settings_json: Option<String>,- #[arg(long)]- force_ffmpeg_decoder: bool,- #[arg(long)]- progress_json: bool,- #[arg(long)]- completion_json: bool,-}--#[derive(Args)]-struct ExportPreview {- project_path: PathBuf,- #[arg(long)]- frame_time: f64,- #[arg(long)]- settings_json: String,- #[arg(long)]- force_ffmpeg_decoder: bool,-}--#[derive(Deserialize)]-#[serde(tag = "format")]-enum CliExportSettings {- Mp4(cap_export::mp4::Mp4ExportSettings),- Gif(cap_export::gif::GifExportSettings),- Mov(cap_export::mov::MovExportSettings),-}--impl CliExportSettings {- fn default_mp4() -> Self {- Self::Mp4(cap_export::mp4::Mp4ExportSettings {- fps: 60,- resolution_base: XY::new(1920, 1080),- compression: cap_export::mp4::ExportCompression::Maximum,- custom_bpp: None,- force_ffmpeg_decoder: false,- optimize_filesize: false,- })+/// `--json` is a global convenience that forces JSON regardless of a command's local `--format`+/// (which stays for back-compat). Either one selecting JSON wins.+pub fn resolve_format(global_json: bool, local: OutputFormat) -> OutputFormat {+ if global_json {+ OutputFormat::Json+ } else {+ local}+}- fn fps(&self) -> u32 {- match self {- Self::Mp4(settings) => settings.fps,- Self::Gif(settings) => settings.fps,- Self::Mov(settings) => settings.fps,- }+impl TargetsArgs {+ fn run(self, json: bool) -> Result<(), String> {+ let (format, result) = match self.command {+ Some(TargetCommands::Screens(args)) => {+ let format = resolve_format(json, args.format);+ (format, targets::print_screens(format))+ }+ Some(TargetCommands::Windows(args)) => {+ let format = resolve_format(json, args.format);+ (format, targets::print_windows(format))+ }+ Some(TargetCommands::Cameras(args)) => {+ let format = resolve_format(json, args.format);+ (format, targets::print_cameras(format))+ }+ Some(TargetCommands::Mics(args)) => {+ let format = resolve_format(json, args.format);+ (format, targets::print_mics(format))+ }+ None => {+ let format = resolve_format(json, self.format);+ (format, targets::print_all(format))+ }+ };+ finish_json(format, result)}+}- fn force_ffmpeg_decoder(&self) -> bool {- match self {- Self::Mp4(settings) => settings.force_ffmpeg_decoder,- Self::Gif(_) | Self::Mov(_) => false,+impl ProjectArgs {+ fn run(self, json: bool) -> Result<(), String> {+ match self.command {+ // validate emits its own structured report (incl. JSON errors), so it is not wrapped.+ ProjectCommands::Validate(args) => {+ project::validate(args.project_path, resolve_format(json, args.format))+ }+ ProjectCommands::Inspect(args) => {+ let format = resolve_format(json, args.format);+ finish_json(format, project::inspect(args.project_path, format))+ }+ ProjectCommands::Config(ProjectConfigArgs { command }) => match command {+ ProjectConfigCommands::Get(args) => finish_json(+ resolve_format(json, args.format),+ project::config_get(args.project_path),+ ),+ ProjectConfigCommands::Set(args) => {+ let format = resolve_format(json, args.format);+ finish_json(+ format,+ project::config_set(args.project_path, &args.settings_json, format),+ )+ }+ },}}+}- fn cursor_only(&self) -> bool {- match self {- Self::Mov(settings) => settings.cursor_only,- Self::Mp4(_) | Self::Gif(_) => false,+impl RecordingsArgs {+ fn run(self, json: bool) -> Result<(), String> {+ match self.command {+ RecordingsCommands::List(args) => {+ let format = resolve_format(json, args.format);+ finish_json(format, recordings::list(args.dir, format))+ }}}}-#[derive(Serialize)]-#[serde(tag = "type")]-enum ExportProgressMessage<'a> {- Progress {- rendered_count: u32,- total_frames: u32,- },- Completed {- path: &'a std::path::Path,- },-}--impl Export {- async fn run(self) -> Result<(), String> {- let settings = self- .settings_json- .as_deref()- .map(serde_json::from_str)- .transpose()- .map_err(|e| format!("Invalid export settings JSON: {e}"))?- .unwrap_or_else(CliExportSettings::default_mp4);-- let force_ffmpeg_decoder = self.force_ffmpeg_decoder || settings.force_ffmpeg_decoder();- let mut builder = ExporterBase::builder(self.project_path.clone())- .with_force_ffmpeg_decoder(force_ffmpeg_decoder);-- if let Some(output_path) = self.output_path {- builder = builder.with_output_path(output_path);- }-- if settings.cursor_only() {- let meta = RecordingMeta::load_for_project(&self.project_path)- .map_err(|e| format!("Failed to load recording meta: {e}"))?;- builder = builder.with_config(make_cursor_only_project(meta.project_config()));- }-- let exporter_base = builder- .build()- .await- .map_err(|v| format!("Exporter build error: {v}"))?;-- let total_frames = exporter_base.total_frames(settings.fps());- let progress_json = self.progress_json;- let completion_json = self.completion_json;- let stdout = Arc::new(Mutex::new(stdout()));-- if progress_json {- emit_export_message(- &stdout,- &ExportProgressMessage::Progress {- rendered_count: 0,- total_frames,- },- )?;- }-- let progress_stdout = Arc::clone(&stdout);- let on_progress = move |frame_index: u32| {- if progress_json {- emit_export_message(- &progress_stdout,- &ExportProgressMessage::Progress {- rendered_count: (frame_index + 1).min(total_frames),- total_frames,- },+impl DesktopArgs {+ fn run(self, json: bool) -> Result<(), String> {+ let (format, result) = match self.command {+ DesktopCommands::Status(args) => {+ let format = resolve_format(json, args.format);+ (+ format,+ emit_install_status(cap_cli_install::status(), format),+ )+ }+ DesktopCommands::InstallCli(args) => {+ let format = resolve_format(json, args.format);+ (+ format,+ emit_install_status(cap_cli_install::install(), format),+ )+ }+ DesktopCommands::UninstallCli(args) => {+ let format = resolve_format(json, args.format);+ (+ format,+ emit_install_status(cap_cli_install::uninstall(), format),)- .is_ok()- } else {- true}};+ finish_json(format, result)+ }+}- let output_path = match settings {- CliExportSettings::Mp4(settings) => settings.export(exporter_base, on_progress).await,- CliExportSettings::Gif(settings) => settings.export(exporter_base, on_progress).await,- CliExportSettings::Mov(settings) => settings.export(exporter_base, on_progress).await,- }- .map_err(|v| format!("Exporter error: {v}"))?;+/// When `--format json` is requested and a command fails before it could emit its own structured+/// output, write a machine-readable `{"error": "..."}` to stdout so agents do not have to scrape+/// the human-readable stderr line. The original `Err` still propagates for a non-zero exit code.+fn finish_json(format: OutputFormat, result: Result<(), String>) -> Result<(), String> {+ if format == OutputFormat::Json+ && let Err(message) = &result+ {+ let _ = write_json(&serde_json::json!({ "error": message }));+ }+ result+}- if progress_json || completion_json {- emit_export_message(- &stdout,- &ExportProgressMessage::Completed { path: &output_path },- )?;+fn emit_install_status(+ status: Result<cap_cli_install::CliInstallStatus, String>,+ format: OutputFormat,+) -> Result<(), String> {+ let status = status?;+ match format {+ OutputFormat::Json => write_json(&status),+ OutputFormat::Text => {+ println!("install dir: {}", status.install_dir);+ println!("shim: {}", status.shim_path);+ println!("target: {}", status.target_path);+ println!("installed: {}", status.installed);+ println!("on PATH: {}", status.on_path);+ if let Some(conflict) = &status.conflict {+ println!("conflict: {conflict}");+ }+ if !status.on_path {+ if status.path_configured {+ println!(+ "PATH updated; restart your terminal or run: {}",+ status.shell_command+ );+ } else {+ println!("add to PATH: {}", status.shell_command);+ }+ }+ Ok(())}-- info!("Exported video to '{}'", output_path.display());-- Ok(())}}-impl ExportPreview {- async fn run(self) -> Result<(), String> {- let settings =- serde_json::from_str::<cap_export::preview::ExportPreviewSettings>(&self.settings_json)- .map_err(|e| format!("Invalid preview settings JSON: {e}"))?;- let result = cap_export::preview::render_preview(- self.project_path,- self.frame_time,- settings,- self.force_ffmpeg_decoder,- )- .await- .map_err(|e| format!("Preview render error: {e}"))?;-- let mut stdout = stdout();- serde_json::to_writer(&mut stdout, &result).map_err(|e| e.to_string())?;- writeln!(&mut stdout).map_err(|e| e.to_string())?;- stdout.flush().map_err(|e| e.to_string())+impl CompletionsArgs {+ fn run(self) {+ let mut cmd = Cli::command();+ let name = cmd.get_name().to_string();+ clap_complete::generate(self.shell, &mut cmd, name, &mut stdout());}}-fn emit_export_message(- stdout: &Arc<Mutex<std::io::Stdout>>,- message: &ExportProgressMessage<'_>,-) -> Result<(), String> {- let mut stdout = stdout- .lock()- .map_err(|_| "Failed to lock stdout".to_string())?;- serde_json::to_writer(&mut *stdout, message).map_err(|e| e.to_string())?;- writeln!(&mut *stdout).map_err(|e| e.to_string())?;+pub fn write_json<T: Serialize>(value: &T) -> Result<(), String> {+ let mut stdout = stdout();+ serde_json::to_writer_pretty(&mut stdout, value).map_err(|e| e.to_string())?;+ writeln!(&mut stdout).map_err(|e| e.to_string())?;stdout.flush().map_err(|e| e.to_string())}-// fn ffmpeg_callback_experiment() {-// unsafe {-// unsafe extern "C" fn ffmpeg_log_callback(-// arg1: *mut std::ffi::c_void,-// arg2: std::ffi::c_int,-// arg3: *const std::ffi::c_char,-// arg4: *mut std::ffi::c_char,-// ) {-// // ffmpeg::sys::AVClass;--// if !arg1.is_null() {-// let arg1_ptr = arg1;-// let arg1 = **(arg1 as *mut *mut AVClass);-// dbg!(CStr::from_ptr(arg1.class_name));-// if let Some(item_name_fn) = arg1.item_name {-// dbg!(CStr::from_ptr(item_name_fn(arg1_ptr)));-// }-// }--// // let class_name = if !arg1.is_null() {-// // CStr::from_ptr((*arg1).class_name)-// // } else {-// // "unknown".to_string()-// // };--// // println!("[{class_name}] {arg2} {s:?}",);-// }--// ffmpeg::sys::av_log_set_callback(Some(ffmpeg_log_callback));-// }-// }+pub fn write_json_line<T: Serialize>(value: &T) -> Result<(), String> {+ let mut stdout = stdout();+ serde_json::to_writer(&mut stdout, value).map_err(|e| e.to_string())?;+ writeln!(&mut stdout).map_err(|e| e.to_string())?;+ stdout.flush().map_err(|e| e.to_string())+}