Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

release-cli: restructure CLI with subcommands + npm package distribution

Louis Beaumont65cdeaa2e04f
diff --git a/.github/workflows/release-cli.yml b/.github/workflows/release-cli.yml
index 6e9bdfdd9..88d421a96 100644
--- a/.github/workflows/release-cli.yml
+++ b/.github/workflows/release-cli.yml
@@ -133,6 +133,55 @@ jobs:
curl -sL https://sentry.io/get-cli/ | bash
sentry-cli debug-files upload --org $SENTRY_ORG --project screenpipe-cli target/${{ matrix.target }}/release/
+ - name: Codesign binary
+ env:
+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
+ run: |
+ # Import certificate into a temporary keychain
+ KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db
+ KEYCHAIN_PASSWORD=$(openssl rand -base64 32)
+
+ security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
+ security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
+ security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
+
+ echo "$APPLE_CERTIFICATE" | base64 --decode > $RUNNER_TEMP/certificate.p12
+ security import $RUNNER_TEMP/certificate.p12 -P "$APPLE_CERTIFICATE_PASSWORD" \
+ -A -t cert -f pkcs12 -k "$KEYCHAIN_PATH"
+ security set-key-partition-list -S apple-tool:,apple: -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
+ security list-keychain -d user -s "$KEYCHAIN_PATH"
+
+ # Sign the binary with hardened runtime
+ codesign --force --options runtime \
+ --sign "$APPLE_SIGNING_IDENTITY" \
+ --timestamp \
+ target/${{ matrix.target }}/release/screenpipe
+
+ # Verify signature
+ codesign --verify --verbose target/${{ matrix.target }}/release/screenpipe
+ echo "codesign: verified"
+
+ - name: Notarize binary
+ env:
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ run: |
+ # notarytool requires zip/dmg/pkg
+ ditto -c -k --keepParent \
+ target/${{ matrix.target }}/release/screenpipe \
+ $RUNNER_TEMP/screenpipe-notarize.zip
+
+ xcrun notarytool submit $RUNNER_TEMP/screenpipe-notarize.zip \
+ --apple-id "$APPLE_ID" \
+ --password "$APPLE_PASSWORD" \
+ --team-id "$APPLE_TEAM_ID" \
+ --wait --timeout 10m
+
+ echo "notarization: complete"
+
- name: Set version
run: |
if [[ $GITHUB_REF == refs/tags/* ]]; then
@@ -396,6 +445,94 @@ jobs:
name: screenpipe-linux-${{ matrix.target }}
path: screenpipe-*.tar.gz
+ publish-npm:
+ runs-on: ubuntu-latest
+ needs: [build-macos, build-windows, build-linux]
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: "20"
+ registry-url: "https://registry.npmjs.org"
+
+ - name: Set version
+ run: |
+ if [[ $GITHUB_REF == refs/tags/* ]]; then
+ VERSION=${GITHUB_REF#refs/tags/v}
+ else
+ VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
+ fi
+ if [[ -z "$VERSION" ]]; then
+ VERSION="0.0.0"
+ fi
+ echo "VERSION=$VERSION" >> $GITHUB_ENV
+
+ - name: Download Artifacts
+ uses: actions/download-artifact@v4
+ with:
+ path: artifacts
+
+ - name: Prepare platform packages
+ run: |
+ # macOS ARM64
+ mkdir -p packages/cli/screenpipe-darwin-arm64/bin
+ tar -xzf artifacts/screenpipe-macos-aarch64-apple-darwin/screenpipe-*.tar.gz -C /tmp/darwin-arm64 || true
+ cp /tmp/darwin-arm64/bin/screenpipe packages/cli/screenpipe-darwin-arm64/bin/ 2>/dev/null || \
+ (cd artifacts/screenpipe-macos-aarch64-apple-darwin && tar -xzf screenpipe-*.tar.gz && cp bin/screenpipe ../../packages/cli/screenpipe-darwin-arm64/bin/)
+ chmod +x packages/cli/screenpipe-darwin-arm64/bin/screenpipe
+
+ # macOS x64
+ mkdir -p packages/cli/screenpipe-darwin-x64/bin
+ cd artifacts/screenpipe-macos-x86_64-apple-darwin && tar -xzf screenpipe-*.tar.gz && cp bin/screenpipe ../../packages/cli/screenpipe-darwin-x64/bin/ && cd ../..
+ chmod +x packages/cli/screenpipe-darwin-x64/bin/screenpipe
+
+ # Linux x64
+ mkdir -p packages/cli/screenpipe-linux-x64/bin
+ cd artifacts/screenpipe-linux-x86_64-unknown-linux-gnu && tar -xzf screenpipe-*.tar.gz && cp bin/screenpipe ../../packages/cli/screenpipe-linux-x64/bin/ && cd ../..
+ chmod +x packages/cli/screenpipe-linux-x64/bin/screenpipe
+
+ # Windows x64
+ mkdir -p packages/cli/screenpipe-win32-x64/bin
+ cd artifacts/screenpipe-windows && unzip -o screenpipe-*.zip -d extracted && cp extracted/bin/screenpipe.exe ../../packages/cli/screenpipe-win32-x64/bin/ && cp extracted/bin/onnxruntime.dll ../../packages/cli/screenpipe-win32-x64/bin/ 2>/dev/null || true && cd ../..
+
+ - name: Update package versions
+ run: |
+ for pkg in screenpipe screenpipe-darwin-arm64 screenpipe-darwin-x64 screenpipe-linux-x64 screenpipe-win32-x64; do
+ cd packages/cli/$pkg
+ npm version ${{ env.VERSION }} --no-git-tag-version --allow-same-version 2>/dev/null || true
+ cd ../../..
+ done
+ # Update optionalDependencies versions in main package
+ cd packages/cli/screenpipe
+ node -e "
+ const pkg = require('./package.json');
+ for (const dep of Object.keys(pkg.optionalDependencies || {})) {
+ pkg.optionalDependencies[dep] = '${{ env.VERSION }}';
+ }
+ require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, 2) + '\n');
+ "
+ cd ../../..
+
+ - name: Publish platform packages
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ run: |
+ for pkg in screenpipe-darwin-arm64 screenpipe-darwin-x64 screenpipe-linux-x64 screenpipe-win32-x64; do
+ cd packages/cli/$pkg
+ npm publish --access public 2>/dev/null || echo "skipping $pkg (may already exist)"
+ cd ../../..
+ done
+
+ - name: Publish main package
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ run: |
+ cd packages/cli/screenpipe
+ npm publish --access public 2>/dev/null || echo "skipping main package (may already exist)"
+
release:
runs-on: ubuntu-latest
needs: [build-macos, build-windows, build-linux]
diff --git a/crates/screenpipe-db/tests/speaker_reassignment_test.rs b/crates/screenpipe-db/tests/speaker_reassignment_test.rs
index dc2ba4175..a987bf994 100644
--- a/crates/screenpipe-db/tests/speaker_reassignment_test.rs
+++ b/crates/screenpipe-db/tests/speaker_reassignment_test.rs
@@ -176,7 +176,7 @@ mod speaker_reassignment_tests {
create_audio_with_speaker(&db, speaker_id, "Hello, this is Louis speaking").await;
// Reassign to new name
- let (new_speaker_id, transcriptions_updated, embeddings_moved) = db
+ let (new_speaker_id, transcriptions_updated, embeddings_moved, _affected_pairs) = db
.reassign_speaker(audio_chunk_id, "Louis", false)
.await
.unwrap();
@@ -206,7 +206,7 @@ mod speaker_reassignment_tests {
create_audio_with_speaker(&db, unknown_id, "This is also Alice speaking").await;
// Reassign unknown to "Alice"
- let (new_speaker_id, transcriptions_updated, embeddings_moved) = db
+ let (new_speaker_id, transcriptions_updated, embeddings_moved, _affected_pairs) = db
.reassign_speaker(audio_chunk_id, "Alice", false)
.await
.unwrap();
@@ -239,7 +239,7 @@ mod speaker_reassignment_tests {
create_audio_with_speaker(&db, speaker2_id, "Second transcription").await;
// Reassign first speaker to "Bob" with propagation
- let (new_speaker_id, transcriptions_updated, embeddings_moved) = db
+ let (new_speaker_id, transcriptions_updated, embeddings_moved, _affected_pairs) = db
.reassign_speaker(audio_chunk_id1, "Bob", true)
.await
.unwrap();
@@ -277,13 +277,13 @@ mod speaker_reassignment_tests {
let audio_chunk_id = create_audio_with_speaker(&db, speaker_id, "Test audio").await;
// First reassignment
- let (first_id, _, _) = db
+ let (first_id, _, _, _) = db
.reassign_speaker(audio_chunk_id, "Charlie", false)
.await
.unwrap();
// Second reassignment to same name should return same speaker
- let (second_id, _, _) = db
+ let (second_id, _, _, _) = db
.reassign_speaker(audio_chunk_id, "Charlie", false)
.await
.unwrap();
@@ -324,7 +324,7 @@ mod speaker_reassignment_tests {
.await;
// Correct the misidentification by naming it "Bob"
- let (bob_id, transcriptions_updated, _embeddings_moved) = db
+ let (bob_id, transcriptions_updated, _embeddings_moved, _affected_pairs) = db
.reassign_speaker(audio_chunk_id, "Bob", false)
.await
.unwrap();
diff --git a/crates/screenpipe-db/tests/timeline_performance_test.rs b/crates/screenpipe-db/tests/timeline_performance_test.rs
index e0f1508ca..d9cef2ac3 100644
--- a/crates/screenpipe-db/tests/timeline_performance_test.rs
+++ b/crates/screenpipe-db/tests/timeline_performance_test.rs
@@ -79,7 +79,7 @@ mod timeline_performance_tests {
async fn insert_audio_transcriptions(
db: &DatabaseManager,
count: usize,
- start_time: chrono::DateTime<Utc>,
+ _start_time: chrono::DateTime<Utc>,
) {
for i in 0..count {
let audio_chunk_id = db
diff --git a/crates/screenpipe-server/src/bin/screenpipe-server.rs b/crates/screenpipe-server/src/bin/screenpipe-server.rs
index 1c142b253..5f8fb671d 100644
--- a/crates/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/crates/screenpipe-server/src/bin/screenpipe-server.rs
@@ -16,16 +16,16 @@ use screenpipe_core::find_ffmpeg_path;
use screenpipe_core::sync::{
BlobType, SyncClientConfig, SyncEvent, SyncManager, SyncService, SyncServiceConfig,
};
-use screenpipe_db::{
- create_migration_worker, DatabaseManager, MigrationCommand, MigrationConfig, MigrationStatus,
-};
+use screenpipe_db::DatabaseManager;
use screenpipe_server::{
analytics,
cli::{
get_or_create_machine_id, AudioCommand, Cli, CliAudioTranscriptionEngine, CliOcrEngine,
- Command, McpCommand, MigrationSubCommand, OutputFormat, SyncCommand, VisionCommand,
+ Command, McpCommand, OutputFormat, RecordArgs, SyncCommand, VisionCommand,
},
- handle_index_command, start_continuous_recording, start_sleep_monitor, start_ui_recording,
+ cli_pipe::handle_pipe_command,
+ cli_status::handle_status_command,
+ start_continuous_recording, start_sleep_monitor, start_ui_recording,
sync_provider::ScreenpipeSyncProvider,
vision_manager::{
start_monitor_watcher, stop_monitor_watcher, VisionManager, VisionManagerConfig,
@@ -243,7 +243,7 @@ async fn main() -> anyhow::Result<()> {
set_fd_limit();
debug!("starting screenpipe server");
- let cli = Cli::parse();
+ let mut cli = Cli::parse();
// Initialize Sentry only if telemetry is enabled
let _sentry_guard = if !cli.disable_telemetry {
@@ -376,27 +376,27 @@ async fn main() -> anyhow::Result<()> {
let local_data_dir_clone = local_data_dir.clone();
// Only set up logging if we're not running a command with JSON output
- let should_log = match &cli.command {
- Some(Command::Add {
- output: OutputFormat::Text,
- ..
- }) => true,
- Some(Command::Migrate {
- output: OutputFormat::Text,
- ..
- }) => true,
- _ => true,
- };
-
// Store the guard in a variable that lives for the entire main function
- let _log_guard = if should_log {
- Some(setup_logging(&local_data_dir, &cli)?)
- } else {
- None
- };
+ let _log_guard = Some(setup_logging(&local_data_dir, &cli)?);
+ // Handle subcommands that return early
if let Some(ref command) = cli.command {
match command {
+ Command::Record(_) => {
+ // Fall through to recording logic below
+ }
+ Command::Status {
+ json,
+ data_dir,
+ port,
+ } => {
+ handle_status_command(*json, data_dir, *port).await?;
+ return Ok(());
+ }
+ Command::Pipe { subcommand } => {
+ handle_pipe_command(subcommand).await?;
+ return Ok(());
+ }
Command::Audio { subcommand } => match subcommand {
AudioCommand::List { output } => {
let default_input = default_input_device().unwrap();
@@ -456,246 +456,6 @@ async fn main() -> anyhow::Result<()> {
return Ok(());
}
},
- Command::Completions { shell } => {
- cli.handle_completions(*shell)?;
- return Ok(());
- }
- Command::Migrate {
- migration_name,
- data_dir,
- subcommand,
- output,
- batch_size,
- batch_delay_ms,
- continue_on_error,
- } => {
- // Initialize the database
- let local_data_dir = get_base_dir(data_dir)?;
- let db = Arc::new(
- DatabaseManager::new(&format!(
- "{}/db.sqlite",
- local_data_dir.to_string_lossy()
- ))
- .await
- .map_err(|e| {
- error!("failed to initialize database: {:?}", e);
- e
- })?,
- );
-
- // Create a migration worker config
- let config = MigrationConfig::new(*batch_size, *batch_delay_ms, *continue_on_error);
-
- // Start the migration worker
- let (cmd_tx, mut status_rx, worker_handle) =
- create_migration_worker(db, Some(config));
-
- // Process the specified subcommand or default to status
- let cmd = match subcommand {
- Some(MigrationSubCommand::Start) => MigrationCommand::Start,
- Some(MigrationSubCommand::Pause) => MigrationCommand::Pause,
- Some(MigrationSubCommand::Stop) => MigrationCommand::Stop,
- Some(MigrationSubCommand::Status) | None => MigrationCommand::Status,
- };
-
- // Send the command to the worker
- if let Err(e) = cmd_tx.send(cmd.clone()).await {
- error!("failed to send command to migration worker: {}", e);
- return Err(anyhow::anyhow!(
- "Failed to send command to migration worker"
- ));
- }
-
- // If the command is start, we need to track the progress
- if matches!(cmd, MigrationCommand::Start) {
- // Send the start command and wait for the worker to acknowledge
- if let Some(response) = status_rx.recv().await {
- match output {
- OutputFormat::Json => {
- println!("{}", serde_json::to_string_pretty(&response.status)?);
- }
- OutputFormat::Text => {
- info!("Started migration: {}", migration_name);
- match response.status {
- MigrationStatus::Running {
- total_records,
- processed_records,
- } => {
- info!(
- "Processing records: {}/{} ({:.2}%)",
- processed_records,
- total_records,
- if total_records > 0 {
- (processed_records as f64 / total_records as f64)
- * 100.0
- } else {
- 0.0
- }
- );
- }
- _ => {
- info!("Migration status: {:?}", response.status);
- }
- }
- }
- }
- }
-
- // Keep checking status periodically until migration completes, fails, or is stopped
- let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(5));
- loop {
- interval.tick().await;
-
- // Send status command
- if let Err(e) = cmd_tx.send(MigrationCommand::Status).await {
- error!("failed to send status command: {}", e);
- break;
- }
-
- // Wait for response
- if let Some(response) = status_rx.recv().await {
- match output {
- OutputFormat::Json => {
- println!("{}", serde_json::to_string_pretty(&response.status)?);
- }
- OutputFormat::Text => match &response.status {
- MigrationStatus::Running {
- total_records,
- processed_records,
- } => {
- info!(
- "Processing records: {}/{} ({:.2}%)",
- processed_records,
- total_records,
- if *total_records > 0 {
- (*processed_records as f64 / *total_records as f64)
- * 100.0
- } else {
- 0.0
- }
- );
- }
- MigrationStatus::Completed {
- total_records,
- duration_secs,
- } => {
- info!(
- "Migration completed: {} records processed in {} seconds",
- total_records, duration_secs
- );
- break;
- }
- MigrationStatus::Paused {
- total_records,
- processed_records,
- } => {
- info!(
- "Migration paused: {}/{} ({:.2}%)",
- processed_records,
- total_records,
- if *total_records > 0 {
- (*processed_records as f64 / *total_records as f64)
- * 100.0
- } else {
- 0.0
- }
- );
- }
- MigrationStatus::Failed {
- total_records,
- processed_records,
- error,
- } => {
- error!(
- "Migration failed: {}/{} records processed. Error: {}",
- processed_records, total_records, error
- );
- break;
- }
- _ => {
- info!("Migration status: {:?}", response.status);
- }
- },
- }
- } else {
- break;
- }
- }
- } else {
- // For non-start commands, just get the status once
- if let Some(response) = status_rx.recv().await {
- match output {
- OutputFormat::Json => {
- println!("{}", serde_json::to_string_pretty(&response.status)?);
- }
- OutputFormat::Text => {
- info!("Migration status: {:?}", response.status);
- }
- }
- }
- }
-
- // If we explicitly stopped, wait for the worker to finish
- if matches!(cmd, MigrationCommand::Stop) {
- if let Err(e) = worker_handle.await {
- error!("error waiting for worker to finish: {}", e);
- }
- }
-
- return Ok(());
- }
- Command::Add {
- path,
- output,
- data_dir,
- pattern,
- ocr_engine,
- metadata_override,
- copy_videos,
- debug,
- use_embedding,
- } => {
- let local_data_dir = get_base_dir(data_dir)?;
-
- // Update logging filter if debug is enabled
- if *debug {
- tracing::subscriber::set_global_default(
- tracing_subscriber::registry()
- .with(
- EnvFilter::from_default_env()
- .add_directive("screenpipe=debug".parse().unwrap()),
- )
- .with(fmt::layer().with_writer(std::io::stdout)),
- )
- .ok();
- debug!("debug logging enabled");
- }
-
- let db = Arc::new(
- DatabaseManager::new(&format!(
- "{}/db.sqlite",
- local_data_dir.to_string_lossy()
- ))
- .await
- .map_err(|e| {
- error!("failed to initialize database: {:?}", e);
- e
- })?,
- );
- handle_index_command(
- local_data_dir,
- path.to_string(),
- pattern.clone(),
- db,
- output.clone(),
- ocr_engine.clone(),
- metadata_override.clone(),
- *copy_videos,
- *use_embedding,
- )
- .await?;
- return Ok(());
- }
Command::Mcp { subcommand } => {
handle_mcp_command(subcommand, &local_data_dir_clone).await?;
return Ok(());
@@ -707,6 +467,68 @@ async fn main() -> anyhow::Result<()> {
}
}
+ // If we get here, we're either `screenpipe` (no command) or `screenpipe record`
+ // For bare `screenpipe`, show deprecation hint
+ if cli.command.is_none() {
+ eprintln!(
+ "{}",
+ "hint: use 'screenpipe record' explicitly. bare 'screenpipe' will be removed in a future version."
+ .bright_yellow()
+ );
+ }
+
+ // Build RecordArgs from either the Record subcommand or legacy top-level flags.
+ // Then override cli fields so all downstream code (which uses cli.*) gets the right values.
+ let record_args = match &cli.command {
+ Some(Command::Record(args)) => args.clone(),
+ _ => RecordArgs::from_cli(&cli),
+ };
+
+ // Sync cli fields from record_args (needed when `screenpipe record --fps 2` is used,
+ // because clap puts those flags on RecordArgs, not on Cli's top-level fields)
+ cli.fps = record_args.fps;
+ cli.adaptive_fps = record_args.adaptive_fps;
+ cli.audio_chunk_duration = record_args.audio_chunk_duration;
+ cli.port = record_args.port;
+ cli.disable_audio = record_args.disable_audio;
+ cli.audio_device = record_args.audio_device.clone();
+ cli.use_system_default_audio = record_args.use_system_default_audio;
+ cli.realtime_audio_device = record_args.realtime_audio_device.clone();
+ cli.data_dir = record_args.data_dir.clone();
+ cli.debug = record_args.debug;
+ cli.audio_transcription_engine = record_args.audio_transcription_engine.clone();
+ cli.enable_realtime_audio_transcription = record_args.enable_realtime_audio_transcription;
+ cli.enable_realtime_vision = record_args.enable_realtime_vision;
+ cli.ocr_engine = record_args.ocr_engine.clone();
+ cli.monitor_id = record_args.monitor_id.clone();
+ cli.use_all_monitors = record_args.use_all_monitors;
+ cli.language = record_args.language.clone();
+ cli.use_pii_removal = record_args.use_pii_removal;
+ cli.disable_vision = record_args.disable_vision;
+ cli.vad_engine = record_args.vad_engine.clone();
+ cli.ignored_windows = record_args.ignored_windows.clone();
+ cli.included_windows = record_args.included_windows.clone();
+ cli.ignored_urls = record_args.ignored_urls.clone();
+ cli.video_chunk_duration = record_args.video_chunk_duration;
+ cli.deepgram_api_key = record_args.deepgram_api_key.clone();
+ cli.auto_destruct_pid = record_args.auto_destruct_pid;
+ cli.vad_sensitivity = record_args.vad_sensitivity.clone();
+ cli.disable_telemetry = record_args.disable_telemetry;
+ cli.enable_llm = record_args.enable_llm;
+ cli.enable_frame_cache = record_args.enable_frame_cache;
+ cli.capture_unfocused_windows = record_args.capture_unfocused_windows;
+ cli.video_quality = record_args.video_quality.clone();
+ cli.enable_ui_events = record_args.enable_ui_events;
+ cli.enable_sync = record_args.enable_sync;
+ cli.sync_token = record_args.sync_token.clone();
+ cli.sync_password = record_args.sync_password.clone();
+ cli.sync_interval_secs = record_args.sync_interval_secs;
+ cli.sync_machine_id = record_args.sync_machine_id.clone();
+
+ // Recompute data dir in case record_args overrode it
+ let local_data_dir = get_base_dir(&cli.data_dir)?;
+ let local_data_dir_clone = local_data_dir.clone();
+
// Replace the current conditional check with:
let ffmpeg_path = find_ffmpeg_path();
if ffmpeg_path.is_none() {
diff --git a/crates/screenpipe-server/src/cli.rs b/crates/screenpipe-server/src/cli.rs
index 47e62d55a..0572d901e 100644
--- a/crates/screenpipe-server/src/cli.rs
+++ b/crates/screenpipe-server/src/cli.rs
@@ -1,9 +1,5 @@
-use std::{path::PathBuf, sync::Arc};
-
-use clap::CommandFactory;
use clap::ValueEnum;
use clap::{Parser, Subcommand, ValueHint};
-use clap_complete::{generate, Shell};
use screenpipe_audio::{
core::engine::AudioTranscriptionEngine as CoreAudioTranscriptionEngine,
vad::{VadEngineEnum, VadSensitivity},
@@ -12,6 +8,8 @@ use screenpipe_core::Language;
use screenpipe_db::CustomOcrConfig as DBCustomOcrConfig;
use screenpipe_db::OcrEngine as DBOcrEngine;
use screenpipe_vision::{custom_ocr::CustomOcrConfig, utils::OcrEngine as CoreOcrEngine};
+use std::sync::Arc;
+
#[derive(Clone, Debug, ValueEnum, PartialEq)]
pub enum CliAudioTranscriptionEngine {
#[clap(name = "deepgram")]
@@ -92,7 +90,6 @@ impl From<CliOcrEngine> for CoreOcrEngine {
#[cfg(target_os = "macos")]
CliOcrEngine::AppleNative => CoreOcrEngine::AppleNative,
CliOcrEngine::Custom => {
- // Try to read config from environment variable
if let Ok(config_str) = std::env::var("SCREENPIPE_CUSTOM_OCR_CONFIG") {
match serde_json::from_str(&config_str) {
Ok(config) => CoreOcrEngine::Custom(config),
@@ -108,6 +105,7 @@ impl From<CliOcrEngine> for CoreOcrEngine {
}
}
}
+
#[derive(Clone, Debug, ValueEnum, PartialEq)]
pub enum CliVadEngine {
#[clap(name = "webrtc")]
@@ -142,86 +140,74 @@ impl From<CliVadSensitivity> for VadSensitivity {
}
}
+#[derive(Clone, Debug, ValueEnum, PartialEq)]
+pub enum OutputFormat {
+ Text,
+ Json,
+}
+
+// =============================================================================
+// Top-level CLI
+// =============================================================================
+
#[derive(Parser)]
#[command(
author,
version,
- about,
+ about = "screenpipe: build ai apps that have the full context",
long_about = None,
name = "screenpipe"
)]
pub struct Cli {
+ #[command(subcommand)]
+ pub command: Option<Command>,
+
+ // =========================================================================
+ // Legacy top-level flags (for backward compat with bare `screenpipe`)
+ // These are duplicated on RecordArgs. When command is None, these are used.
+ // =========================================================================
+
/// FPS for continuous recording
- /// 1 FPS = 30 GB / month
- /// 5 FPS = 150 GB / month
- /// Optimise based on your needs.
- /// Your screen rarely change more than 1 times within a second, right?
#[cfg_attr(not(target_os = "macos"), arg(short, long, default_value_t = 1.0))]
#[cfg_attr(target_os = "macos", arg(short, long, default_value_t = 0.5))]
- pub fps: f64, // ! not crazy about this (inconsistent behaviour across platforms) see https://github.com/screenpipe/screenpipe/issues/173
+ pub fps: f64,
- /// Enable adaptive FPS based on input activity.
- /// When enabled, capture rate increases during mouse/keyboard activity (up to 5 FPS)
- /// and decreases during idle periods (down to base FPS).
- /// Requires the 'adaptive-fps' feature to be enabled.
#[arg(long, default_value_t = false)]
pub adaptive_fps: bool,
- /// Audio chunk duration in seconds
#[arg(short = 'd', long, default_value_t = 30)]
pub audio_chunk_duration: u64,
- /// Port to run the server on
#[arg(short = 'p', long, default_value_t = 3030)]
pub port: u16,
- /// Disable audio recording
#[arg(long, default_value_t = false)]
pub disable_audio: bool,
- /// Audio devices to use (can be specified multiple times)
#[arg(short = 'i', long)]
pub audio_device: Vec<String>,
- /// Follow system default audio devices. When enabled, screenpipe automatically
- /// switches to the current system default when devices are plugged/unplugged
- /// or the default changes in system settings.
#[arg(long, default_value_t = true)]
pub use_system_default_audio: bool,
- // Audio devices to use for realtime audio transcription
#[arg(short = 'r', long)]
pub realtime_audio_device: Vec<String>,
- /// Data directory. Default to $HOME/.screenpipe
#[arg(long, value_hint = ValueHint::DirPath)]
pub data_dir: Option<String>,
- /// Enable debug logging for screenpipe modules
#[arg(long)]
pub debug: bool,
- /// Audio transcription engine to use.
- /// Deepgram is a very high quality cloud-based transcription service (free of charge on us for now), recommended for high quality audio.
- /// WhisperTiny is a local, lightweight transcription model, recommended for high data privacy.
- /// WhisperDistilLargeV3 is a local, lightweight transcription model (-a whisper-large), recommended for higher quality audio than tiny.
- /// WhisperLargeV3Turbo is a local, lightweight transcription model (-a whisper-large-v3-turbo), recommended for higher quality audio than tiny.
#[arg(short = 'a', long, value_enum, default_value_t = CliAudioTranscriptionEngine::WhisperLargeV3TurboQuantized)]
pub audio_transcription_engine: CliAudioTranscriptionEngine,
- /// Enable realtime audio transcription
#[arg(long, default_value_t = false)]
pub enable_realtime_audio_transcription: bool,
- /// Enable realtime vision
#[arg(long, default_value_t = true)]
pub enable_realtime_vision: bool,
- /// OCR engine to use.
- /// AppleNative is the default local OCR engine for macOS.
- /// WindowsNative is a local OCR engine for Windows.
- /// Unstructured is a cloud OCR engine (free of charge on us for now), recommended for high quality OCR.
- /// Tesseract is a local OCR engine (not supported on macOS)
#[cfg_attr(
target_os = "macos",
arg(short = 'o', long, value_enum, default_value_t = CliOcrEngine::AppleNative)
@@ -236,123 +222,77 @@ pub struct Cli {
)]
pub ocr_engine: CliOcrEngine,
- /// Monitor IDs to use, these will be used to select the monitors to record
#[arg(short = 'm', long)]
pub monitor_id: Vec<u32>,
- /// Automatically record all monitors and dynamically detect when monitors are
- /// connected/disconnected. Recording starts/stops automatically as monitors change.
#[arg(long, default_value_t = true)]
pub use_all_monitors: bool,
#[arg(short = 'l', long, value_enum)]
pub language: Vec<Language>,
- /// Enable PII removal from OCR text and audio transcriptions saved to db and returned in search results.
- /// When enabled, sensitive data like emails, phone numbers, credit cards, SSNs, and API keys are redacted.
#[arg(long, default_value_t = true)]
pub use_pii_removal: bool,
- /// Disable vision recording
#[arg(long, default_value_t = false)]
pub disable_vision: bool,
- /// VAD engine to use for speech detection
- #[arg(long, value_enum, default_value_t = CliVadEngine::Silero)] // Silero or WebRtc
+ #[arg(long, value_enum, default_value_t = CliVadEngine::Silero)]
pub vad_engine: CliVadEngine,
- /// List of windows to ignore (by title) for screen recording - we use contains to match, example:
- /// --ignored-windows "Spotify" --ignored-windows "Bit" will ignore both "Bitwarden" and "Bittorrent"
- /// --ignored-windows "x" will ignore "Home / X" and "SpaceX"
#[arg(long)]
pub ignored_windows: Vec<String>,
- /// List of windows to include (by title) for screen recording - we use contains to match, example:
- /// --included-windows "Chrome" will include "Google Chrome"
- /// --included-windows "WhatsApp" will include "WhatsApp"
#[arg(long)]
pub included_windows: Vec<String>,
- /// List of URLs to ignore for browser privacy filtering - we use contains to match, example:
- /// --ignored-urls "wellsfargo.com" --ignored-urls "chase.com" will ignore banking sites
- /// --ignored-urls ".bank" will ignore any URL containing ".bank"
#[arg(long)]
pub ignored_urls: Vec<String>,
- /// Video chunk duration in seconds
#[arg(long, default_value_t = 60)]
pub video_chunk_duration: u64,
- /// Deepgram API Key for audio transcription
#[arg(long = "deepgram-api-key")]
pub deepgram_api_key: Option<String>,
- /// PID to watch for auto-destruction. If provided, screenpipe will stop when this PID is no longer running.
#[arg(long)]
pub auto_destruct_pid: Option<u32>,
- /// Voice activity detection sensitivity level
#[arg(long, value_enum, default_value_t = CliVadSensitivity::High)]
pub vad_sensitivity: CliVadSensitivity,
- /// Disable telemetry
#[arg(long, default_value_t = false)]
pub disable_telemetry: bool,
- /// Enable Local LLM API
#[arg(long, default_value_t = false)]
pub enable_llm: bool,
- /// Enable experimental video frame cache (may increase CPU usage) - makes timeline UI available, frame streaming, etc.
#[arg(long, default_value_t = true)]
pub enable_frame_cache: bool,
- /// Capture windows that are not focused (default: false)
#[arg(long, default_value_t = false)]
pub capture_unfocused_windows: bool,
- /// Video quality preset: low, balanced, high, max.
- /// Controls H.265 CRF during recording and JPEG quality during frame extraction.
- /// low=smallest files, balanced=default, high=sharper, max=best quality.
#[arg(long, default_value = "balanced")]
pub video_quality: String,
- /// Enable UI event capture (keyboard, mouse, clipboard).
- /// Requires accessibility and input monitoring permissions on macOS.
- /// Currently supported on macOS only.
#[arg(long, default_value_t = false)]
pub enable_ui_events: bool,
- // =========================================================================
- // Cloud Sync Options
- // =========================================================================
- /// Enable cloud sync for cross-device data synchronization.
- /// Requires a valid sync token and password.
#[arg(long, default_value_t = false)]
pub enable_sync: bool,
- /// API token for cloud sync authentication.
- /// Can also be set via SCREENPIPE_SYNC_TOKEN environment variable.
#[arg(long, env = "SCREENPIPE_SYNC_TOKEN")]
pub sync_token: Option<String>,
- /// Password for encrypting synced data.
- /// This password is used to derive encryption keys - it never leaves your device.
- /// Can also be set via SCREENPIPE_SYNC_PASSWORD environment variable.
#[arg(long, env = "SCREENPIPE_SYNC_PASSWORD")]
pub sync_password: Option<String>,
- /// Interval between sync cycles in seconds (default: 300 = 5 minutes)
#[arg(long, default_value_t = 300)]
pub sync_interval_secs: u64,
- /// Override the machine ID for this device.
- /// By default, a unique ID is derived from the hostname.
#[arg(long)]
pub sync_machine_id: Option<String>,
-
- #[command(subcommand)]
- pub command: Option<Command>,
}
impl Cli {
@@ -365,16 +305,10 @@ impl Cli {
}
Ok(unique_langs.into_iter().collect())
}
- pub fn handle_completions(&self, shell: Shell) -> anyhow::Result<()> {
- let mut cmd = Self::command();
- generate(shell, &mut cmd, "screenpipe", &mut std::io::stdout());
- Ok(())
- }
/// Create UI recorder configuration from CLI arguments
#[cfg(feature = "ui-events")]
pub fn to_ui_recorder_config(&self) -> crate::ui_recorder::UiRecorderConfig {
- // Use sensible defaults - the single enable_ui_events flag controls everything
crate::ui_recorder::UiRecorderConfig {
enabled: self.enable_ui_events,
excluded_windows: self.ignored_windows.clone(),
@@ -382,107 +316,353 @@ impl Cli {
}
}
- /// Create UI recorder configuration (stub when ui-events feature is disabled)
#[cfg(not(feature = "ui-events"))]
pub fn to_ui_recorder_config(&self) -> crate::ui_recorder::UiRecorderConfig {
crate::ui_recorder::UiRecorderConfig { enabled: false }
}
}
+// =============================================================================
+// Commands
+// =============================================================================
+
#[derive(Subcommand)]
pub enum Command {
+ /// Start recording screen, audio, and optionally serve the API
+ Record(RecordArgs),
+
+ /// Show screenpipe status (running state, data stats)
+ Status {
+ /// Output format
+ #[arg(long, default_value_t = false)]
+ json: bool,
+ /// Data directory. Default to $HOME/.screenpipe
+ #[arg(long, value_hint = ValueHint::DirPath)]
+ data_dir: Option<String>,
+ /// Port to check for running server
+ #[arg(short = 'p', long, default_value_t = 3030)]
+ port: u16,
+ },
+
+ /// Manage pipes (scheduled agents on screen data)
+ Pipe {
+ #[command(subcommand)]
+ subcommand: PipeCommand,
+ },
+
/// Audio device management commands
Audio {
#[command(subcommand)]
subcommand: AudioCommand,
},
+
/// Vision device management commands
Vision {
#[command(subcommand)]
subcommand: VisionCommand,
},
+
/// Cloud sync management commands
Sync {
#[command(subcommand)]
subcommand: SyncCommand,
},
+
/// MCP Server management commands
Mcp {
#[command(subcommand)]
subcommand: McpCommand,
},
- /// Add video files to existing screenpipe data (OCR only) - DOES NOT SUPPORT AUDIO
- Add {
- /// Path to folder containing video files
- path: String,
- /// Data directory. Default to $HOME/.screenpipe
- #[arg(long, value_hint = ValueHint::DirPath)]
- data_dir: Option<String>,
+}
+
+// =============================================================================
+// Record args (all the flags that were previously top-level)
+// =============================================================================
+
+#[derive(Parser, Clone)]
+pub struct RecordArgs {
+ /// FPS for continuous recording
+ /// 1 FPS = 30 GB / month, 5 FPS = 150 GB / month
+ #[cfg_attr(not(target_os = "macos"), arg(short, long, default_value_t = 1.0))]
+ #[cfg_attr(target_os = "macos", arg(short, long, default_value_t = 0.5))]
+ pub fps: f64,
+
+ /// Enable adaptive FPS based on input activity
+ #[arg(long, default_value_t = false)]
+ pub adaptive_fps: bool,
+
+ /// Audio chunk duration in seconds
+ #[arg(short = 'd', long, default_value_t = 30)]
+ pub audio_chunk_duration: u64,
+
+ /// Port to run the server on
+ #[arg(short = 'p', long, default_value_t = 3030)]
+ pub port: u16,
+
+ /// Disable audio recording
+ #[arg(long, default_value_t = false)]
+ pub disable_audio: bool,
+
+ /// Audio devices to use (can be specified multiple times)
+ #[arg(short = 'i', long)]
+ pub audio_device: Vec<String>,
+
+ /// Follow system default audio devices
+ #[arg(long, default_value_t = true)]
+ pub use_system_default_audio: bool,
+
+ /// Audio devices to use for realtime audio transcription
+ #[arg(short = 'r', long)]
+ pub realtime_audio_device: Vec<String>,
+
+ /// Data directory. Default to $HOME/.screenpipe
+ #[arg(long, value_hint = ValueHint::DirPath)]
+ pub data_dir: Option<String>,
+
+ /// Enable debug logging for screenpipe modules
+ #[arg(long)]
+ pub debug: bool,
+
+ /// Audio transcription engine to use
+ #[arg(short = 'a', long, value_enum, default_value_t = CliAudioTranscriptionEngine::WhisperLargeV3TurboQuantized)]
+ pub audio_transcription_engine: CliAudioTranscriptionEngine,
+
+ /// Enable realtime audio transcription
+ #[arg(long, default_value_t = false)]
+ pub enable_realtime_audio_transcription: bool,
+
+ /// Enable realtime vision
+ #[arg(long, default_value_t = true)]
+ pub enable_realtime_vision: bool,
+
+ /// OCR engine to use
+ #[cfg_attr(
+ target_os = "macos",
+ arg(short = 'o', long, value_enum, default_value_t = CliOcrEngine::AppleNative)
+ )]
+ #[cfg_attr(
+ target_os = "windows",
+ arg(short = 'o', long, value_enum, default_value_t = CliOcrEngine::WindowsNative)
+ )]
+ #[cfg_attr(
+ not(any(target_os = "macos", target_os = "windows")),
+ arg(short = 'o', long, value_enum, default_value_t = CliOcrEngine::Tesseract)
+ )]
+ pub ocr_engine: CliOcrEngine,
+
+ /// Monitor IDs to use
+ #[arg(short = 'm', long)]
+ pub monitor_id: Vec<u32>,
+
+ /// Automatically record all monitors
+ #[arg(long, default_value_t = true)]
+ pub use_all_monitors: bool,
+
+ /// Languages for OCR/transcription
+ #[arg(short = 'l', long, value_enum)]
+ pub language: Vec<Language>,
+
+ /// Enable PII removal
+ #[arg(long, default_value_t = true)]
+ pub use_pii_removal: bool,
+
+ /// Disable vision recording
+ #[arg(long, default_value_t = false)]
+ pub disable_vision: bool,
+
+ /// VAD engine to use for speech detection
+ #[arg(long, value_enum, default_value_t = CliVadEngine::Silero)]
+ pub vad_engine: CliVadEngine,
+
+ /// Windows to ignore (by title, uses contains matching)
+ #[arg(long)]
+ pub ignored_windows: Vec<String>,
+
+ /// Windows to include (by title, uses contains matching)
+ #[arg(long)]
+ pub included_windows: Vec<String>,
+
+ /// URLs to ignore for browser privacy filtering
+ #[arg(long)]
+ pub ignored_urls: Vec<String>,
+
+ /// Video chunk duration in seconds
+ #[arg(long, default_value_t = 60)]
+ pub video_chunk_duration: u64,
+
+ /// Deepgram API Key for audio transcription
+ #[arg(long = "deepgram-api-key")]
+ pub deepgram_api_key: Option<String>,
+
+ /// PID to watch for auto-destruction
+ #[arg(long)]
+ pub auto_destruct_pid: Option<u32>,
+
+ /// Voice activity detection sensitivity level
+ #[arg(long, value_enum, default_value_t = CliVadSensitivity::High)]
+ pub vad_sensitivity: CliVadSensitivity,
+
+ /// Disable telemetry
+ #[arg(long, default_value_t = false)]
+ pub disable_telemetry: bool,
+
+ /// Enable Local LLM API
+ #[arg(long, default_value_t = false)]
+ pub enable_llm: bool,
+
+ /// Enable frame cache (makes timeline UI available)
+ #[arg(long, default_value_t = true)]
+ pub enable_frame_cache: bool,
+
+ /// Capture windows that are not focused
+ #[arg(long, default_value_t = false)]
+ pub capture_unfocused_windows: bool,
+
+ /// Video quality preset: low, balanced, high, max
+ #[arg(long, default_value = "balanced")]
+ pub video_quality: String,
+
+ /// Enable UI event capture (keyboard, mouse, clipboard)
+ #[arg(long, default_value_t = false)]
+ pub enable_ui_events: bool,
+
+ /// Enable cloud sync
+ #[arg(long, default_value_t = false)]
+ pub enable_sync: bool,
+
+ /// API token for cloud sync
+ #[arg(long, env = "SCREENPIPE_SYNC_TOKEN")]
+ pub sync_token: Option<String>,
+
+ /// Password for encrypting synced data
+ #[arg(long, env = "SCREENPIPE_SYNC_PASSWORD")]
+ pub sync_password: Option<String>,
+
+ /// Interval between sync cycles in seconds
+ #[arg(long, default_value_t = 300)]
+ pub sync_interval_secs: u64,
+
+ /// Override the machine ID for this device
+ #[arg(long)]
+ pub sync_machine_id: Option<String>,
+}
+
+impl RecordArgs {
+ /// Convert legacy top-level Cli flags into RecordArgs
+ pub fn from_cli(cli: &Cli) -> Self {
+ RecordArgs {
+ fps: cli.fps,
+ adaptive_fps: cli.adaptive_fps,
+ audio_chunk_duration: cli.audio_chunk_duration,
+ port: cli.port,
+ disable_audio: cli.disable_audio,
+ audio_device: cli.audio_device.clone(),
+ use_system_default_audio: cli.use_system_default_audio,
+ realtime_audio_device: cli.realtime_audio_device.clone(),
+ data_dir: cli.data_dir.clone(),
+ debug: cli.debug,
+ audio_transcription_engine: cli.audio_transcription_engine.clone(),
+ enable_realtime_audio_transcription: cli.enable_realtime_audio_transcription,
+ enable_realtime_vision: cli.enable_realtime_vision,
+ ocr_engine: cli.ocr_engine.clone(),
+ monitor_id: cli.monitor_id.clone(),
+ use_all_monitors: cli.use_all_monitors,
+ language: cli.language.clone(),
+ use_pii_removal: cli.use_pii_removal,
+ disable_vision: cli.disable_vision,
+ vad_engine: cli.vad_engine.clone(),
+ ignored_windows: cli.ignored_windows.clone(),
+ included_windows: cli.included_windows.clone(),
+ ignored_urls: cli.ignored_urls.clone(),
+ video_chunk_duration: cli.video_chunk_duration,
+ deepgram_api_key: cli.deepgram_api_key.clone(),
+ auto_destruct_pid: cli.auto_destruct_pid,
+ vad_sensitivity: cli.vad_sensitivity.clone(),
+ disable_telemetry: cli.disable_telemetry,
+ enable_llm: cli.enable_llm,
+ enable_frame_cache: cli.enable_frame_cache,
+ capture_unfocused_windows: cli.capture_unfocused_windows,
+ video_quality: cli.video_quality.clone(),
+ enable_ui_events: cli.enable_ui_events,
+ enable_sync: cli.enable_sync,
+ sync_token: cli.sync_token.clone(),
+ sync_password: cli.sync_password.clone(),
+ sync_interval_secs: cli.sync_interval_secs,
+ sync_machine_id: cli.sync_machine_id.clone(),
+ }
+ }
+
+ pub fn unique_languages(&self) -> Result<Vec<Language>, String> {
+ let mut unique_langs = std::collections::HashSet::new();
+ for lang in &self.language {
+ if !unique_langs.insert(lang.clone()) {
+ // continue don't care
+ }
+ }
+ Ok(unique_langs.into_iter().collect())
+ }
+
+ /// Create UI recorder configuration from record arguments
+ #[cfg(feature = "ui-events")]
+ pub fn to_ui_recorder_config(&self) -> crate::ui_recorder::UiRecorderConfig {
+ crate::ui_recorder::UiRecorderConfig {
+ enabled: self.enable_ui_events,
+ excluded_windows: self.ignored_windows.clone(),
+ ..Default::default()
+ }
+ }
+
+ #[cfg(not(feature = "ui-events"))]
+ pub fn to_ui_recorder_config(&self) -> crate::ui_recorder::UiRecorderConfig {
+ crate::ui_recorder::UiRecorderConfig { enabled: false }
+ }
+}
+
+// =============================================================================
+// Pipe commands (unimplemented — will be built by pipes agent, see #2213)
+// =============================================================================
+
+#[derive(Subcommand)]
+pub enum PipeCommand {
+ /// List all pipes
+ List {
/// Output format
- #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Text)]
- output: OutputFormat,
- /// Regex pattern to filter files (e.g. "monitor.*\.mp4$")
- #[arg(long)]
- pattern: Option<String>,
- /// OCR engine to use
- #[arg(short = 'o', long, value_enum)]
- ocr_engine: Option<CliOcrEngine>,
- /// Path to JSON file containing metadata overrides
- #[arg(long, value_hint = ValueHint::FilePath)]
- metadata_override: Option<PathBuf>,
- /// Copy videos to screenpipe data directory
- #[arg(long, default_value_t = true)]
- copy_videos: bool,
- /// Enable debug logging for screenpipe modules
- #[arg(long)]
- debug: bool,
- /// Enable embedding generation for OCR text
#[arg(long, default_value_t = false)]
- use_embedding: bool,
+ json: bool,
},
- /// Run data migrations in the background
- Migrate {
- /// The name of the migration to run
- #[arg(long, default_value = "ocr_text_to_frames")]
- migration_name: String,
- /// Data directory. Default to $HOME/.screenpipe
- #[arg(long, value_hint = ValueHint::DirPath)]
- data_dir: Option<String>,
- /// The subcommand for data migration
- #[command(subcommand)]
- subcommand: Option<MigrationSubCommand>,
- /// Output format
- #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Text)]
- output: OutputFormat,
- /// Batch size for processing records
- #[arg(long, default_value_t = 100_000)]
- batch_size: i64,
- /// Delay between batches in milliseconds
- #[arg(long, default_value_t = 100)]
- batch_delay_ms: u64,
- /// Continue processing if errors occur
- #[arg(long, default_value_t = true)]
- continue_on_error: bool,
+ /// Enable a pipe
+ Enable {
+ /// Pipe name
+ name: String,
+ },
+ /// Disable a pipe
+ Disable {
+ /// Pipe name
+ name: String,
},
- /// Generate shell completions
- Completions {
- /// The shell to generate completions for
- #[arg(value_enum)]
- shell: Shell,
+ /// Run a pipe once immediately
+ Run {
+ /// Pipe name
+ name: String,
+ },
+ /// Show pipe logs
+ Logs {
+ /// Pipe name
+ name: String,
+ /// Follow log output
+ #[arg(short, long, default_value_t = false)]
+ follow: bool,
+ },
+ /// Delete a pipe
+ Delete {
+ /// Pipe name
+ name: String,
},
}
-#[derive(Subcommand)]
-pub enum MigrationSubCommand {
- /// Start or resume a migration
- Start,
- /// Pause a running migration
- Pause,
- /// Stop a running migration
- Stop,
- /// Get migration status
- Status,
-}
+// =============================================================================
+// Existing subcommands (unchanged)
+// =============================================================================
#[derive(Subcommand)]
pub enum AudioCommand {
@@ -526,12 +706,6 @@ pub enum McpCommand {
},
}
-#[derive(Clone, Debug, ValueEnum, PartialEq)]
-pub enum OutputFormat {
- Text,
- Json,
-}
-
#[derive(Subcommand)]
pub enum SyncCommand {
/// Show sync status
@@ -560,13 +734,16 @@ pub enum SyncCommand {
},
}
+// =============================================================================
+// Helpers
+// =============================================================================
+
/// Get or create a persistent machine ID for sync
pub fn get_or_create_machine_id(override_id: Option<String>) -> String {
if let Some(id) = override_id {
return id;
}
- // Use hostname hash as machine ID
if let Ok(hostname) = hostname::get() {
let hostname_str = hostname.to_string_lossy();
format!("{:x}", md5::compute(hostname_str.as_bytes()))
diff --git a/crates/screenpipe-server/src/cli_pipe.rs b/crates/screenpipe-server/src/cli_pipe.rs
new file mode 100644
index 000000000..255527651
--- /dev/null
+++ b/crates/screenpipe-server/src/cli_pipe.rs
@@ -0,0 +1,46 @@
+use crate::cli::PipeCommand;
+
+/// Handle pipe subcommands.
+///
+/// NOTE: This is a placeholder. Pipe execution, scheduling, and management
+/// will be implemented as part of the pipes system (see #2213).
+/// For now, all commands print unimplemented messages.
+pub async fn handle_pipe_command(command: &PipeCommand) -> anyhow::Result<()> {
+ match command {
+ PipeCommand::List { json: _ } => {
+ eprintln!("screenpipe pipe list: not yet implemented (see #2213)");
+ }
+ PipeCommand::Enable { name } => {
+ eprintln!(
+ "screenpipe pipe enable '{}': not yet implemented (see #2213)",
+ name
+ );
+ }
+ PipeCommand::Disable { name } => {
+ eprintln!(
+ "screenpipe pipe disable '{}': not yet implemented (see #2213)",
+ name
+ );
+ }
+ PipeCommand::Run { name } => {
+ eprintln!(
+ "screenpipe pipe run '{}': not yet implemented (see #2213)",
+ name
+ );
+ }
+ PipeCommand::Logs { name, follow: _ } => {
+ eprintln!(
+ "screenpipe pipe logs '{}': not yet implemented (see #2213)",
+ name
+ );
+ }
+ PipeCommand::Delete { name } => {
+ eprintln!(
+ "screenpipe pipe delete '{}': not yet implemented (see #2213)",
+ name
+ );
+ }
+ }
+
+ Ok(())
+}
diff --git a/crates/screenpipe-server/src/cli_status.rs b/crates/screenpipe-server/src/cli_status.rs
new file mode 100644
index 000000000..a6871985b
--- /dev/null
+++ b/crates/screenpipe-server/src/cli_status.rs
@@ -0,0 +1,128 @@
+use dirs::home_dir;
+use serde_json::json;
+use sqlx::Row;
+use std::path::PathBuf;
+use tokio::net::TcpStream;
+
+pub async fn handle_status_command(
+ json: bool,
+ data_dir: &Option<String>,
+ port: u16,
+) -> anyhow::Result<()> {
+ let base_dir = get_base_dir(data_dir)?;
+ let db_path = base_dir.join("data").join("db.sqlite");
+
+ // Check if server is running
+ let running = TcpStream::connect(format!("127.0.0.1:{}", port))
+ .await
+ .is_ok();
+
+ // Get DB stats
+ let (frame_count, audio_count, last_timestamp) = if db_path.exists() {
+ match screenpipe_db::DatabaseManager::new(&db_path.to_string_lossy()).await {
+ Ok(db) => {
+ let frames: i64 = sqlx::query("SELECT COUNT(*) as cnt FROM frames")
+ .fetch_one(&db.pool)
+ .await
+ .map(|row| row.get::<i64, _>("cnt"))
+ .unwrap_or(0);
+
+ let audio: i64 =
+ sqlx::query("SELECT COUNT(*) as cnt FROM audio_transcriptions")
+ .fetch_one(&db.pool)
+ .await
+ .map(|row| row.get::<i64, _>("cnt"))
+ .unwrap_or(0);
+
+ let last: String = sqlx::query(
+ "SELECT timestamp FROM frames ORDER BY timestamp DESC LIMIT 1",
+ )
+ .fetch_optional(&db.pool)
+ .await
+ .ok()
+ .flatten()
+ .map(|row| row.get::<String, _>("timestamp"))
+ .unwrap_or_else(|| "never".to_string());
+
+ (frames, audio, last)
+ }
+ Err(_) => (0, 0, "error reading db".to_string()),
+ }
+ } else {
+ (0, 0, "no data".to_string())
+ };
+
+ // Get data dir size
+ let data_size = dir_size(&base_dir.join("data")).unwrap_or(0);
+ let data_size_human = format_bytes(data_size);
+
+ if json {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&json!({
+ "running": running,
+ "port": port,
+ "frames": frame_count,
+ "audio_transcriptions": audio_count,
+ "last_capture": last_timestamp,
+ "data_size_bytes": data_size,
+ "data_size": data_size_human,
+ "data_dir": base_dir.to_string_lossy(),
+ }))?
+ );
+ } else {
+ let status = if running { "running" } else { "not running" };
+ let status_icon = if running { "●" } else { "○" };
+ println!("screenpipe: {} {} (port {})", status_icon, status, port);
+ println!("frames: {}", frame_count);
+ println!("audio: {}", audio_count);
+ println!("last capture: {}", last_timestamp);
+ println!("data size: {}", data_size_human);
+ println!("data dir: {}", base_dir.display());
+ }
+
+ Ok(())
+}
+
+fn get_base_dir(custom_path: &Option<String>) -> anyhow::Result<PathBuf> {
+ let default_path = home_dir()
+ .ok_or_else(|| anyhow::anyhow!("failed to get home directory"))?
+ .join(".screenpipe");
+
+ Ok(custom_path
+ .as_ref()
+ .map(PathBuf::from)
+ .unwrap_or(default_path))
+}
+
+fn dir_size(path: &PathBuf) -> std::io::Result<u64> {
+ let mut size = 0;
+ if path.is_dir() {
+ for entry in std::fs::read_dir(path)? {
+ let entry = entry?;
+ let metadata = entry.metadata()?;
+ if metadata.is_dir() {
+ size += dir_size(&entry.path())?;
+ } else {
+ size += metadata.len();
+ }
+ }
+ }
+ Ok(size)
+}
+
+fn format_bytes(bytes: u64) -> String {
+ const KB: u64 = 1024;
+ const MB: u64 = KB * 1024;
+ const GB: u64 = MB * 1024;
+
+ if bytes >= GB {
+ format!("{:.1} GB", bytes as f64 / GB as f64)
+ } else if bytes >= MB {
+ format!("{:.1} MB", bytes as f64 / MB as f64)
+ } else if bytes >= KB {
+ format!("{:.1} KB", bytes as f64 / KB as f64)
+ } else {
+ format!("{} B", bytes)
+ }
+}
diff --git a/crates/screenpipe-server/src/lib.rs b/crates/screenpipe-server/src/lib.rs
index a844ea95f..6ba44911d 100644
--- a/crates/screenpipe-server/src/lib.rs
+++ b/crates/screenpipe-server/src/lib.rs
@@ -8,6 +8,8 @@ mod apple_intelligence_api;
mod auto_destruct;
pub mod chunking;
pub mod cli;
+pub mod cli_pipe;
+pub mod cli_status;
pub mod cloud_search;
pub mod core;
pub mod filtering;
@@ -24,7 +26,6 @@ mod video;
pub mod video_cache;
pub mod video_utils;
pub mod vision_manager;
-pub use add::handle_index_command;
pub use auto_destruct::watch_pid;
pub use axum::Json as JsonResponse;
pub use cli::Cli;
diff --git a/crates/screenpipe-server/tests/index_test.rs b/crates/screenpipe-server/tests/index_test.rs
deleted file mode 100644
index c2268e272..000000000
--- a/crates/screenpipe-server/tests/index_test.rs
+++ /dev/null
@@ -1,165 +0,0 @@
-use std::{
- path::{Path, PathBuf},
- sync::Arc,
-};
-
-use anyhow::Result;
-use dirs::home_dir;
-use screenpipe_db::DatabaseManager;
-use screenpipe_server::{cli::OutputFormat, handle_index_command};
-use tempfile::tempdir;
-use tokio::fs;
-use tracing::debug;
-
-async fn setup_test_env() -> Result<()> {
- tracing_subscriber::fmt()
- .with_max_level(tracing::Level::DEBUG)
- .init();
- Ok(())
-}
-
-async fn setup_test_db() -> Result<(tempfile::TempDir, Arc<DatabaseManager>)> {
- let temp_dir = tempdir()?;
- let db_path = temp_dir.path().join("test.db");
- let db = Arc::new(DatabaseManager::new(&db_path.to_string_lossy()).await?);
- Ok((temp_dir, db))
-}
-
-async fn copy_test_video(temp_dir: &Path) -> Result<PathBuf> {
- // Find a small video file from .screenpipe
- let screenpipe_dir = home_dir()
- .expect("couldn't find home dir")
- .join(".screenpipe")
- .join("data");
-
- let mut entries = fs::read_dir(&screenpipe_dir).await?;
- let mut source_video = None;
-
- while let Some(entry) = entries.next_entry().await? {
- let path = entry.path();
- if let Some(ext) = path.extension() {
- if ext == "mp4"
- && fs::metadata(&path).await?.len() < 100_000_000
- && path.to_string_lossy().to_lowercase().contains("monitor")
- {
- source_video = Some(path);
- break;
- }
- }
- }
-
- let source_path =
- source_video.ok_or_else(|| anyhow::anyhow!("no suitable test video found"))?;
- let target_path = temp_dir.join("test_video.mp4");
-
- fs::copy(&source_path, &target_path).await?;
- println!("copied test video to {}", target_path.display());
- Ok(target_path)
-}
-
-#[tokio::test]
-#[ignore]
-async fn test_index_command_with_sql() -> Result<()> {
- setup_test_env().await?;
-
- let (temp_dir, db) = setup_test_db().await?;
- let video_path = copy_test_video(temp_dir.path()).await?;
-
- debug!("testing indexing with video at {}", video_path.display());
-
- // Run indexing
- handle_index_command(
- temp_dir.path().into(),
- video_path.to_str().unwrap().to_string(),
- None,
- db.clone(),
- OutputFormat::Text,
- Some(screenpipe_server::cli::CliOcrEngine::Custom),
- None,
- false,
- false,
- )
- .await?;
-
- // Check video_chunks table
- let video_chunks = db
- .execute_raw_sql("SELECT * FROM video_chunks WHERE file_path LIKE '%test_video.mp4'")
- .await?;
- debug!(
- "video chunks: {}",
- serde_json::to_string_pretty(&video_chunks)?
- );
- assert!(
- !video_chunks.as_array().unwrap().is_empty(),
- "should have video chunk entry"
- );
-
- // Check frames table
- let frames = db
- .execute_raw_sql(
- "SELECT COUNT(*) as frame_count FROM frames f
- JOIN video_chunks vc ON f.video_chunk_id = vc.id
- WHERE vc.file_path LIKE '%test_video.mp4'",
- )
- .await?;
- debug!("frames: {}", serde_json::to_string_pretty(&frames)?);
- assert!(
- frames.as_array().unwrap()[0]["frame_count"]
- .as_i64()
- .unwrap()
- > 0,
- "should have frames"
- );
-
- // Check OCR results
- let ocr_results = db
- .execute_raw_sql(
- "SELECT COUNT(*) as ocr_count FROM ocr_text ot
- JOIN frames f ON ot.frame_id = f.id
- JOIN video_chunks vc ON f.video_chunk_id = vc.id
- WHERE vc.file_path LIKE '%test_video.mp4'",
- )
- .await?;
- debug!(
- "ocr results: {}",
- serde_json::to_string_pretty(&ocr_results)?
- );
- assert!(
- ocr_results.as_array().unwrap()[0]["ocr_count"]
- .as_i64()
- .unwrap()
- > 0,
- "should have OCR results"
- );
-
- // Check timestamps are valid
- let timestamps = db
- .execute_raw_sql(
- "SELECT f.timestamp FROM frames f
- JOIN video_chunks vc ON f.video_chunk_id = vc.id
- WHERE vc.file_path LIKE '%test_video.mp4'",
- )
- .await?;
- debug!("timestamps: {}", serde_json::to_string_pretty(&timestamps)?);
- assert!(
- !timestamps.as_array().unwrap().is_empty(),
- "should have timestamps"
- );
-
- // Check OCR text content
- let ocr_text = db
- .execute_raw_sql(
- "SELECT ot.text, ot.app_name, ot.window_name FROM ocr_text ot
- JOIN frames f ON ot.frame_id = f.id
- JOIN video_chunks vc ON f.video_chunk_id = vc.id
- WHERE vc.file_path LIKE '%test_video.mp4'
- LIMIT 5",
- )
- .await?;
- debug!(
- "sample ocr text: {}",
- serde_json::to_string_pretty(&ocr_text)?
- );
-
- Ok(())
-}
diff --git a/packages/cli/README.md b/packages/cli/README.md
new file mode 100644
index 000000000..7b894d2de
--- /dev/null
+++ b/packages/cli/README.md
@@ -0,0 +1,41 @@
+# screenpipe CLI (npm)
+
+Install and run the screenpipe CLI via npm/bun.
+
+## Usage
+
+```bash
+# Run directly (downloads binary on first use)
+npx screenpipe status --json
+bunx screenpipe status --json
+
+# Or install globally
+npm install -g screenpipe
+screenpipe record --fps 1
+screenpipe status
+screenpipe pipe list
+```
+
+## How it works
+
+The `screenpipe` npm package is a thin wrapper around the platform-specific binary.
+Platform packages (`@screenpipe/cli-darwin-arm64`, etc.) contain the actual compiled
+Rust binary. npm/bun automatically installs only the package matching your platform.
+
+## Publishing (CI)
+
+After a release build, copy the binary into the platform package and publish:
+
+```bash
+# Example for darwin-arm64
+cp target/aarch64-apple-darwin/release/screenpipe packages/cli/screenpipe-darwin-arm64/bin/
+cd packages/cli/screenpipe-darwin-arm64 && npm publish --access public
+cd packages/cli/screenpipe && npm publish --access public
+```
+
+## Supported platforms
+
+- macOS ARM64 (Apple Silicon)
+- macOS x64 (Intel)
+- Linux x64
+- Windows x64
diff --git a/packages/cli/screenpipe-darwin-arm64/package.json b/packages/cli/screenpipe-darwin-arm64/package.json
new file mode 100644
index 000000000..9b6ee68ae
--- /dev/null
+++ b/packages/cli/screenpipe-darwin-arm64/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@screenpipe/cli-darwin-arm64",
+ "version": "0.1.0",
+ "description": "screenpipe CLI binary for macOS ARM64",
+ "os": ["darwin"],
+ "cpu": ["arm64"],
+ "bin": {
+ "screenpipe": "bin/screenpipe"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/screenpipe/screenpipe"
+ },
+ "license": "MIT"
+}
diff --git a/packages/cli/screenpipe-darwin-x64/package.json b/packages/cli/screenpipe-darwin-x64/package.json
new file mode 100644
index 000000000..65a79ce95
--- /dev/null
+++ b/packages/cli/screenpipe-darwin-x64/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@screenpipe/cli-darwin-x64",
+ "version": "0.1.0",
+ "description": "screenpipe CLI binary for macOS x64",
+ "os": ["darwin"],
+ "cpu": ["x64"],
+ "bin": {
+ "screenpipe": "bin/screenpipe"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/screenpipe/screenpipe"
+ },
+ "license": "MIT"
+}
diff --git a/packages/cli/screenpipe-linux-x64/package.json b/packages/cli/screenpipe-linux-x64/package.json
new file mode 100644
index 000000000..203d22265
--- /dev/null
+++ b/packages/cli/screenpipe-linux-x64/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@screenpipe/cli-linux-x64",
+ "version": "0.1.0",
+ "description": "screenpipe CLI binary for Linux x64",
+ "os": ["linux"],
+ "cpu": ["x64"],
+ "bin": {
+ "screenpipe": "bin/screenpipe"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/screenpipe/screenpipe"
+ },
+ "license": "MIT"
+}
diff --git a/packages/cli/screenpipe-win32-x64/package.json b/packages/cli/screenpipe-win32-x64/package.json
new file mode 100644
index 000000000..8d574c106
--- /dev/null
+++ b/packages/cli/screenpipe-win32-x64/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@screenpipe/cli-win32-x64",
+ "version": "0.1.0",
+ "description": "screenpipe CLI binary for Windows x64",
+ "os": ["win32"],
+ "cpu": ["x64"],
+ "bin": {
+ "screenpipe": "bin/screenpipe.exe"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/screenpipe/screenpipe"
+ },
+ "license": "MIT"
+}
diff --git a/packages/cli/screenpipe/bin/screenpipe.js b/packages/cli/screenpipe/bin/screenpipe.js
new file mode 100644
index 000000000..d6cf8ba2a
--- /dev/null
+++ b/packages/cli/screenpipe/bin/screenpipe.js
@@ -0,0 +1,80 @@
+#!/usr/bin/env node
+
+const { execFileSync, execSync } = require("child_process");
+const { join, dirname } = require("path");
+const { existsSync, chmodSync } = require("fs");
+
+const PLATFORMS = {
+ "darwin-arm64": "@screenpipe/cli-darwin-arm64",
+ "darwin-x64": "@screenpipe/cli-darwin-x64",
+ "linux-x64": "@screenpipe/cli-linux-x64",
+ "win32-x64": "@screenpipe/cli-win32-x64",
+};
+
+const key = `${process.platform}-${process.arch}`;
+const pkg = PLATFORMS[key];
+
+if (!pkg) {
+ console.error(`screenpipe: unsupported platform ${key}`);
+ console.error(`supported: ${Object.keys(PLATFORMS).join(", ")}`);
+ process.exit(1);
+}
+
+let binPath;
+try {
+ const pkgPath = require.resolve(`${pkg}/package.json`);
+ const ext = process.platform === "win32" ? ".exe" : "";
+ binPath = join(dirname(pkgPath), "bin", `screenpipe${ext}`);
+} catch {
+ console.error(`screenpipe: platform package ${pkg} not installed`);
+ console.error(`run: npm install screenpipe (or: bun install screenpipe)`);
+ process.exit(1);
+}
+
+if (!existsSync(binPath)) {
+ console.error(`screenpipe: binary not found at ${binPath}`);
+ console.error(`the platform package may be corrupted. try reinstalling.`);
+ process.exit(1);
+}
+
+// macOS: remove quarantine attribute (Gatekeeper) and ensure executable
+if (process.platform === "darwin") {
+ try {
+ execSync(`xattr -d com.apple.quarantine "${binPath}" 2>/dev/null || true`);
+ } catch {}
+ try {
+ chmodSync(binPath, 0o755);
+ } catch {}
+}
+
+// Linux: ensure executable
+if (process.platform === "linux") {
+ try {
+ chmodSync(binPath, 0o755);
+ } catch {}
+}
+
+try {
+ execFileSync(binPath, process.argv.slice(2), { stdio: "inherit" });
+} catch (e) {
+ if (e.status !== undefined) {
+ process.exit(e.status);
+ }
+
+ // Helpful error messages for common failures
+ const msg = (e.message || "").toLowerCase();
+ if (process.platform === "darwin" && msg.includes("eperm")) {
+ console.error(`\nscreenpipe: macOS blocked the binary.`);
+ console.error(`go to System Settings > Privacy & Security and allow screenpipe.`);
+ console.error(`or run: xattr -d com.apple.quarantine "${binPath}"`);
+ } else if (process.platform === "linux" && msg.includes("enoent")) {
+ console.error(`\nscreenpipe: missing system libraries.`);
+ console.error(`try: sudo apt install libasound2-dev ffmpeg (ubuntu/debian)`);
+ console.error(` sudo dnf install alsa-lib ffmpeg (fedora)`);
+ } else if (process.platform === "win32" && msg.includes("onnxruntime")) {
+ console.error(`\nscreenpipe: missing onnxruntime.dll`);
+ console.error(`check that it's alongside screenpipe.exe in the package.`);
+ }
+
+ process.exit(e.status || 1);
+}
diff --git a/packages/cli/screenpipe/package.json b/packages/cli/screenpipe/package.json
new file mode 100644
index 000000000..335f474ff
--- /dev/null
+++ b/packages/cli/screenpipe/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "screenpipe",
+ "version": "0.1.0",
+ "description": "screenpipe CLI — AI that knows everything you've seen, said, or heard",
+ "bin": {
+ "screenpipe": "bin/screenpipe.js"
+ },
+ "scripts": {
+ "postinstall": "sh scripts/postinstall.sh || true"
+ },
+ "optionalDependencies": {
+ "@screenpipe/cli-darwin-arm64": "0.1.0",
+ "@screenpipe/cli-darwin-x64": "0.1.0",
+ "@screenpipe/cli-linux-x64": "0.1.0",
+ "@screenpipe/cli-win32-x64": "0.1.0"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/screenpipe/screenpipe"
+ },
+ "license": "MIT",
+ "keywords": ["screenpipe", "screen-recording", "ai", "memory", "cli"]
+}
diff --git a/packages/cli/screenpipe/scripts/postinstall.sh b/packages/cli/screenpipe/scripts/postinstall.sh
new file mode 100755
index 000000000..39c4f7457
--- /dev/null
+++ b/packages/cli/screenpipe/scripts/postinstall.sh
@@ -0,0 +1,114 @@
+#!/bin/sh
+# postinstall script — ensures runtime dependencies are present
+# Runs automatically after `npm install screenpipe` or `bunx screenpipe`
+
+set -e
+
+check_ffmpeg() {
+ if command -v ffmpeg >/dev/null 2>&1; then
+ return 0
+ fi
+ return 1
+}
+
+install_ffmpeg_macos() {
+ arch=$(uname -m)
+ if [ "$arch" = "arm64" ]; then
+ FFMPEG_URL="https://ffmpeg.martin-riedl.de/redirect/latest/macos/arm64/release/ffmpeg.zip"
+ else
+ FFMPEG_URL="https://ffmpeg.martin-riedl.de/redirect/latest/macos/amd64/release/ffmpeg.zip"
+ fi
+
+ echo "screenpipe: downloading ffmpeg..."
+ TMP_DIR=$(mktemp -d)
+ if curl -sL "$FFMPEG_URL" -o "$TMP_DIR/ffmpeg.zip"; then
+ cd "$TMP_DIR"
+ unzip -q ffmpeg.zip
+ mkdir -p "$HOME/.local/bin"
+ mv ffmpeg "$HOME/.local/bin/"
+ chmod +x "$HOME/.local/bin/ffmpeg"
+ xattr -d com.apple.quarantine "$HOME/.local/bin/ffmpeg" 2>/dev/null || true
+ cd - >/dev/null
+ rm -rf "$TMP_DIR"
+ echo "screenpipe: ffmpeg installed to ~/.local/bin/ffmpeg"
+ else
+ echo "screenpipe: warning: failed to download ffmpeg"
+ echo "screenpipe: install it manually: brew install ffmpeg"
+ fi
+}
+
+install_ffmpeg_linux() {
+ if command -v apt-get >/dev/null 2>&1; then
+ echo "screenpipe: installing ffmpeg via apt..."
+ sudo apt-get install -qq -y ffmpeg 2>/dev/null || echo "screenpipe: warning: failed to install ffmpeg (try: sudo apt install ffmpeg)"
+ elif command -v dnf >/dev/null 2>&1; then
+ echo "screenpipe: installing ffmpeg via dnf..."
+ sudo dnf install -q -y ffmpeg 2>/dev/null || echo "screenpipe: warning: failed to install ffmpeg (try: sudo dnf install ffmpeg)"
+ elif command -v pacman >/dev/null 2>&1; then
+ echo "screenpipe: installing ffmpeg via pacman..."
+ sudo pacman -S --noconfirm --quiet ffmpeg 2>/dev/null || echo "screenpipe: warning: failed to install ffmpeg (try: sudo pacman -S ffmpeg)"
+ else
+ echo "screenpipe: warning: ffmpeg not found. install it manually."
+ fi
+}
+
+install_linux_deps() {
+ # Check for libasound
+ if ! ldconfig -p 2>/dev/null | grep -q "libasound.so.2"; then
+ if command -v apt-get >/dev/null 2>&1; then
+ echo "screenpipe: installing libasound2-dev..."
+ sudo apt-get install -qq -y libasound2-dev 2>/dev/null || true
+ elif command -v dnf >/dev/null 2>&1; then
+ sudo dnf install -q -y alsa-lib 2>/dev/null || true
+ elif command -v pacman >/dev/null 2>&1; then
+ sudo pacman -S --noconfirm --quiet alsa-lib 2>/dev/null || true
+ fi
+ fi
+}
+
+# Remove macOS quarantine from the binary
+remove_quarantine() {
+ if [ "$(uname)" = "Darwin" ]; then
+ # Find the platform package binary
+ SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
+ PKG_DIR=$(dirname "$SCRIPT_DIR")
+ NODE_MODULES=$(dirname "$PKG_DIR")
+ for pkg in "@screenpipe/cli-darwin-arm64" "@screenpipe/cli-darwin-x64"; do
+ BIN="$NODE_MODULES/$pkg/bin/screenpipe"
+ if [ -f "$BIN" ]; then
+ xattr -d com.apple.quarantine "$BIN" 2>/dev/null || true
+ fi
+ done
+ fi
+}
+
+# Main
+OS=$(uname -s | tr '[:upper:]' '[:lower:]')
+
+if ! check_ffmpeg; then
+ case "$OS" in
+ darwin) install_ffmpeg_macos ;;
+ linux) install_ffmpeg_linux ;;
+ esac
+fi
+
+if [ "$OS" = "linux" ]; then
+ install_linux_deps
+fi
+
+remove_quarantine
+
+# PostHog install tracking (non-blocking)
+curl -sL -X POST https://eu.i.posthog.com/capture/ \
+ -H "Content-Type: application/json" \
+ -d '{
+ "api_key": "phc_Bt8GoTBPgkCpDrbaIZzJIEYt0CrJjhBiuLaBck1clce",
+ "event": "cli_install_npm",
+ "properties": {
+ "distinct_id": "'$(hostname)'",
+ "os": "'$OS'",
+ "arch": "'$(uname -m)'"
+ }
+ }' >/dev/null 2>&1 || true
+
+echo "screenpipe: ready! run: screenpipe status"