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

it works

Louis Beaumontf27f6a6f4800
diff --git a/examples/typescript/pipe-activity-topic-tracker/main.js b/examples/typescript/pipe-activity-topic-tracker/main.js
index f0a51d0e7..95fc1575f 100644
--- a/examples/typescript/pipe-activity-topic-tracker/main.js
+++ b/examples/typescript/pipe-activity-topic-tracker/main.js
@@ -1,33 +1,24 @@
-// const INTERVAL = 5 * 60 * 1000; // 5 minutes in milliseconds
-const INTERVAL = 10 * 1000; // 10 seconds in milliseconds
+const INTERVAL = 1 * 60 * 1000; // 1 minutes in milliseconds
async function queryScreenpipe(params) {
try {
console.log("params", params);
- const queryParams = new URLSearchParams(
- Object.entries({
- q: params.q,
- offset: params.offset ? params.offset.toString() : undefined,
- limit: params.limit ? params.limit.toString() : undefined,
- start_time: params.start_time,
- end_time: params.end_time,
- content_type: params.content_type,
- app_name: params.app_name,
- }).filter(([_, v]) => v != null)
- );
+ const queryParams = Object.entries({
+ q: params.q,
+ offset: params.offset,
+ limit: params.limit,
+ start_time: params.start_time,
+ end_time: params.end_time,
+ content_type: params.content_type,
+ app_name: params.app_name,
+ })
+ .filter(([_, v]) => v != null)
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
+ .join('&');
console.log("calling screenpipe", JSON.stringify(params));
- const response = await fetch(`http://localhost:3030/search?${queryParams}`);
- if (!response.ok) {
- const text = await response.text();
- console.log("error", text);
- throw new Error(`HTTP error! status: ${response.status} ${text}`);
- }
- const result = await response.json();
- console.log("result", result.data.length);
- console.log("result", {
- ...result,
- data: undefined,
- });
+ const result = await pipe.get(`http://localhost:3030/search?${queryParams}`);
+ console.log("got", result.data.length, "items from screenpipe");
+
return result;
} catch (error) {
console.error("Error querying screenpipe:", error);
@@ -38,7 +29,7 @@ async function queryScreenpipe(params) {
async function getAIProvider() {
// Default to OpenAI if no provider is specified
const provider = "ollama";
- const model = "mistral-nemo:12b-instruct-2407-q2_K";
+ const model = "mistral-nemo";
return { provider, model };
}
@@ -51,10 +42,10 @@ async function generateActivityData(provider) {
start_time: fiveMinutesAgo.toISOString(),
end_time: now.toISOString(),
limit: 50,
- content_type: "all",
+ content_type: "ocr",
});
- const prompt = `Based on the following screen and audio data, generate an activity summary for the last 5 minutes:
+ const prompt = `Based on the following screen and audio data, generate an activity summary for the last minutes:
${JSON.stringify(screenData)}
@@ -63,38 +54,34 @@ async function generateActivityData(provider) {
- tags: an array of tags
- summary: a concise summary of the activity
- timestamp: the timestamp of the activity
+ - sources: an array of absolute file paths to mp4 videos in the user's screenpipe data directory
Examples:
- - { "topics": ["meeting", "project", "discussion"], "tags": ["work", "team", "important"], "summary": "Discussed project requirements and assigned tasks.", "timestamp": "2024-08-18T12:54:12Z" }
- - { "topics": ["game", "strategy", "multiplayer"], "tags": ["gaming", "online", "competitive"], "summary": "Played a multiplayer strategy game with friends.", "timestamp": "2024-08-18T06:13:55Z" }
- - { "topics": ["sales", "meeting", "presentation"], "tags": ["work", "team", "important"], "summary": "Presented the new product to the sales team.", "timestamp": "2024-08-18T12:54:12Z" }
- - { "topics": ["programming", "code", "debugging"], "tags": ["work", "team", "important"], "summary": "Debugged a bug in the codebase.", "timestamp": "2024-08-18T12:54:12Z" }
- - { "topics": ["writing", "blog", "content"], "tags": ["work", "team", "important"], "summary": "Wrote a blog post about the new product.", "timestamp": "2024-08-18T12:54:12Z" }
- - { "topics": ["content creation", "social media", "marketing"], "tags": ["work", "team", "important"], "summary": "Created a social media post about the new product.", "timestamp": "2024-08-18T12:54:12Z" }
+ - { "topics": ["meeting", "project", "discussion"], "tags": ["work", "team", "important"], "summary": "Discussed project requirements and assigned tasks.", "timestamp": "2024-08-18T12:54:12Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-50-00.mp4", "/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-55-00.mp4"] }
+ - { "topics": ["game", "strategy", "multiplayer"], "tags": ["gaming", "online", "competitive"], "summary": "Played a multiplayer strategy game with friends.", "timestamp": "2024-08-18T06:13:55Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_06-10-00.mp4"] }
+ - { "topics": ["sales", "meeting", "presentation"], "tags": ["work", "team", "important"], "summary": "Presented the new product to the sales team.", "timestamp": "2024-08-18T12:54:12Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-45-00.mp4"] }
+ - { "topics": ["programming", "code", "debugging"], "tags": ["work", "team", "important"], "summary": "Debugged a bug in the codebase.", "timestamp": "2024-08-18T12:54:12Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-30-00.mp4", "/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-40-00.mp4", "/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-50-00.mp4"] }
+ - { "topics": ["writing", "blog", "content"], "tags": ["work", "team", "important"], "summary": "Wrote a blog post about the new product.", "timestamp": "2024-08-18T12:54:12Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-30-00.mp4"] }
+ - { "topics": ["content creation", "social media", "marketing"], "tags": ["work", "team", "important"], "summary": "Created a social media post about the new product.", "timestamp": "2024-08-18T12:54:12Z", "sources": ["/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-40-00.mp4", "/Users/louisbeaumont/.screenpipe/data/2024-08-18_12-50-00.mp4"] }
- Provide a concise summary, relevant topics, and tags.`;
+ Provide a concise summary, relevant topics, tags, and sources (absolute file paths to mp4 videos in /Users/louisbeaumont/.screenpipe/data/). The sources array may contain one or more file paths.`;
- const response = await fetch(
+ const result = await pipe.post(
provider.provider === "openai"
? "https://api.openai.com/v1/chat/completions"
: "http://localhost:11434/api/chat",
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- model: provider.model,
- messages: [{ role: "user", content: prompt }],
- ...(provider.provider === "openai" && {
- response_format: { type: "json_object" },
- }),
- stream: false,
+ JSON.stringify({
+ model: provider.model,
+ messages: [{ role: "user", content: prompt }],
+ ...(provider.provider === "openai" && {
+ response_format: { type: "json_object" },
}),
- }
+ stream: false,
+ }),
);
- const result = await response.json();
+ console.log("AI answer:", result);
+
const content =
provider.provider === "openai"
? result.choices[0].message.content
@@ -105,16 +92,26 @@ async function generateActivityData(provider) {
// Global variable to store our activities in memory
let activityLog = [];
-async function mergeAndSaveActivity(activity) {
- // Add the new activity to our in-memory log
- activityLog.push(activity);
-
- // Optionally, we can limit the size of our log to prevent memory issues
- const MAX_LOG_SIZE = 1000; // Adjust as needed
- if (activityLog.length > MAX_LOG_SIZE) {
- activityLog = activityLog.slice(-MAX_LOG_SIZE);
+async function mergeAndSaveActivity(fileName, activity) {
+ let existingLog = [];
+ try {
+ const fileContent = await pipe.readFile(fileName);
+ existingLog = JSON.parse(fileContent);
+ } catch (error) {
+ console.error("Error reading existing log, starting fresh:", error);
}
+ // Add the new activity to the existing log
+ existingLog.push(activity);
+
+ console.log("will write", JSON.stringify(existingLog, null, 2));
+
+ // Write the updated log back to the file
+ await pipe.writeFile(fileName, JSON.stringify(existingLog, null, 2));
+
+ // Update the in-memory activityLog
+ activityLog = existingLog;
+
// Log the current state of our activity log
console.log("Updated activity log:", JSON.stringify(activityLog, null, 2));
}
@@ -122,12 +119,13 @@ async function mergeAndSaveActivity(activity) {
async function runActivityTracker() {
const provider = await getAIProvider();
- console.log("Starting Activity Topic Tracker");
+ console.log("Starting Activity Topic Tracker with provider:", provider);
+ const fileName = `activity-log-${new Date().toLocaleString("en-US", { dateStyle: "short", timeStyle: "short" }).replace(/[/:]/g, "-")}.json`;
while (true) {
try {
const activity = await generateActivityData(provider);
- await mergeAndSaveActivity(activity);
+ await mergeAndSaveActivity(fileName, activity);
console.log("Activity logged:", activity);
} catch (error) {
console.error("Error logging activity:", error);
@@ -139,10 +137,6 @@ async function runActivityTracker() {
// Self-invoking async function to run the activity tracker
(async () => {
try {
- console.log("Hello world from JS!");
- console.log(Deno.build);
- Extension.info("Hello world from JS!");
-
await runActivityTracker();
return "hi";
} catch (error) {
diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.toml
index ca816869d..456ba3d10 100644
--- a/screenpipe-core/Cargo.toml
+++ b/screenpipe-core/Cargo.toml
@@ -23,8 +23,13 @@ hf-hub = { workspace = true, features = ["tokio"] }
# pipes
reqwest = { workspace = true }
tokio = { workspace = true }
-deno_core = { version = "0.299" }
-deno_runtime = { version = "0.173" }
+deno_core = { version = "0.283.0", optional = true }
+deno_ast = { version = "0.38.2", features = ["transpiling"], optional = true }
+[features]
+pipes = ["dep:deno_core", "dep:deno_ast"]
+[build-dependencies]
+# Move this under the same feature flag
+deno_core = { version = "0.283.0", optional = true }
diff --git a/screenpipe-core/build.rs b/screenpipe-core/build.rs
new file mode 100644
index 000000000..fe4beffed
--- /dev/null
+++ b/screenpipe-core/build.rs
@@ -0,0 +1,28 @@
+fn main() {
+ #[cfg(feature = "pipes")]
+ {
+ use deno_core::extension;
+ use std::env;
+ use std::path::PathBuf;
+
+ extension!(runjs, js = ["src/deno/runtime.js",]);
+
+ let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
+ let snapshot_path = out_dir.join("RUNJS_SNAPSHOT.bin");
+
+ let snapshot = deno_core::snapshot::create_snapshot(
+ deno_core::snapshot::CreateSnapshotOptions {
+ cargo_manifest_dir: env!("CARGO_MANIFEST_DIR"),
+ startup_snapshot: None,
+ skip_op_registration: false,
+ extensions: vec![runjs::init_ops_and_esm()],
+ with_runtime_cb: None,
+ extension_transpiler: None,
+ },
+ None,
+ )
+ .unwrap();
+
+ std::fs::write(snapshot_path, snapshot.output).unwrap();
+ }
+}
diff --git a/screenpipe-core/src/deno/runtime.js b/screenpipe-core/src/deno/runtime.js
new file mode 100644
index 000000000..7c47a00f7
--- /dev/null
+++ b/screenpipe-core/src/deno/runtime.js
@@ -0,0 +1,41 @@
+const { core } = Deno;
+const { ops } = core;
+
+function argsToMessage(...args) {
+ return args.map((arg) => JSON.stringify(arg)).join(" ");
+}
+
+const console = {
+ log: (...args) => {
+ core.print(`[js][info]: ${argsToMessage(...args)}\n`, false);
+ },
+ error: (...args) => {
+ core.print(`[js][error]: ${argsToMessage(...args)}\n`, true);
+ },
+};
+
+const pipe = {
+ readFile: (path) => {
+ return ops.op_read_file(path);
+ },
+ writeFile: (path, contents) => {
+ return ops.op_write_file(path, contents);
+ },
+ removeFile: (path) => {
+ return ops.op_remove_file(path);
+ },
+ get: async (url) => {
+ const response = await ops.op_fetch_get(url);
+ return JSON.parse(response);
+ },
+ post: async (url, body) => {
+ const response = await ops.op_fetch_post(url, body);
+ return JSON.parse(response);
+ },
+};
+
+globalThis.setTimeout = (callback, delay) => {
+ ops.op_set_timeout(delay).then(callback);
+};
+globalThis.console = console;
+globalThis.pipe = pipe;
\ No newline at end of file
diff --git a/screenpipe-core/src/extensions/bootstrap.js b/screenpipe-core/src/extensions/bootstrap.js
deleted file mode 100644
index fffd80eeb..000000000
--- a/screenpipe-core/src/extensions/bootstrap.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import { op_info } from "ext:core/ops";
-function info(msg) {
- op_info(msg);
-}
-
-function fetch(url) {
- return ops.op_fetch(url);
-}
-
-globalThis.Extension = { info, fetch };
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rs
index a1468e343..b66b96077 100644
--- a/screenpipe-core/src/pipes.rs
+++ b/screenpipe-core/src/pipes.rs
@@ -1,67 +1,191 @@
-pub use anyhow::Result;
-use deno_core::{op2, FsModuleLoader, ModuleSpecifier};
-use deno_runtime::{
- deno_permissions::{Permissions, PermissionsContainer},
- worker::WorkerOptions,
-};
-use log::info;
-use std::{path::Path, rc::Rc};
-
-pub struct Pipe;
-
-#[op2(fast)]
-fn op_info(#[string] text: &str) {
- info!("{}", text);
-}
+#[cfg(feature = "pipes")]
+mod pipes {
+ use deno_ast::MediaType;
+ use deno_ast::ParseParams;
+ use deno_ast::SourceTextInfo;
+ use deno_core::error::AnyError;
+ use deno_core::extension;
+ use deno_core::op2;
+ use deno_core::ModuleLoadResponse;
+ use deno_core::ModuleSourceCode;
+ use log::error;
+ use std::env;
+ use std::rc::Rc;
-#[op2(fast)]
-pub fn op_fetch(#[string] url: String) -> String {
- let client = reqwest::blocking::Client::new();
- let response = client.get(&url).send().unwrap();
- let body = response.text().unwrap();
- body
-}
+ #[op2(async)]
+ #[string]
+ async fn op_read_file(#[string] path: String) -> Result<String, AnyError> {
+ tokio::fs::read_to_string(&path).await.map_err(|e| {
+ error!("Failed to read file '{}': {}", path, e);
+ AnyError::from(e)
+ })
+ }
+
+ #[op2(async)]
+ #[string]
+ async fn op_write_file(
+ #[string] path: String,
+ #[string] contents: String,
+ ) -> Result<(), AnyError> {
+ tokio::fs::write(&path, contents).await.map_err(|e| {
+ error!("Failed to write file '{}': {}", path, e);
+ AnyError::from(e)
+ })
+ }
+
+ #[op2(async)]
+ #[string]
+ async fn op_fetch_get(#[string] url: String) -> Result<String, AnyError> {
+ let response = reqwest::get(&url).await?;
+ let status = response.status();
+ let text = response.text().await?;
-deno_core::extension!(
- info_runtime,
- ops = [op_info],
- esm_entry_point = "ext:info_runtime/bootstrap.js",
- esm = [dir "src/extensions", "bootstrap.js"]
-);
-
-deno_core::extension!(
- fetch_runtime,
- ops = [op_fetch],
- esm_entry_point = "ext:fetch_runtime/bootstrap.js",
- esm = [dir "src/extensions", "bootstrap.js"]
-);
-
-impl Pipe {
- pub fn new() -> Self {
- Pipe
+ if !status.is_success() {
+ error!("HTTP error status: {}, text: {}", status, text);
+ return Err(AnyError::msg(format!(
+ "HTTP error status: {}, text: {}",
+ status, text
+ )));
+ }
+
+ Ok(text)
}
- pub async fn run(&self, path_to_main_module: &Path) -> Result<()> {
- let main_module = ModuleSpecifier::from_file_path(path_to_main_module).map_err(|_| {
- anyhow::anyhow!(
- "Failed to create module specifier from path: {:?}",
- path_to_main_module
- )
- })?;
-
- let mut main_worker = deno_runtime::worker::MainWorker::bootstrap_from_options(
- main_module.clone(),
- PermissionsContainer::new(Permissions::allow_all()),
- WorkerOptions {
- module_loader: Rc::new(FsModuleLoader),
- extensions: vec![
- info_runtime::init_ops_and_esm(),
- fetch_runtime::init_ops_and_esm(),
- ],
- ..Default::default()
- },
- );
- main_worker.execute_main_module(&main_module).await?;
+ #[op2(async)]
+ #[string]
+ async fn op_fetch_post(
+ #[string] url: String,
+ #[string] body: String,
+ ) -> Result<String, AnyError> {
+ let client = reqwest::Client::new();
+ let response = client.post(&url).body(body).send().await?;
+ let status = response.status();
+ let text = response.text().await?;
+
+ if !status.is_success() {
+ error!("HTTP error status: {}, text: {}", status, text);
+ return Err(AnyError::msg(format!(
+ "HTTP error status: {}, text: {}",
+ status, text
+ )));
+ }
+
+ Ok(text)
+ }
+
+ #[op2(async)]
+ async fn op_set_timeout(delay: f64) -> Result<(), AnyError> {
+ tokio::time::sleep(std::time::Duration::from_millis(delay as u64)).await;
Ok(())
}
+
+ #[op2(fast)]
+ fn op_remove_file(#[string] path: String) -> Result<(), AnyError> {
+ std::fs::remove_file(path)?;
+ Ok(())
+ }
+
+ struct TsModuleLoader;
+
+ impl deno_core::ModuleLoader for TsModuleLoader {
+ fn resolve(
+ &self,
+ specifier: &str,
+ referrer: &str,
+ _kind: deno_core::ResolutionKind,
+ ) -> Result<deno_core::ModuleSpecifier, AnyError> {
+ deno_core::resolve_import(specifier, referrer).map_err(|e| e.into())
+ }
+
+ fn load(
+ &self,
+ module_specifier: &deno_core::ModuleSpecifier,
+ _maybe_referrer: Option<&reqwest::Url>,
+ _is_dyn_import: bool,
+ _requested_module_type: deno_core::RequestedModuleType,
+ ) -> ModuleLoadResponse {
+ let module_specifier = module_specifier.clone();
+
+ let module_load = Box::pin(async move {
+ let path = module_specifier.to_file_path().unwrap();
+
+ let media_type = MediaType::from_path(&path);
+ let (module_type, should_transpile) = match MediaType::from_path(&path) {
+ MediaType::JavaScript | MediaType::Mjs | MediaType::Cjs => {
+ (deno_core::ModuleType::JavaScript, false)
+ }
+ MediaType::Jsx => (deno_core::ModuleType::JavaScript, true),
+ MediaType::TypeScript
+ | MediaType::Mts
+ | MediaType::Cts
+ | MediaType::Dts
+ | MediaType::Dmts
+ | MediaType::Dcts
+ | MediaType::Tsx => (deno_core::ModuleType::JavaScript, true),
+ MediaType::Json => (deno_core::ModuleType::Json, false),
+ _ => panic!("Unknown extension {:?}", path.extension()),
+ };
+
+ let code = std::fs::read_to_string(&path)?;
+ let code = if should_transpile {
+ let parsed = deno_ast::parse_module(ParseParams {
+ specifier: module_specifier.clone(),
+ text_info: SourceTextInfo::from_string(code),
+ media_type,
+ capture_tokens: false,
+ scope_analysis: false,
+ maybe_syntax: None,
+ })?;
+ parsed
+ .transpile(&Default::default(), &Default::default())?
+ .into_source()
+ .text
+ } else {
+ code
+ };
+ let module = deno_core::ModuleSource::new(
+ module_type,
+ ModuleSourceCode::String(code.into()),
+ &module_specifier,
+ None,
+ );
+ Ok(module)
+ });
+
+ ModuleLoadResponse::Async(module_load)
+ }
+ }
+
+ static RUNTIME_SNAPSHOT: &[u8] =
+ include_bytes!(concat!(env!("OUT_DIR"), "/RUNJS_SNAPSHOT.bin"));
+
+ extension! {
+ runjs,
+ ops = [
+ op_read_file,
+ op_write_file,
+ op_remove_file,
+ op_fetch_get,
+ op_fetch_post,
+ op_set_timeout,
+ ]
+ }
+
+ pub async fn run_js(file_path: &str) -> Result<(), AnyError> {
+ let main_module = deno_core::resolve_path(file_path, env::current_dir()?.as_path())?;
+ let mut js_runtime = deno_core::JsRuntime::new(deno_core::RuntimeOptions {
+ module_loader: Some(Rc::new(TsModuleLoader)),
+ startup_snapshot: Some(RUNTIME_SNAPSHOT),
+ extensions: vec![runjs::init_ops()],
+ ..Default::default()
+ });
+
+ let mod_id = js_runtime.load_main_es_module(&main_module).await?;
+ let result = js_runtime.mod_evaluate(mod_id);
+ js_runtime.run_event_loop(Default::default()).await?;
+ result.await
+ }
}
+
+#[cfg(feature = "pipes")]
+pub use pipes::*;
diff --git a/screenpipe-core/tests/pipes_test.rs b/screenpipe-core/tests/pipes_test.rs
index 8e062db43..27974ae6f 100644
--- a/screenpipe-core/tests/pipes_test.rs
+++ b/screenpipe-core/tests/pipes_test.rs
@@ -1,51 +1,33 @@
#[cfg(test)]
mod tests {
- use super::*;
- use deno_core::{JsRuntime, RuntimeOptions};
- use screenpipe_core::PluginSystem;
+ use screenpipe_core::run_js;
+ use tokio::{
+ fs::{remove_file, File},
+ io::AsyncWriteExt,
+ };
#[tokio::test]
async fn test_js_execution() {
- let mut runtime = JsRuntime::new(RuntimeOptions::default());
-
- // Test a simple JavaScript function
- let result = runtime.execute_script(
- "test.js",
- r#"
+ let code = r#"
function add(a, b) {
return a + b;
}
add(2, 3);
- "#,
- );
+ console.log("Hello, world!");
+ const response = await runjs.fetch("https://jsonplaceholder.typicode.com/todos/1");
+ console.log(response);
+ "#;
+
+ // write code to a file
+ let file_path = "test.js";
+ let mut file = File::create(file_path).await.unwrap();
+ file.write_all(code.as_bytes()).await.unwrap();
+ file.flush().await.unwrap();
+ // Test a simple JavaScript function
+ let result = run_js(file_path).await;
assert!(result.is_ok());
println!("result: {:?}", result);
- // let result = result.unwrap();
- // assert_eq!(result.get_i32(), Some(5));
- }
-
- #[tokio::test]
- async fn test_plugin_system() {
- let plugin_system = PluginSystem::new();
-
- // Add a test plugin
- plugin_system
- .add_plugin(
- "test_plugin".to_string(),
- r#"
- console.log('Test plugin executed');
- "#
- .to_string(),
- )
- .await;
-
- // Run plugins
- plugin_system.run_plugins().await;
-
- // Assert that the plugin was added successfully
- // let plugins = plugin_system.plugins.lock().await;
- // assert_eq!(plugins.len(), 1);
- // assert_eq!(plugins[0].name, "test_plugin");
+ remove_file(file_path).await.unwrap();
}
}
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index bd2a317cc..e7e144e98 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -15,7 +15,7 @@ serde_json = "1.0"
screenpipe-vision = { path = "../screenpipe-vision" }
screenpipe-audio = { path = "../screenpipe-audio" }
-screenpipe-core = { path = "../screenpipe-core" }
+screenpipe-core = { path = "../screenpipe-core", features = ["pipes"] }
# Image processing
image = { workspace = true }
@@ -116,6 +116,7 @@ static-ffmpeg = ["ffmpeg-next/static"]
metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]
cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]
+pipes = ["screenpipe-core/pipes"]
[[bin]]
name = "screenpipe"
@@ -123,4 +124,9 @@ path = "src/bin/screenpipe-server.rs"
[[bin]]
name = "screenpipe-video"
-path = "src/bin/screenpipe-video.rs"
\ No newline at end of file
+path = "src/bin/screenpipe-video.rs"
+
+[[bin]]
+name = "screenpipe-pipe-runner"
+path = "src/bin/screenpipe-pipe-runner.rs"
+required-features = ["pipes"]
diff --git a/screenpipe-server/src/bin/screenpipe-pipe-runner.rs b/screenpipe-server/src/bin/screenpipe-pipe-runner.rs
new file mode 100644
index 000000000..5507c30cc
--- /dev/null
+++ b/screenpipe-server/src/bin/screenpipe-pipe-runner.rs
@@ -0,0 +1,38 @@
+use clap::Parser;
+use log::LevelFilter;
+#[cfg(feature = "pipes")]
+use screenpipe_core::run_js;
+use screenpipe_server::Cli;
+use std::path::Path;
+
+#[cfg(feature = "pipes")]
+fn main() {
+ let cli = Cli::parse(); // Parse CLI arguments
+
+ if cli.pipe.is_empty() {
+ eprintln!("No pipe specified. Use --pipe to specify the pipe.");
+ std::process::exit(1);
+ }
+
+ let mut builder = env_logger::Builder::new();
+ builder
+ .filter(None, LevelFilter::Info)
+ .format_timestamp_secs()
+ .init();
+
+ let path_to_main_module = Path::new(cli.pipe[0].as_str()).canonicalize().unwrap();
+
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ if let Err(error) = runtime.block_on(run_js(&path_to_main_module.to_string_lossy())) {
+ eprintln!("error: {error}");
+ }
+}
+
+#[cfg(not(feature = "pipes"))]
+fn main() {
+ eprintln!("Pipes support is not enabled. Compile with --features pipes to enable it.");
+ std::process::exit(1);
+}
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 58177d3c6..d2bbfb960 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -3,76 +3,36 @@ use std::{
fs::{self, File},
net::SocketAddr,
ops::Deref,
- path::{Path, PathBuf},
+ path::PathBuf,
sync::{atomic::AtomicBool, Arc},
time::Duration,
};
-use clap::Parser;
#[allow(unused_imports)]
use colored::Colorize;
use crossbeam::queue::SegQueue;
use dirs::home_dir;
use log::{debug, error, info, LevelFilter};
use screenpipe_audio::{
- default_input_device, default_output_device, list_audio_devices, parse_audio_device, AudioDevice, DeviceControl
+ default_input_device, default_output_device, list_audio_devices, parse_audio_device,
+ AudioDevice, DeviceControl,
+};
+use screenpipe_vision::{
+ monitor::{get_monitor_by_id, list_monitors},
+ OcrEngine,
};
-use screenpipe_vision::{monitor::{get_monitor_by_id, list_monitors}, OcrEngine};
use std::io::Write;
-use screenpipe_core::{find_ffmpeg_path, Pipe};
-use screenpipe_server::logs::MultiWriter;
-use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server};
-use tokio::sync::mpsc::channel;
-use screenpipe_vision::utils::OcrEngine as CoreOcrEngine;
+use clap::Parser;
use screenpipe_audio::AudioTranscriptionEngine as CoreAudioTranscriptionEngine;
-
-use clap::ValueEnum;
-
-#[derive(Clone, Debug, ValueEnum, PartialEq)]
-enum CliAudioTranscriptionEngine {
- #[clap(name = "deepgram")]
- Deepgram,
- #[clap(name = "whisper-tiny")]
- WhisperTiny,
- #[clap(name = "whisper-large")]
- WhisperDistilLargeV3,
-}
-
-impl From<CliAudioTranscriptionEngine> for CoreAudioTranscriptionEngine {
- fn from(cli_engine: CliAudioTranscriptionEngine) -> Self {
- match cli_engine {
- CliAudioTranscriptionEngine::Deepgram => CoreAudioTranscriptionEngine::Deepgram,
- CliAudioTranscriptionEngine::WhisperTiny => CoreAudioTranscriptionEngine::WhisperTiny,
- CliAudioTranscriptionEngine::WhisperDistilLargeV3 => CoreAudioTranscriptionEngine::WhisperDistilLargeV3,
- }
- }
-}
-
-#[derive(Clone, Debug, ValueEnum, PartialEq)]
-enum CliOcrEngine {
- Unstructured,
- #[cfg(not(target_os = "macos"))]
- Tesseract,
- #[cfg(target_os = "windows")]
- WindowsNative,
- #[cfg(target_os = "macos")]
- AppleNative,
-}
-
-impl From<CliOcrEngine> for CoreOcrEngine {
- fn from(cli_engine: CliOcrEngine) -> Self {
- match cli_engine {
- CliOcrEngine::Unstructured => CoreOcrEngine::Unstructured,
- #[cfg(not(target_os = "macos"))]
- CliOcrEngine::Tesseract => CoreOcrEngine::Tesseract,
- #[cfg(target_os = "windows")]
- CliOcrEngine::WindowsNative => CoreOcrEngine::WindowsNative,
- #[cfg(target_os = "macos")]
- CliOcrEngine::AppleNative => CoreOcrEngine::AppleNative,
- }
- }
-}
+use screenpipe_core::find_ffmpeg_path;
+use screenpipe_server::{
+ cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine},
+ logs::MultiWriter,
+ start_continuous_recording, DatabaseManager, ResourceMonitor, Server,
+};
+use screenpipe_vision::utils::OcrEngine as CoreOcrEngine;
+use tokio::{process::Command, sync::mpsc::channel};
fn print_devices(devices: &[AudioDevice]) {
println!("Available audio devices:");
@@ -84,7 +44,6 @@ fn print_devices(devices: &[AudioDevice]) {
println!("On macOS, it's not intuitive but output devices are your displays");
}
-// keep in mind this is the most important feature ever // TODO: add a pipe and a ⭐️ e.g screen | ⭐️ somehow in ascii ♥️🤓
const DISPLAY: &str = r"
_
__________________ ___ ____ ____ (_____ ___
@@ -95,100 +54,6 @@ const DISPLAY: &str = r"
";
-#[derive(Parser)]
-#[command(
- author,
- version,
- about,
- long_about = None,
- name = "screenpipe"
-)]
-struct Cli {
- /// 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.2))]
- fps: f64, // ! not crazy about this (unconsistent behaviour across platforms) see https://github.com/louis030195/screen-pipe/issues/173
-
- /// Audio chunk duration in seconds
- #[arg(short = 'd', long, default_value_t = 30)]
- audio_chunk_duration: u64,
-
- /// Port to run the server on
- #[arg(short = 'p', long, default_value_t = 3030)]
- port: u16,
-
- /// Disable audio recording
- #[arg(long, default_value_t = false)]
- disable_audio: bool,
-
- /// EXPERIMENTAL: Enable self healing when detecting unhealthy state based on /health endpoint.
- /// This feature will automatically restart the recording tasks while keeping the API alive.
- #[arg(long, default_value_t = false)]
- self_healing: bool,
-
- /// Audio devices to use (can be specified multiple times)
- #[arg(short = 'i', long)]
- audio_device: Vec<String>,
-
- /// List available audio devices
- #[arg(long)]
- list_audio_devices: bool,
-
- /// Data directory. Default to $HOME/.screenpipe
- #[arg(long)]
- data_dir: Option<String>,
-
- /// Enable debug logging for screenpipe modules
- #[arg(long)]
- debug: bool,
-
- /// Save text files
- #[arg(long, default_value_t = false)]
- save_text_files: 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.
- #[arg(short = 'a', long, value_enum, default_value_t = CliAudioTranscriptionEngine::WhisperTiny)]
- audio_transcription_engine: CliAudioTranscriptionEngine,
-
- /// 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)
- )]
- #[cfg_attr(
- not(target_os = "macos"),
- arg(short = 'o', long, value_enum, default_value_t = CliOcrEngine::Tesseract)
- )]
- ocr_engine: CliOcrEngine,
-
- /// UID key for sending data to friend wearable (if not provided, data won't be sent)
- #[arg(long)]
- friend_wearable_uid: Option<String>,
-
- /// List available monitors, then you can use --monitor-id to select one (with the ID)
- #[arg(long)]
- list_monitors: bool,
-
- /// Monitor ID to use, this will be used to select the monitor to record
- #[arg(short = 'm', long)]
- monitor_id: Option<u32>,
-
- /// File path for the pipe
- #[arg(long)]
- pipe: Vec<String>,
-}
-
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"))?
@@ -203,14 +68,14 @@ fn get_base_dir(custom_path: Option<String>) -> anyhow::Result<PathBuf> {
#[tokio::main]
async fn main() -> anyhow::Result<()> {
+ let cli = Cli::parse();
+
if find_ffmpeg_path().is_none() {
eprintln!("ffmpeg not found. Please install ffmpeg and ensure it is in your PATH.");
std::process::exit(1);
}
// Initialize logging
- let cli = Cli::parse();
-
let mut builder = env_logger::Builder::new();
builder
.filter(None, LevelFilter::Info)
@@ -227,9 +92,6 @@ async fn main() -> anyhow::Result<()> {
debug!("Text files will be saved.");
}
- // builder.init();
- // tokio-console
- // console_subscriber::init();
let local_data_dir = get_base_dir(cli.data_dir)?;
let local_data_dir_clone = local_data_dir.clone();
@@ -376,11 +238,18 @@ async fn main() -> anyhow::Result<()> {
let warning_ocr_engine_clone = cli.ocr_engine.clone();
let warning_audio_transcription_engine_clone = cli.audio_transcription_engine.clone();
- let monitor_id = cli.monitor_id.unwrap_or(all_monitors.first().unwrap().id());
+ let monitor_id = cli.monitor_id.unwrap_or(all_monitors.first().unwrap().id());
// try to use the monitor selected, if not available throw an error
get_monitor_by_id(monitor_id).await.unwrap_or_else(|| {
- eprintln!("{}", format!("Monitor with id {} not found. Try 'screenpipe --list-monitors'", monitor_id).red());
+ eprintln!(
+ "{}",
+ format!(
+ "Monitor with id {} not found. Try 'screenpipe --list-monitors'",
+ monitor_id
+ )
+ .red()
+ );
std::process::exit(1);
});
let ocr_engine_clone = cli.ocr_engine.clone();
@@ -410,7 +279,8 @@ async fn main() -> anyhow::Result<()> {
}
let core_ocr_engine: CoreOcrEngine = cli.ocr_engine.clone().into();
let ocr_engine = Arc::new(OcrEngine::from(core_ocr_engine));
- let core_audio_transcription_engine: CoreAudioTranscriptionEngine = cli.audio_transcription_engine.clone().into();
+ let core_audio_transcription_engine: CoreAudioTranscriptionEngine =
+ cli.audio_transcription_engine.clone().into();
let audio_transcription_engine = Arc::new(core_audio_transcription_engine);
recording_task = tokio::spawn(async move {
@@ -425,7 +295,7 @@ async fn main() -> anyhow::Result<()> {
audio_transcription_engine,
ocr_engine,
friend_wearable_uid_clone, // Use the cloned version
- monitor_id
+ monitor_id,
)
.await;
@@ -458,9 +328,21 @@ async fn main() -> anyhow::Result<()> {
server.start(devices_status, api_plugin).await.unwrap();
});
- let isolate = Pipe::new();
- let path_to_main_module = Path::new(cli.pipe[0].as_str()).canonicalize().unwrap();
- isolate.run(&path_to_main_module).await.unwrap();
+ #[cfg(feature = "pipes")]
+ if !cli.pipe.is_empty() {
+ let status = Command::new("screenpipe-pipe-runner")
+ .arg("--pipe")
+ .args(&cli.pipe)
+ .status()
+ .await
+ .expect("Failed to start pipe-runner process");
+
+ if !status.success() {
+ eprintln!("pipe-runner process failed with status: {}", status);
+ }
+
+ return Ok(());
+ }
// Wait for the server to start
info!("Server started on http://localhost:{}", cli.port);
@@ -482,15 +364,27 @@ async fn main() -> anyhow::Result<()> {
println!("│ Setting │ Value │");
println!("├─────────────────────┼────────────────────────────────────┤");
println!("│ FPS │ {:<34} │", cli.fps);
- println!("│ Audio Chunk Duration│ {:<34} │", format!("{} seconds", cli.audio_chunk_duration));
+ println!(
+ "│ Audio Chunk Duration│ {:<34} │",
+ format!("{} seconds", cli.audio_chunk_duration)
+ );
println!("│ Port │ {:<34} │", cli.port);
println!("│ Audio Disabled │ {:<34} │", cli.disable_audio);
println!("│ Self Healing │ {:<34} │", cli.self_healing);
println!("│ Save Text Files │ {:<34} │", cli.save_text_files);
- println!("│ Audio Engine │ {:<34} │", format!("{:?}", warning_audio_transcription_engine_clone));
- println!("│ OCR Engine │ {:<34} │", format!("{:?}", ocr_engine_clone));
+ println!(
+ "│ Audio Engine │ {:<34} │",
+ format!("{:?}", warning_audio_transcription_engine_clone)
+ );
+ println!(
+ "│ OCR Engine │ {:<34} │",
+ format!("{:?}", ocr_engine_clone)
+ );
println!("│ Monitor ID │ {:<34} │", monitor_id);
- println!("│ Data Directory │ {:<34} │", local_data_dir_clone.display());
+ println!(
+ "│ Data Directory │ {:<34} │",
+ local_data_dir_clone.display()
+ );
println!("│ Debug Mode │ {:<34} │", cli.debug);
const VALUE_WIDTH: usize = 34;
@@ -525,9 +419,10 @@ async fn main() -> anyhow::Result<()> {
println!("└─────────────────────┴────────────────────────────────────┘");
-
// Add warning for cloud arguments
- if warning_audio_transcription_engine_clone == CliAudioTranscriptionEngine::Deepgram || warning_ocr_engine_clone == CliOcrEngine::Unstructured {
+ if warning_audio_transcription_engine_clone == CliAudioTranscriptionEngine::Deepgram
+ || warning_ocr_engine_clone == CliOcrEngine::Unstructured
+ {
println!(
"{}",
"WARNING: You are using cloud now. Make sure to understand the data privacy risks."
diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rs
new file mode 100644
index 000000000..3ab6abb21
--- /dev/null
+++ b/screenpipe-server/src/cli.rs
@@ -0,0 +1,145 @@
+use clap::Parser;
+use screenpipe_audio::AudioTranscriptionEngine as CoreAudioTranscriptionEngine;
+use screenpipe_vision::utils::OcrEngine as CoreOcrEngine;
+use clap::ValueEnum;
+
+#[derive(Clone, Debug, ValueEnum, PartialEq)]
+pub enum CliAudioTranscriptionEngine {
+ #[clap(name = "deepgram")]
+ Deepgram,
+ #[clap(name = "whisper-tiny")]
+ WhisperTiny,
+ #[clap(name = "whisper-large")]
+ WhisperDistilLargeV3,
+}
+
+impl From<CliAudioTranscriptionEngine> for CoreAudioTranscriptionEngine {
+ fn from(cli_engine: CliAudioTranscriptionEngine) -> Self {
+ match cli_engine {
+ CliAudioTranscriptionEngine::Deepgram => CoreAudioTranscriptionEngine::Deepgram,
+ CliAudioTranscriptionEngine::WhisperTiny => CoreAudioTranscriptionEngine::WhisperTiny,
+ CliAudioTranscriptionEngine::WhisperDistilLargeV3 => {
+ CoreAudioTranscriptionEngine::WhisperDistilLargeV3
+ }
+ }
+ }
+}
+
+#[derive(Clone, Debug, ValueEnum, PartialEq)]
+pub enum CliOcrEngine {
+ Unstructured,
+ #[cfg(not(target_os = "macos"))]
+ Tesseract,
+ #[cfg(target_os = "windows")]
+ WindowsNative,
+ #[cfg(target_os = "macos")]
+ AppleNative,
+}
+
+impl From<CliOcrEngine> for CoreOcrEngine {
+ fn from(cli_engine: CliOcrEngine) -> Self {
+ match cli_engine {
+ CliOcrEngine::Unstructured => CoreOcrEngine::Unstructured,
+ #[cfg(not(target_os = "macos"))]
+ CliOcrEngine::Tesseract => CoreOcrEngine::Tesseract,
+ #[cfg(target_os = "windows")]
+ CliOcrEngine::WindowsNative => CoreOcrEngine::WindowsNative,
+ #[cfg(target_os = "macos")]
+ CliOcrEngine::AppleNative => CoreOcrEngine::AppleNative,
+ }
+ }
+}
+
+#[derive(Parser)]
+#[command(
+ author,
+ version,
+ about,
+ long_about = None,
+ name = "screenpipe"
+)]
+pub struct Cli {
+ /// 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.2))]
+ pub fps: f64, // ! not crazy about this (unconsistent behaviour across platforms) see https://github.com/louis030195/screen-pipe/issues/173
+
+ /// 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,
+
+ /// EXPERIMENTAL: Enable self healing when detecting unhealthy state based on /health endpoint.
+ /// This feature will automatically restart the recording tasks while keeping the API alive.
+ #[arg(long, default_value_t = false)]
+ pub self_healing: bool,
+
+ /// Audio devices to use (can be specified multiple times)
+ #[arg(short = 'i', long)]
+ pub audio_device: Vec<String>,
+
+ /// List available audio devices
+ #[arg(long)]
+ pub list_audio_devices: bool,
+
+ /// Data directory. Default to $HOME/.screenpipe
+ #[arg(long)]
+ pub data_dir: Option<String>,
+
+ /// Enable debug logging for screenpipe modules
+ #[arg(long)]
+ pub debug: bool,
+
+ /// Save text files
+ #[arg(long, default_value_t = false)]
+ pub save_text_files: 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.
+ #[arg(short = 'a', long, value_enum, default_value_t = CliAudioTranscriptionEngine::WhisperTiny)]
+ pub audio_transcription_engine: CliAudioTranscriptionEngine,
+
+ /// 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)
+ )]
+ #[cfg_attr(
+ not(target_os = "macos"),
+ arg(short = 'o', long, value_enum, default_value_t = CliOcrEngine::Tesseract)
+ )]
+ pub ocr_engine: CliOcrEngine,
+
+ /// UID key for sending data to friend wearable (if not provided, data won't be sent)
+ #[arg(long)]
+ pub friend_wearable_uid: Option<String>,
+
+ /// List available monitors, then you can use --monitor-id to select one (with the ID)
+ #[arg(long)]
+ pub list_monitors: bool,
+
+ /// Monitor ID to use, this will be used to select the monitor to record
+ #[arg(short = 'm', long)]
+ pub monitor_id: Option<u32>,
+
+ /// File path for the pipe
+ #[arg(long)]
+ pub pipe: Vec<String>,
+}
\ No newline at end of file
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index 39ea1f345..f78f582fc 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -1,4 +1,5 @@
pub mod chunking;
+pub mod cli;
pub mod core;
mod db;
pub mod filtering;
@@ -7,6 +8,7 @@ mod plugin;
mod resource_monitor;
mod server;
mod video;
+pub use cli::Cli;
pub use core::{start_continuous_recording, RecorderControl};
pub use db::{ContentType, DatabaseManager, SearchResult};
pub use logs::MultiWriter;