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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat: add pipe management as CLI subcommand
Louis Beaumont1ab3ee455737
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex f71342f08..0d7e7770c 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -22,11 +22,12 @@ use screenpipe_audio::{};use screenpipe_core::find_ffmpeg_path;use screenpipe_server::{- cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine},+ cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand},start_continuous_recording, DatabaseManager, PipeManager, ResourceMonitor, Server,};use screenpipe_vision::monitor::{get_monitor_by_id, list_monitors};use screenpipe_vision::utils::OcrEngine as CoreOcrEngine;+use serde_json::{json, Value};use tokio::{signal,sync::mpsc::channel,@@ -76,6 +77,17 @@ async fn main() -> anyhow::Result<()> {let local_data_dir = get_base_dir(cli.data_dir)?;let local_data_dir_clone = local_data_dir.clone();+ let pipe_manager = Arc::new(PipeManager::new(local_data_dir_clone.clone()));++ if let Some(pipe_command) = cli.command {+ match pipe_command {+ Command::Pipe { subcommand } => {+ handle_pipe_command(subcommand, &pipe_manager).await?;+ return Ok(());+ }+ }+ }+if find_ffmpeg_path().is_none() {eprintln!("ffmpeg not found. Please install ffmpeg and ensure it is in your PATH.");std::process::exit(1);@@ -344,7 +356,6 @@ async fn main() -> anyhow::Result<()> {});let local_data_dir_clone_2 = local_data_dir_clone.clone();- let pipe_manager = Arc::new(PipeManager::new(local_data_dir_clone.clone()));let api_plugin = |req: &axum::http::Request<axum::body::Body>| {// Custom plugin logic here@@ -524,3 +535,51 @@ async fn main() -> anyhow::Result<()> {info!("Shutdown complete");Ok(())}++async fn handle_pipe_command(pipe: PipeCommand, pipe_manager: &PipeManager) -> anyhow::Result<()> {+ // Handle pipe subcommands+ match pipe {+ PipeCommand::List => {+ let pipes = pipe_manager.list_pipes().await;+ println!("Available pipes:");+ for pipe in pipes {+ println!(" ID: {}, Enabled: {}", pipe.id, pipe.enabled);+ }+ }+ PipeCommand::Download { url } => match pipe_manager.download_pipe(&url).await {+ Ok(pipe_id) => println!("Pipe downloaded successfully. ID: {}", pipe_id),+ Err(e) => eprintln!("Failed to download pipe: {}", e),+ },+ PipeCommand::Info { id } => match pipe_manager.get_pipe_info(&id).await {+ Some(info) => println!("Pipe info: {:?}", info),+ None => eprintln!("Pipe not found"),+ },+ PipeCommand::Enable { id } => {+ match pipe_manager+ .update_config(&id, json!({"enabled": true}))+ .await+ {+ Ok(_) => println!("Pipe {} enabled", id),+ Err(e) => eprintln!("Failed to enable pipe: {}", e),+ }+ }+ PipeCommand::Disable { id } => {+ match pipe_manager+ .update_config(&id, json!({"enabled": false}))+ .await+ {+ Ok(_) => println!("Pipe {} disabled", id),+ Err(e) => eprintln!("Failed to disable pipe: {}", e),+ }+ }+ PipeCommand::Update { id, config } => {+ let config: Value = serde_json::from_str(&config)+ .map_err(|e| anyhow::anyhow!("Invalid JSON: {}", e))?;+ match pipe_manager.update_config(&id, config).await {+ Ok(_) => println!("Pipe {} config updated", id),+ Err(e) => eprintln!("Failed to update pipe config: {}", e),+ }+ }+ }+ return Ok(());+}diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rsindex 10507d447..b073c14a2 100644--- a/screenpipe-server/src/cli.rs+++ b/screenpipe-server/src/cli.rs@@ -1,4 +1,4 @@-use clap::Parser;+use clap::{Parser, Subcommand};use screenpipe_audio::AudioTranscriptionEngine as CoreAudioTranscriptionEngine;use screenpipe_vision::utils::OcrEngine as CoreOcrEngine;use clap::ValueEnum;@@ -150,4 +150,51 @@ pub struct Cli {/// Disable vision recording#[arg(long, default_value_t = false)]pub disable_vision: bool,++ #[command(subcommand)]+ pub command: Option<Command>,+}++#[derive(Subcommand)]+pub enum Command {+ /// Pipe management commands+ Pipe {+ #[command(subcommand)]+ subcommand: PipeCommand,+ },+ // ... (other top-level commands if any)+}+++#[derive(Subcommand)]+pub enum PipeCommand {+ /// List all pipes+ List,+ /// Download a new pipe+ Download {+ /// URL of the pipe to download+ url: String,+ },+ /// Get info for a specific pipe+ Info {+ /// ID of the pipe+ id: String,+ },+ /// Enable a pipe+ Enable {+ /// ID of the pipe to enable+ id: String,+ },+ /// Disable a pipe+ Disable {+ /// ID of the pipe to disable+ id: String,+ },+ /// Update pipe configuration+ Update {+ /// ID of the pipe to update+ id: String,+ /// New configuration as a JSON string+ config: String,+ },}\ No newline at end of filediff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex cc5b15a80..e12b0133a 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -4,6 +4,7 @@ pub mod core;mod db;pub mod filtering;pub mod logs;+mod pipe_manager;mod plugin;mod resource_monitor;mod server;@@ -13,6 +14,7 @@ pub use cli::Cli;pub use core::start_continuous_recording;pub use db::{ContentSource, ContentType, DatabaseManager, SearchResult};pub use logs::MultiWriter;+pub use pipe_manager::PipeManager;pub use resource_monitor::{ResourceMonitor, RestartSignal};pub use server::create_router;pub use server::health_check;@@ -20,6 +22,5 @@ pub use server::AppState;pub use server::ContentItem;pub use server::HealthCheckResponse;pub use server::PaginatedResponse;-pub use server::PipeManager;pub use server::Server;pub use video::VideoCapture;diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rsnew file mode 100644index 000000000..896d196ec--- /dev/null+++ b/screenpipe-server/src/pipe_manager.rs@@ -0,0 +1,124 @@+use anyhow::Result;+use log::{debug, error};+use screenpipe_core::{download_pipe, run_pipe};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::future::Future;+use std::path::PathBuf;+use tokio::fs::File;+use tokio::io::AsyncWriteExt;++#[derive(Clone, Serialize, Deserialize, Debug)]+pub struct PipeInfo {+ pub id: String,+ pub enabled: bool,+ pub config: Value,+}++pub struct PipeManager {+ screenpipe_dir: PathBuf,+}++impl PipeManager {+ pub fn new(screenpipe_dir: PathBuf) -> Self {+ PipeManager { screenpipe_dir }+ }++ pub async fn start_pipe(+ &self,+ id: &str,+ ) -> Result<impl Future<Output = Result<(), anyhow::Error>>> {+ let pipes = self.list_pipes().await;++ if let Some(_) = pipes.iter().find(|pipe| pipe.id == id) {+ let pipe_id = id.to_string();+ let screenpipe_dir = self.screenpipe_dir.clone();++ let future = run_pipe(pipe_id.clone(), screenpipe_dir);++ self.update_config(+ id,+ serde_json::json!({+ "enabled": true,+ }),+ )+ .await?;++ Ok(future)+ } else {+ Err(anyhow::anyhow!("Pipe not found"))+ }+ }++ pub async fn update_config(&self, id: &str, new_config: Value) -> Result<()> {+ debug!("Updating config for pipe: {}", id);+ let pipe_dir = self.screenpipe_dir.join("pipes").join(id);+ let config_path = pipe_dir.join("pipe.json");++ let config_str = tokio::fs::read_to_string(&config_path).await?;+ let mut config: Value = serde_json::from_str(&config_str)?;++ if let Value::Object(existing_config) = &mut config {+ if let Value::Object(updates) = new_config {+ for (key, value) in updates {+ existing_config.insert(key, value);+ }+ } else {+ return Err(anyhow::anyhow!("New configuration must be an object"));+ }+ } else {+ return Err(anyhow::anyhow!("Existing configuration is not an object"));+ }++ let updated_config_str = serde_json::to_string_pretty(&config)?;++ let mut file = File::create(&config_path).await?;+ file.write_all(updated_config_str.as_bytes()).await?;++ Ok(())+ }++ pub async fn get_pipe_info(&self, id: &str) -> Option<PipeInfo> {+ let pipes = self.list_pipes().await;+ pipes.iter().find(|pipe| pipe.id == id).cloned()+ }++ pub async fn list_pipes(&self) -> Vec<PipeInfo> {+ let pipe_dir = self.screenpipe_dir.join("pipes");+ let mut pipe_infos = Vec::new();++ if let Ok(mut entries) = tokio::fs::read_dir(pipe_dir).await {+ while let Ok(Some(entry)) = entries.next_entry().await {+ let pipe_id = entry.file_name().to_string_lossy().into_owned();+ let config_path = entry.path().join("pipe.json");+ pipe_infos.push(async move {+ let config = tokio::fs::read_to_string(config_path).await?;+ let config: Value = serde_json::from_str(&config)?;+ debug!("Pipe config: {:?}", config);+ Ok::<_, anyhow::Error>(PipeInfo {+ id: pipe_id,+ enabled: config+ .get("enabled")+ .unwrap_or(&Value::Bool(false))+ .as_bool()+ .unwrap_or(false),+ config,+ })+ });+ }+ }++ match futures::future::try_join_all(pipe_infos).await {+ Ok(infos) => infos,+ Err(e) => {+ error!("Error listing pipes: {}", e);+ Vec::new()+ }+ }+ }++ pub async fn download_pipe(&self, url: &str) -> Result<String> {+ let pipe_dir = download_pipe(url, self.screenpipe_dir.clone()).await?;+ Ok(pipe_dir.file_name().unwrap().to_string_lossy().into_owned())+ }+}diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex f348e6924..85372a630 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -7,10 +7,14 @@ use axum::{};use crossbeam::queue::SegQueue;use futures::future::try_join_all;-use screenpipe_core::{download_pipe, run_pipe};+use screenpipe_core::download_pipe;use screenpipe_vision::monitor::list_monitors;-use crate::{db::TagContentType, ContentType, DatabaseManager, SearchResult};+use crate::{+ db::TagContentType,+ pipe_manager::{PipeInfo, PipeManager},+ ContentType, DatabaseManager, SearchResult,+};use crate::{plugin::ApiPluginLayer, video_utils::extract_frame};use chrono::{DateTime, Utc};use log::{debug, error, info};@@ -21,15 +25,13 @@ use serde::{Deserialize, Serialize};use serde_json::{json, Value};use std::{collections::HashMap,- future::Future,net::SocketAddr,path::PathBuf,sync::{atomic::AtomicBool, Arc},time::Duration,};-use tokio::io::AsyncWriteExt;-use tokio::{fs::File, net::TcpListener};+use tokio::net::TcpListener;use tower_http::trace::TraceLayer;use tower_http::{cors::CorsLayer, trace::DefaultMakeSpan};@@ -525,130 +527,6 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He})}-// New structs for pipe management-#[derive(Clone, Serialize)]-pub struct PipeInfo {- pub id: String,- pub enabled: bool,- pub config: serde_json::Value,-}--pub struct PipeManager {- screenpipe_dir: PathBuf,-}--impl PipeManager {- pub fn new(screenpipe_dir: PathBuf) -> Self {- PipeManager { screenpipe_dir }- }-- pub async fn start_pipe(- &self,- id: &str,- ) -> Result<impl Future<Output = Result<(), anyhow::Error>>, String> {- let pipes = self.list_pipes().await;-- if let Some(_) = pipes.iter().find(|pipe| pipe.id == id) {- let pipe_id = id.to_string();- let screenpipe_dir = self.screenpipe_dir.clone();-- let future = run_pipe(pipe_id.clone(), screenpipe_dir);-- self.update_config(- id,- serde_json::json!({- "enabled": true,- }),- )- .await?;-- Ok(future)- } else {- Err("Pipe not found".to_string())- }- }-- async fn update_config(&self, id: &str, new_config: Value) -> Result<(), String> {- info!("Updating config for pipe: {}", id);- let pipe_dir = self.screenpipe_dir.join("pipes").join(id);- let config_path = pipe_dir.join("pipe.json");-- // Read the existing config- let config_str = tokio::fs::read_to_string(&config_path)- .await- .map_err(|e| format!("Failed to read pipe config: {}", e))?;-- let mut config: Value = serde_json::from_str(&config_str)- .map_err(|e| format!("Failed to parse pipe config: {}", e))?;-- // Update the config- if let Value::Object(existing_config) = &mut config {- if let Value::Object(updates) = new_config {- for (key, value) in updates {- existing_config.insert(key, value);- }- } else {- return Err("New configuration must be an object".to_string());- }- } else {- return Err("Existing configuration is not an object".to_string());- }-- // Write the updated config back to the file- let updated_config_str = serde_json::to_string_pretty(&config)- .map_err(|e| format!("Failed to serialize updated config: {}", e))?;-- let mut file = File::create(&config_path)- .await- .map_err(|e| format!("Failed to open pipe config file for writing: {}", e))?;-- file.write_all(updated_config_str.as_bytes())- .await- .map_err(|e| format!("Failed to write updated config: {}", e))?;-- Ok(())- }-- async fn get_pipe_info(&self, id: &str) -> Option<PipeInfo> {- let pipes = self.list_pipes().await;- pipes.iter().find(|pipe| pipe.id == id).cloned()- }-- pub async fn list_pipes(&self) -> Vec<PipeInfo> {- let pipe_dir = self.screenpipe_dir.join("pipes");- let mut pipe_infos = Vec::new();-- if let Ok(mut entries) = tokio::fs::read_dir(pipe_dir).await {- while let Ok(Some(entry)) = entries.next_entry().await {- let pipe_id = entry.file_name().to_string_lossy().into_owned();- let config_path = entry.path().join("pipe.json");- pipe_infos.push(async move {- let config = tokio::fs::read_to_string(config_path).await?;- let config: Value = serde_json::from_str(&config)?;- debug!("Pipe config: {:?}", config);- Ok::<_, anyhow::Error>(PipeInfo {- id: pipe_id,- enabled: config- .get("enabled")- .unwrap_or(&Value::Bool(false))- .as_bool()- .unwrap_or(false),- config,- })- });- }- }-- match try_join_all(pipe_infos).await {- Ok(infos) => infos,- Err(e) => {- error!("Error listing pipes: {}", e);- Vec::new()- }- }- }-}-// Request and response structs#[derive(Deserialize)]struct DownloadPipeRequest {@@ -715,7 +593,7 @@ async fn run_pipe_handler("message": format!("Pipe {} started", payload.pipe_id),"pipe_id": payload.pipe_id}))),- Err(e) => Err((StatusCode::BAD_REQUEST, e)),+ Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())),}}@@ -738,7 +616,7 @@ async fn stop_pipe_handler("message": format!("Pipe {} stopped", payload.pipe_id),"pipe_id": payload.pipe_id}))),- Err(e) => Err((StatusCode::BAD_REQUEST, e)),+ Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())),}}@@ -756,7 +634,7 @@ async fn update_pipe_config_handler("message": format!("Pipe {} config updated", payload.pipe_id),"pipe_id": payload.pipe_id}))),- Err(e) => Err((StatusCode::BAD_REQUEST, e)),+ Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())),}}