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
work on pipe
Louis Beaumonta50da9e769cf
diff --git a/examples/typescript/pipe-stream-ocr-text/.gitignore b/examples/typescript/pipe-stream-ocr-text/.gitignorenew file mode 100644index 000000000..b512c09d4--- /dev/null+++ b/examples/typescript/pipe-stream-ocr-text/.gitignore@@ -0,0 +1 @@+node_modules\ No newline at end of filediff --git a/examples/typescript/pipe-stream-ocr-text/bun.lockb b/examples/typescript/pipe-stream-ocr-text/bun.lockbnew file mode 100755index 000000000..eed5e28b3Binary files /dev/null and b/examples/typescript/pipe-stream-ocr-text/bun.lockb differdiff --git a/examples/typescript/pipe-stream-ocr-text/package-lock.json b/examples/typescript/pipe-stream-ocr-text/package-lock.jsonnew file mode 100644index 000000000..a3c721524--- /dev/null+++ b/examples/typescript/pipe-stream-ocr-text/package-lock.json@@ -0,0 +1,25 @@+{+ "name": "pipe-stream-ocr-text",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "dependencies": {+ "@types/node": "^22.6.1"+ }+ },+ "node_modules/@types/node": {+ "version": "22.6.1",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.6.1.tgz",+ "integrity": "sha512-V48tCfcKb/e6cVUigLAaJDAILdMP0fUW6BidkPK4GpGjXcfbnoHasCZDwz3N3yVt5we2RHm4XTQCpv0KJz9zqw==",+ "dependencies": {+ "undici-types": "~6.19.2"+ }+ },+ "node_modules/undici-types": {+ "version": "6.19.8",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz",+ "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw=="+ }+ }+}diff --git a/examples/typescript/pipe-stream-ocr-text/package.json b/examples/typescript/pipe-stream-ocr-text/package.jsonnew file mode 100644index 000000000..0dd6d62a9--- /dev/null+++ b/examples/typescript/pipe-stream-ocr-text/package.json@@ -0,0 +1,8 @@+{+ "dependencies": {+ "@types/node": "^22.6.1"+ },+ "scripts": {+ "build": "tsc"+ }+}\ No newline at end of filediff --git a/examples/typescript/pipe-stream-ocr-text/pipe.js b/examples/typescript/pipe-stream-ocr-text/pipe.jsnew file mode 100644index 000000000..43764b46b--- /dev/null+++ b/examples/typescript/pipe-stream-ocr-text/pipe.js@@ -0,0 +1,63 @@+import * as fs from "fs";+import * as path from "path";+let INTERVAL = 10 * 1000; // 10 seconds in milliseconds+async function queryScreenpipe() {+ try {+ const now = new Date();+ const oneMinuteAgo = new Date(now.getTime() - INTERVAL);+ const queryParams = `start_time=${oneMinuteAgo.toISOString()}&end_time=${now.toISOString()}&limit=50&content_type=ocr`;+ const result = await fetch(`http://localhost:3030/search?${queryParams}`).then((r) => r.json());+ console.log("Retrieved", result.data.length, "items from screenpipe");+ return result.data;+ }+ catch (error) {+ console.error("Error querying screenpipe:", error);+ return [];+ }+}+async function writeToMarkdown(data) {+ console.log("Writing to markdown", JSON.stringify(data));+ const fileName = `screen-ocr-${new Date()+ .toISOString()+ .replace(/[:.]/g, "-")}.md`;+ const content = data+ .map((item) => `## ${item.content.timestamp}\n\n${item.content.text}\n\n---\n`)+ .join("\n");+ fs.writeFileSync(path.join(process.env.PIPE_DIR, fileName), content);+ console.log(`Written OCR data to ${fileName}`);+}+async function runOCRTracker() {+ console.log("Starting OCR Tracker");+ // wait 2 seocnds+ await new Promise((resolve) => setTimeout(resolve, 1000));+ console.log(pipe);+ await pipe.loadConfig();+ INTERVAL = pipe.config.interval * 1000;+ console.log("INTERVAL", INTERVAL);+ while (true) {+ try {+ const screenData = await queryScreenpipe();+ await writeToMarkdown(screenData);+ }+ catch (error) {+ console.error("Error in OCR tracking:", error);+ }+ finally {+ await new Promise((resolve) => setTimeout(resolve, INTERVAL));+ }+ // const isEnabled = await pipe.isEnabled();+ // if (!isEnabled) {+ // console.log("pipe is disabled");+ // break;+ // }+ }+}+// Self-invoking async function to run the OCR tracker+(async () => {+ try {+ await runOCRTracker();+ }+ catch (error) {+ console.error("Fatal error in OCR Tracker:", error);+ }+})();diff --git a/examples/typescript/pipe-stream-ocr-text/pipe.ts b/examples/typescript/pipe-stream-ocr-text/pipe.tsindex daaf25fda..1d3d92d74 100644--- a/examples/typescript/pipe-stream-ocr-text/pipe.ts+++ b/examples/typescript/pipe-stream-ocr-text/pipe.ts@@ -1,3 +1,6 @@+import * as fs from "fs";+import * as path from "path";+let INTERVAL = 10 * 1000; // 10 seconds in millisecondsasync function queryScreenpipe() {@@ -7,9 +10,9 @@ async function queryScreenpipe() {const queryParams = `start_time=${oneMinuteAgo.toISOString()}&end_time=${now.toISOString()}&limit=50&content_type=ocr`;- const result = await pipe.get(+ const result = await fetch(`http://localhost:3030/search?${queryParams}`- );+ ).then((r) => r.json());console.log("Retrieved", result.data.length, "items from screenpipe");return result.data;} catch (error) {@@ -18,18 +21,19 @@ async function queryScreenpipe() {}}-async function writeToMarkdown(data) {+async function writeToMarkdown(data: any) {console.log("Writing to markdown", JSON.stringify(data));const fileName = `screen-ocr-${new Date().toISOString().replace(/[:.]/g, "-")}.md`;const content = data.map(- (item) => `## ${item.content.timestamp}\n\n${item.content.text}\n\n---\n`+ (item: any) =>+ `## ${item.content.timestamp}\n\n${item.content.text}\n\n---\n`).join("\n");- await pipe.writeFile(fileName, content);+ fs.writeFileSync(path.join(__dirname, fileName), content);console.log(`Written OCR data to ${fileName}`);}diff --git a/examples/typescript/pipe-stream-ocr-text/screenpipe.d.ts b/examples/typescript/pipe-stream-ocr-text/screenpipe.d.tsindex a72e28d09..bf0d8c312 100644--- a/examples/typescript/pipe-stream-ocr-text/screenpipe.d.ts+++ b/examples/typescript/pipe-stream-ocr-text/screenpipe.d.ts@@ -1,33 +1,30 @@declare global {- const pipe: {- readFile: (path: string) => Promise<string>;- writeFile: (path: string, contents: string) => Promise<void>;- removeFile: (path: string) => Promise<void>;- get: (url: string) => Promise<any>;- post: (url: string, body: string) => Promise<any>;- fetch: (url: string, options?: RequestInit) => Promise<Response>;- sendNotification: (options: { title: string; body: string }) => Promise<any>;- loadConfig: () => Promise<Record<string, any>>;- config: Record<string, any>;- metadata: {- id: string;- };+ const pipe: {+ readFile: (path: string) => Promise<string>;+ writeFile: (path: string, contents: string) => Promise<void>;+ removeFile: (path: string) => Promise<void>;+ get: (url: string) => Promise<any>;+ post: (url: string, body: string) => Promise<any>;+ fetch: (url: string, options?: RequestInit) => Promise<Response>;+ sendNotification: (options: {+ title: string;+ body: string;+ }) => Promise<any>;+ loadConfig: () => Promise<Record<string, any>>;+ config: Record<string, any>;+ metadata: {+ id: string;};-- interface Console {- log: (...args: any[]) => void;- error: (...args: any[]) => void;- }-- const console: Console;-- namespace NodeJS {- interface ProcessEnv {- SCREENPIPE_DIR: string;- SCREENPIPE_LOG_API_URL?: string;- SCREENPIPE_SERVER_URL?: string;- }+ };++ namespace NodeJS {+ interface ProcessEnv {+ SCREENPIPE_DIR: string;+ SCREENPIPE_LOG_API_URL?: string;+ SCREENPIPE_SERVER_URL?: string;+ PIPE_DIR: string;}}-- export {};\ No newline at end of file+}++export {};diff --git a/examples/typescript/pipe-stream-ocr-text/tsconfig.json b/examples/typescript/pipe-stream-ocr-text/tsconfig.jsonindex da9d0f913..c4e6dfdd7 100644--- a/examples/typescript/pipe-stream-ocr-text/tsconfig.json+++ b/examples/typescript/pipe-stream-ocr-text/tsconfig.json@@ -1,17 +1,17 @@{"compilerOptions": {- "typeRoots": [- "./node_modules/@types",- "./types"- ],- "types": [- "screenpipe"- ],- "lib": ["ES2015", "DOM"],- "target": "ES2015"+ "target": "es2018",+ "module": "esnext",+ "moduleResolution": "node",+ "outDir": "./",+ "rootDir": "./",+ "strict": true,+ "esModuleInterop": true},"include": [- "**/*.ts",- "screenpipe.d.ts"+ "./**/*.ts"+ ],+ "exclude": [+ "node_modules"]}\ No newline at end of filediff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rsindex 15374dbd7..d06fd000f 100644--- a/screenpipe-audio/src/stt.rs+++ b/screenpipe-audio/src/stt.rs@@ -529,7 +529,7 @@ pub async fn create_whisper_channel(error!("Error receiving input: {:?}", e);// Depending on the error type, you might want to break the loop or continue// For now, we'll continue to the next iteration- continue;+ break;}}},diff --git a/screenpipe-core/src/deno/runtime.js b/screenpipe-core/src/deno/runtime.jsindex 027369de6..2b9e43f52 100644--- a/screenpipe-core/src/deno/runtime.js+++ b/screenpipe-core/src/deno/runtime.js@@ -1,5 +1,9 @@const { core } = Deno;const { ops } = core;+const Path = {+ isAbsolute: (path) => path.startsWith('/') || /^[A-Za-z]:\\/.test(path),+ join: (...parts) => parts.join('/').replace(/\/+/g, '/'),+};function argsToMessage(...args) {return args.map((arg) => JSON.stringify(arg)).join(" ");@@ -43,14 +47,27 @@ globalThis.console = console;const pipe = {readFile: (path) => {- return ops.op_read_file(path);- },- writeFile: (path, contents) => {- return ops.op_write_file(path, contents);+ let fullPath;+ if (Path.isAbsolute(path)) {+ fullPath = path;+ } else {+ const pipeDir = `${process.env.SCREENPIPE_DIR}/pipes/${globalThis.metadata.id}`;+ fullPath = Path.join(pipeDir, path);+ }+ return ops.op_read_file(fullPath);},+removeFile: (path) => {- return ops.op_remove_file(path);+ let fullPath;+ if (Path.isAbsolute(path)) {+ fullPath = path;+ } else {+ const pipeDir = `${process.env.SCREENPIPE_DIR}/pipes/${globalThis.metadata.id}`;+ fullPath = Path.join(pipeDir, path);+ }+ return ops.op_remove_file(fullPath);},+get: async (url) => {const response = await ops.op_fetch_get(url);return JSON.parse(response);diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex a30bbbfaa..827dcbf04 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -27,10 +27,17 @@ mod pipes {use tracing::{error, info};use url::Url;- // Add this function near the top of the file, after the imports+ // Update this function near the top of the filefn sanitize_pipe_name(name: &str) -> String {let re = Regex::new(r"[^a-zA-Z0-9_-]").unwrap();- re.replace_all(name, "-").to_string()+ let sanitized = re.replace_all(name, "-").to_string();++ // Remove "-ref-main/" suffix if it exists+ sanitized+ .strip_suffix("-ref-main/")+ .or_else(|| sanitized.strip_suffix("-ref-main"))+ .unwrap_or(&sanitized)+ .to_string()}#[op2]@@ -316,6 +323,7 @@ mod pipes {globalThis.process.env.TEMP_DIR = "{}";globalThis.process.env.PIPE_ID = "{}";globalThis.process.env.PIPE_FILE = "{}";+ globalThis.process.env.PIPE_DIR = "{}";"#,screenpipe_dir.to_string_lossy()@@ -334,7 +342,13 @@ mod pipes {.replace('\\', "\\\\").replace('\"', "\\\""),pipe.replace('\"', "\\\""),- file_path.replace('\\', "\\\\").replace('\"', "\\\"")+ file_path.replace('\\', "\\\\").replace('\"', "\\\""),+ screenpipe_dir+ .join("pipes")+ .join(pipe)+ .to_string_lossy()+ .replace('\\', "\\\\")+ .replace('\"', "\\\""),),)?;@@ -418,12 +432,6 @@ mod pipes {);download_github_folder(&client, &api_url, screenpipe_dir, &pipe_name).await}- Some("raw.githubusercontent.com") => {- let pipe_name = sanitize_pipe_name(- Path::new(source).file_name().unwrap().to_str().unwrap(),- );- download_single_file(&client, source, screenpipe_dir, &pipe_name).await- }_ => anyhow::bail!("Unsupported URL format"),}} else {@@ -461,7 +469,7 @@ mod pipes {if file_type.is_file() {if file_name.to_str()- .map(|s| s.ends_with(".ts") || s.ends_with(".js") || s == "pipe.json")+ .map(|s| s == "pipe.js" || s == "pipe.json").unwrap_or(false){let src_path = entry.path();@@ -507,18 +515,12 @@ mod pipes {for item in contents.as_array().unwrap() {let file_name = item["name"].as_str().unwrap();- if file_name.ends_with(".ts") || file_name.ends_with(".js") || file_name == "pipe.json"- {- if file_name.starts_with("main")- || file_name.starts_with("pipe")- || file_name == "pipe.json"- {- let download_url = item["download_url"].as_str().unwrap();- let file_content = client.get(download_url).send().await?.bytes().await?;- let file_path = pipe_dir.join(file_name);- tokio::fs::write(&file_path, &file_content).await?;- info!("Downloaded: {:?}", file_path);- }+ if file_name == "pipe.js" || file_name == "pipe.json" {+ let download_url = item["download_url"].as_str().unwrap();+ let file_content = client.get(download_url).send().await?.bytes().await?;+ let file_path = pipe_dir.join(file_name);+ tokio::fs::write(&file_path, &file_content).await?;+ info!("Downloaded: {:?}", file_path);}}@@ -526,32 +528,6 @@ mod pipes {Ok(pipe_dir)}- async fn download_single_file(- client: &Client,- url: &str,- screenpipe_dir: PathBuf,- pipe_name: &str,- ) -> anyhow::Result<PathBuf> {- let response = client.get(url).send().await?;- let content = response.bytes().await?;-- let pipe_dir = screenpipe_dir.join("pipes").join(pipe_name);-- // Check if the pipe directory already exists- if pipe_dir.exists() {- info!("Pipe already exists: {:?}", pipe_dir);- return Ok(pipe_dir);- }-- tokio::fs::create_dir_all(&pipe_dir).await?;-- let file_path = pipe_dir.join(pipe_name);- tokio::fs::write(&file_path, &content).await?;-- info!("Downloaded single file: {:?}", file_path);- Ok(pipe_dir)- }-fn get_raw_github_url(url: &str) -> anyhow::Result<String> {info!("Attempting to get raw GitHub URL for: {}", url);let parsed_url = Url::parse(url)?;@@ -581,13 +557,11 @@ mod pipes {let entry = entry?;let file_name = entry.file_name();let file_name_str = file_name.to_str().unwrap();- if (file_name_str.starts_with("pipe") || file_name_str.starts_with("main"))- && (file_name_str.ends_with(".ts") || file_name_str.ends_with(".js"))- {+ if file_name_str.contains("pipe.js") {return Ok(entry.path());}}- anyhow::bail!("No pipe.ts, pipe.js, main.ts, or main.js found in the pipe directory")+ anyhow::bail!("No pipe.js found in the pipe/dist directory")}}