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

chore: improve pipe api + security pipe

Louis Beaumont751977e2c499
diff --git a/examples/typescript/pipe-security-check/README.md b/examples/typescript/pipe-security-check/README.md
index 4442dab6e..954bf9300 100644
--- a/examples/typescript/pipe-security-check/README.md
+++ b/examples/typescript/pipe-security-check/README.md
@@ -1,5 +1,23 @@
send a notification to the user when exposed to a security risk on your screen
+```bash
+ollama run mistral-nemo
+```
+
+```bash
+curl -X POST "http://localhost:3030/pipes/download" -H "Content-Type: application/json" -d '{"url": "$(pwd)/examples/typescript/pipe-security-check"}'
+
+curl -X POST "http://localhost:3030/pipes/enable" -H "Content-Type: application/json" -d '{"pipe_id": "pipe-security-check"}'
+```
+
+or
+
+```bash
+./target/release/screenpipe pipe download $(pwd)/examples/typescript/pipe-security-check
+
+./target/release/screenpipe pipe enable pipe-security-check
+```
+
diff --git a/examples/typescript/pipe-security-check/main.js b/examples/typescript/pipe-security-check/main.js
index 88ef8e29b..cb7e3a36d 100644
--- a/examples/typescript/pipe-security-check/main.js
+++ b/examples/typescript/pipe-security-check/main.js
@@ -20,29 +20,42 @@ async function queryScreenpipe(params) {
async function getAIProvider() {
const provider = "ollama";
- const model = "Hermes-llama-3.1:latest";
+ const model = "mistral-nemo";
return { provider, model };
}
async function checkSecurity(provider, screenData) {
+
+ const listOfBrowsers = ["arc", "chrome", "edge", "safari", "firefox"];
+ const browserData = screenData.data.filter(item =>
+ listOfBrowsers.some(browser =>
+ item.content.app_name.toLowerCase().includes(browser) ||
+ item.content.window_name.toLowerCase().includes(browser)
+ )
+ );
const prompt = `Act like a cybersecurity expert with 10 years of experience detecting suspicious activity. Analyze the following screen data and determine if a security issue is present.
-Instructions:
Analyze the screen data for suspicious activity.
- Output a JSON object:
+ Return a JSON object with the following structure:
+ {
+ "securityIssueFound": true, // or false
+ "reason": "Specify the reason for the issue"
+ "summary": "One-sentence summary of the security threat"
+ }
- {
- "securityIssueFound": true, // or false
- "reason": "Specify the reason for the issue"
- "summary": "One-sentence summary of the security threat"
- }
+ Rules:
+ - do not add \`\`\`json or \`\`\` at the beginning or end of the JSON object.
+ - do not add any other text.
+ - do not add any other comments.
+ - only return the JSON object.
+ - only take into account browser activity, not other apps.
Input:
- ${JSON.stringify(screenData)}
+ ${JSON.stringify(browserData)}
Output only the JSON object.`;
try {
const result = await pipe.post(
- "http://localhost:10001/api/chat",
+ "http://localhost:11434/api/chat",
JSON.stringify({
model: provider.model,
messages: [{ role: "user", content: prompt }],
@@ -53,6 +66,8 @@ Instructions:
console.log("AI answer:", result);
const content = result.message.content;
console.log("AI answer content:", content);
+ // if present, remove the ```json and ``` at the beginning and end of the content
+ // content = content.replace(/^```json\n/, "").replace(/\n```$/, "").trim();
return JSON.parse(content);
} catch (error) {
console.error("Error in AI Response:", error);
@@ -70,18 +85,18 @@ async function checkRecentActivities(provider) {
content_type: "ocr",
});
-// console.log("Screenpipe data:", screenData);
+ // console.log("Screenpipe data:", screenData);
if (!screenData || !screenData.data || screenData.data.length === 0) {
console.log("No data retrieved from Screenpipe");
return;
}
- const response = await checkSecurity(provider, screenData);
+ const response = await checkSecurity(provider, screenData);
console.log("Security check for recent activities response: ", response);
if (response.securityIssueFound) {
- console.error("Security issue detected", response.reason);
- // pipe.sendNotification("Security issue detected", response.reason);
+ console.log("Security issue detected", response.reason);
+ await pipe.sendNotification({ title: "Security issue detected", body: response.reason });
} else {
console.log("No security issue detected");
}
@@ -95,7 +110,7 @@ async function runSecurityChecker() {
try {
await checkRecentActivities(provider);
} catch (error) {
- // pipe.sendNotification({title: "Error in security check", body: error.message})
+ // await pipe.sendNotification({ title: "Error in security check", body: error.message })
console.error("Error in security check of activity:", error);
}
await new Promise(resolve => setTimeout(resolve, INTERVAL));
diff --git a/screenpipe-core/src/deno/runtime.js b/screenpipe-core/src/deno/runtime.js
index 7e2ee3d76..027369de6 100644
--- a/screenpipe-core/src/deno/runtime.js
+++ b/screenpipe-core/src/deno/runtime.js
@@ -88,24 +88,19 @@ const pipe = {
const notificationApiUrl = process.env.SCREENPIPE_SERVER_URL || "http://localhost:11435";
try {
- const response = await ops.op_fetch(notificationApiUrl)
- if (!response.ok) {
- throw new Error("Failed to send notification");
- }
+ const response = await ops.op_fetch(notificationApiUrl + "/notify", {
+ headers: {
+ "Content-Type": "application/json",
+ },
+ method: "POST",
+ body: JSON.stringify({ title, body })
+ });
+ console.log("Notification sent:", response);
+ return JSON.parse(response);
} catch (error) {
- console.warn("Failed to send notification to server, is your notification server running?");
- return
+ console.log("Failed to send notification to server, is your notification server running?");
+ return false;
}
-
- const response = await ops.op_fetch(notificationApiUrl + "/notify", {
- headers: {
- "Content-Type": "application/json",
- },
- method: "POST",
- body: JSON.stringify({ title, body })
- });
- console.log("Notification sent:", response);
- return JSON.parse(response);
},
loadConfig: async () => {
try {
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rs
index cac94e310..0ddbad9d7 100644
--- a/screenpipe-core/src/pipes.rs
+++ b/screenpipe-core/src/pipes.rs
@@ -37,7 +37,7 @@ mod pipes {
async fn op_fetch(
#[string] url: String,
#[serde] options: Option<Value>,
- ) -> anyhow::Result<String> {
+ ) -> anyhow::Result<String, AnyError> {
let client = Client::new();
let mut request = client.get(&url);
@@ -92,7 +92,7 @@ mod pipes {
#[op2(async)]
#[string]
- async fn op_read_file(#[string] path: String) -> anyhow::Result<String> {
+ async fn op_read_file(#[string] path: String) -> anyhow::Result<String, AnyError> {
let current_dir = std::env::current_dir()?;
let full_path = current_dir.join(path);
tokio::fs::read_to_string(&full_path).await.map_err(|e| {
@@ -106,7 +106,7 @@ mod pipes {
async fn op_write_file(
#[string] path: String,
#[string] contents: String,
- ) -> anyhow::Result<()> {
+ ) -> anyhow::Result<(), AnyError> {
tokio::fs::write(&path, contents).await.map_err(|e| {
error!("Failed to write file '{}': {}", path, e);
AnyError::from(e)
@@ -115,7 +115,7 @@ mod pipes {
#[op2(async)]
#[string]
- async fn op_fetch_get(#[string] url: String) -> anyhow::Result<String> {
+ async fn op_fetch_get(#[string] url: String) -> anyhow::Result<String, AnyError> {
let response = reqwest::get(&url).await?;
let status = response.status();
let text = response.text().await?;
@@ -136,7 +136,7 @@ mod pipes {
async fn op_fetch_post(
#[string] url: String,
#[string] body: String,
- ) -> anyhow::Result<String> {
+ ) -> anyhow::Result<String, AnyError> {
let client = reqwest::Client::new();
// Create a HeaderMap and add the Content-Type header
@@ -160,7 +160,7 @@ mod pipes {
}
#[op2(async)]
- async fn op_set_timeout(delay: f64) -> anyhow::Result<()> {
+ async fn op_set_timeout(delay: f64) -> anyhow::Result<(), AnyError> {
tokio::time::sleep(std::time::Duration::from_millis(delay as u64)).await;
Ok(())
}
@@ -425,10 +425,10 @@ mod pipes {
.unwrap_or("unknown_pipe");
let dest_dir = screenpipe_dir.join("pipes").join(pipe_name);
- if dest_dir.exists() {
- info!("Pipe already exists: {:?}", dest_dir);
- return Ok(dest_dir);
- }
+ // if dest_dir.exists() {
+ // info!("Pipe already exists: {:?}", dest_dir);
+ // return Ok(dest_dir);
+ // }
tokio::fs::create_dir_all(&dest_dir).await?;
copy_local_folder(source_path, &dest_dir).await?;
diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rs
index 896d196ec..0fcd65050 100644
--- a/screenpipe-server/src/pipe_manager.rs
+++ b/screenpipe-server/src/pipe_manager.rs
@@ -1,5 +1,5 @@
use anyhow::Result;
-use log::{debug, error};
+use log::debug;
use screenpipe_core::{download_pipe, run_pipe};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -7,6 +7,7 @@ use std::future::Future;
use std::path::PathBuf;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
+use tracing::warn;
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct PipeInfo {
@@ -55,8 +56,16 @@ impl PipeManager {
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)?;
+ let mut config: Value = if config_path.exists() {
+ let config_str = tokio::fs::read_to_string(&config_path).await?;
+ serde_json::from_str(&config_str)?
+ } else {
+ tokio::fs::create_dir_all(&pipe_dir).await?;
+ serde_json::json!({
+ "id": id,
+ "enabled": false
+ })
+ };
if let Value::Object(existing_config) = &mut config {
if let Value::Object(updates) = new_config {
@@ -83,6 +92,24 @@ impl PipeManager {
pipes.iter().find(|pipe| pipe.id == id).cloned()
}
+ async fn load_pipe_info(pipe_id: String, config_path: PathBuf) -> PipeInfo {
+ let config = tokio::fs::read_to_string(&config_path)
+ .await
+ .and_then(|s| serde_json::from_str::<Value>(&s).map_err(Into::into))
+ .unwrap_or_else(|_| {
+ warn!("pipe {}: does not seem to have a config file", pipe_id);
+ Value::Null
+ });
+
+ PipeInfo {
+ id: pipe_id,
+ enabled: config
+ .get("enabled")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ config,
+ }
+ }
pub async fn list_pipes(&self) -> Vec<PipeInfo> {
let pipe_dir = self.screenpipe_dir.join("pipes");
let mut pipe_infos = Vec::new();
@@ -91,30 +118,11 @@ impl PipeManager {
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,
- })
- });
+ pipe_infos.push(Self::load_pipe_info(pipe_id, config_path));
}
}
- match futures::future::try_join_all(pipe_infos).await {
- Ok(infos) => infos,
- Err(e) => {
- error!("Error listing pipes: {}", e);
- Vec::new()
- }
- }
+ futures::future::join_all(pipe_infos).await
}
pub async fn download_pipe(&self, url: &str) -> Result<String> {
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 8feddb562..191129ea2 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -408,18 +408,26 @@ pub(crate) async fn add_tags(
State(state): State<Arc<AppState>>,
Path((content_type, id)): Path<(String, i64)>,
JsonResponse(payload): JsonResponse<AddTagsRequest>,
-) -> Result<JsonResponse<AddTagsResponse>, (StatusCode, String)> {
+) -> Result<JsonResponse<AddTagsResponse>, (StatusCode, JsonResponse<Value>)> {
let content_type = match content_type.as_str() {
"vision" => TagContentType::Vision,
"audio" => TagContentType::Audio,
- _ => return Err((StatusCode::BAD_REQUEST, "Invalid content type".to_string())),
+ _ => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": "Invalid content type"})),
+ ))
+ }
};
match state.db.add_tags(id, content_type, payload.tags).await {
Ok(_) => Ok(JsonResponse(AddTagsResponse { success: true })),
Err(e) => {
error!("Failed to add tags: {}", e);
- Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
+ Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ ))
}
}
}
@@ -428,18 +436,26 @@ pub(crate) async fn remove_tags(
State(state): State<Arc<AppState>>,
Path((content_type, id)): Path<(String, i64)>,
JsonResponse(payload): JsonResponse<RemoveTagsRequest>,
-) -> Result<JsonResponse<RemoveTagsResponse>, (StatusCode, String)> {
+) -> Result<JsonResponse<RemoveTagsResponse>, (StatusCode, JsonResponse<Value>)> {
let content_type = match content_type.as_str() {
"vision" => TagContentType::Vision,
"audio" => TagContentType::Audio,
- _ => return Err((StatusCode::BAD_REQUEST, "Invalid content type".to_string())),
+ _ => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": "Invalid content type"})),
+ ))
+ }
};
match state.db.remove_tags(id, content_type, payload.tags).await {
Ok(_) => Ok(JsonResponse(RemoveTagsResponse { success: true })),
Err(e) => {
error!("Failed to remove tag: {}", e);
- Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
+ Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ ))
}
}
}
@@ -548,7 +564,7 @@ struct UpdatePipeConfigRequest {
async fn download_pipe_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<DownloadPipeRequest>,
-) -> Result<JsonResponse<serde_json::Value>, (StatusCode, String)> {
+) -> Result<JsonResponse<serde_json::Value>, (StatusCode, JsonResponse<Value>)> {
debug!("Downloading pipe: {}", payload.url);
match download_pipe(&payload.url, state.screenpipe_dir.clone()).await {
Ok(pipe_dir) => {
@@ -561,7 +577,10 @@ async fn download_pipe_handler(
}
Err(e) => {
error!("Failed to download pipe: {}", e);
- Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
+ Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ ))
}
}
}
@@ -569,15 +588,9 @@ async fn download_pipe_handler(
async fn run_pipe_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<RunPipeRequest>,
-) -> Result<JsonResponse<Value>, (StatusCode, String)> {
+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
debug!("Starting pipe: {}", payload.pipe_id);
- // match state.pipe_manager.start_pipe(&payload.pipe_id).await {
- // Ok(_) => Ok(JsonResponse(json!({
- // "message": format!("Pipe {} started", payload.pipe_id),
- // "pipe_id": payload.pipe_id
- // }))),
- // Err(e) => Err((StatusCode::BAD_REQUEST, e)),
- // }
+
match state
.pipe_manager
@@ -593,14 +606,17 @@ async fn run_pipe_handler(
"message": format!("Pipe {} started", payload.pipe_id),
"pipe_id": payload.pipe_id
}))),
- Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())),
+ Err(e) => Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": e.to_string()})),
+ )),
}
}
async fn stop_pipe_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<RunPipeRequest>,
-) -> Result<JsonResponse<Value>, (StatusCode, String)> {
+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
debug!("Stopping pipe: {}", payload.pipe_id);
match state
.pipe_manager
@@ -616,14 +632,17 @@ async fn stop_pipe_handler(
"message": format!("Pipe {} stopped", payload.pipe_id),
"pipe_id": payload.pipe_id
}))),
- Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())),
+ Err(e) => Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": e.to_string()})),
+ )),
}
}
async fn update_pipe_config_handler(
State(state): State<Arc<AppState>>,
JsonResponse(payload): JsonResponse<UpdatePipeConfigRequest>,
-) -> Result<JsonResponse<Value>, (StatusCode, String)> {
+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
debug!("Updating pipe config for: {}", payload.pipe_id);
match state
.pipe_manager
@@ -634,18 +653,24 @@ 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.to_string())),
+ Err(e) => Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": e.to_string()})),
+ )),
}
}
async fn get_pipe_info_handler(
State(state): State<Arc<AppState>>,
Path(pipe_id): Path<String>,
-) -> Result<JsonResponse<PipeInfo>, (StatusCode, String)> {
+) -> Result<JsonResponse<PipeInfo>, (StatusCode, JsonResponse<Value>)> {
debug!("Getting pipe info for: {}", pipe_id);
match state.pipe_manager.get_pipe_info(&pipe_id).await {
Some(info) => Ok(JsonResponse(info)),
- None => Err((StatusCode::NOT_FOUND, "Pipe not found".to_string())),
+ None => Err((
+ StatusCode::NOT_FOUND,
+ JsonResponse(json!({"error": "Pipe not found"})),
+ )),
}
}
@@ -843,6 +868,10 @@ curl -X POST "http://localhost:3030/pipes/download" \
-H "Content-Type: application/json" \
-d '{"url": "./examples/typescript/pipe-stream-ocr-text"}' | jq
+curl -X POST "http://localhost:3030/pipes/download" \
+ -H "Content-Type: application/json" \
+ -d '{"url": "./examples/typescript/pipe-security-check"}' | jq
+
curl -X POST "http://localhost:3030/pipes/download" \
-H "Content-Type: application/json" \
@@ -857,6 +886,11 @@ curl -X POST "http://localhost:3030/pipes/enable" \
-H "Content-Type: application/json" \
-d '{"pipe_id": "pipe-stream-ocr-text"}' | jq
+
+ curl -X POST "http://localhost:3030/pipes/enable" \
+ -H "Content-Type: application/json" \
+ -d '{"pipe_id": "pipe-security-check"}' | jq
+
# Stop a pipe
curl -X POST "http://localhost:3030/pipes/disable" \
-H "Content-Type: application/json" \