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: pipe.input.type etc. claude computer use pipe
Louis Beaumont8a24ef328171
diff --git a/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/README.md b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/README.mdnew file mode 100644index 000000000..6d3f66599--- /dev/null+++ b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/README.md@@ -0,0 +1 @@+WIP\ No newline at end of filediff --git a/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/deno.json b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/deno.jsonnew file mode 100644index 000000000..55aa44e5b--- /dev/null+++ b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/deno.json@@ -0,0 +1,9 @@+{+ "imports": {+ "fs": "node:fs",+ "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts",+ "ai": "npm:ai",+ "ollama-ai-provider": "npm:ollama-ai-provider",+ "zod": "npm:zod"+ }+}diff --git a/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.json b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.jsonnew file mode 100644index 000000000..7222e7e6b--- /dev/null+++ b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.json@@ -0,0 +1,15 @@+{+ "fields": [+ {+ "name": "interval",+ "type": "number",+ "default": 30,+ "description": "interval in seconds to process meeting data"+ },+ {+ "name": "anthropicApiKey",+ "type": "string",+ "description": "Anthropic API key for Claude"+ }+ ]+}diff --git a/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.ts b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.tsnew file mode 100644index 000000000..9cb3ad034--- /dev/null+++ b/examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.ts@@ -0,0 +1,220 @@+import { pipe, ContentItem } from "screenpipe";+import Anthropic from "npm:@anthropic-ai/sdk";++let anthropic: Anthropic;+let meetingNotes = "";+let actionItems: string[] = [];++// VERY EXPERIMENTAL++// this pipe assist my meetings by taking notes and suggesting things i could do or say+// during the meeting by writing in my note taking software opened in split screen++async function meetingAssistant() {+ console.log("starting meeting assistant");++ const config = pipe.loadPipeConfig();+ const interval = config.interval * 1000 || 30000; // Default to 30 seconds if not specified++ // Initialize Anthropic client with API key from config+ anthropic = new Anthropic({+ apiKey: config.anthropicApiKey,+ });++ pipe.scheduler+ .task("processMeetingData")+ .every(interval)+ .do(async () => {+ try {+ const screenData = await captureScreen();+ const audioData = await captureAudio();++ if (screenData && audioData) {+ await processData(screenData, audioData);+ await generateSuggestions();+ }+ } catch (error) {+ console.error("error in meeting assistant:", error);+ }+ });++ await pipe.scheduler.start();+}++async function captureScreen() {+ const now = new Date();+ const intervalAgo = new Date(now.getTime() - 30000); // Last 30 seconds++ return await pipe.queryScreenpipe({+ startTime: intervalAgo.toISOString(),+ endTime: now.toISOString(),+ limit: 1,+ contentType: "ocr",+ includeFrames: true,+ });+}++async function captureAudio() {+ const now = new Date();+ const intervalAgo = new Date(now.getTime() - 30000); // Last 30 seconds++ return await pipe.queryScreenpipe({+ startTime: intervalAgo.toISOString(),+ endTime: now.toISOString(),+ limit: 1,+ contentType: "audio",+ });+}++async function processData(+ screenData: ContentItem[],+ audioData: ContentItem[]+) {+ if (screenData.length === 0 || audioData.length === 0) {+ console.log("No new data to process");+ return;+ }++ const screenContent =+ screenData[0].type === "OCR" ? screenData[0].content.text : "";+ const audioContent =+ audioData[0].type === "STT" ? audioData[0].content.text : "";++ const tools = [+ {+ type: "computer_20241022",+ name: "computer",+ display_width_px: 1920,+ display_height_px: 1080,+ },+ ];++ let response = await anthropic.beta.messages.create({+ model: "claude-3-5-sonnet-20241022",+ max_tokens: 1024,+ tools: tools,+ messages: [+ {+ role: "user",+ content: [+ {+ type: "text",+ text: `Analyze this meeting data and update the meeting notes. Extract any action items.++Screen content: ${screenContent}+Audio content: ${audioContent}++Current meeting notes:+${meetingNotes}++Use the computer tools to save the updated notes and action items.`,+ },+ {+ type: "image",+ source: {+ type: "base64",+ media_type: "image/png",+ data:+ screenData[0].type === "OCR" ? screenData[0].content.frame : "",+ },+ },+ ],+ },+ ],+ betas: ["computer-use-2024-10-22"],+ });++ // Implement agent loop to handle tool use requests+ while (response.stop_reason === "tool_use") {+ const toolUse = response.tool_calls[0];+ const toolResult = await executeToolUse(toolUse);++ // Continue the conversation with the tool result+ response = await anthropic.beta.messages.create({+ model: "claude-3-5-sonnet-20241022",+ max_tokens: 1024,+ tools: tools,+ messages: [+ ...response.messages,+ {+ role: "user",+ content: [+ { type: "tool_result", id: toolUse.id, output: toolResult },+ ],+ },+ ],+ betas: ["computer-use-2024-10-22"],+ });+ }++ // Process the final response+ const result = JSON.parse(response.content[0].text);+ meetingNotes = result.updatedNotes;+ actionItems = [...actionItems, ...result.newActionItems];++ console.log("Meeting notes updated");+ console.log("New action items:", result.newActionItems);+}++async function executeToolUse(toolUse: any) {+ const { name, arguments: args } = toolUse;++ if (name === "computer") {+ const parsedArgs = JSON.parse(args);+ if (parsedArgs.action === "type") {+ return await pipe.input.type(parsedArgs.text);+ }+ // Add other computer actions as needed+ }++ // Return appropriate result based on the tool used+ return "Tool execution completed";+}++async function generateSuggestions() {+ const response = await anthropic.messages.create({+ model: "claude-3-opus-20240229",+ max_tokens: 1024,+ messages: [+ {+ role: "user",+ content: `Based on the current meeting notes and action items, suggest 3 different paths the conversation could take next. Each suggestion should be concise and actionable.++Meeting notes:+${meetingNotes}++Action items:+${actionItems.join("\n")}++Return a JSON object with a 'suggestions' field containing an array of 3 suggestion strings.`,+ },+ ],+ });++ const result = JSON.parse(response.content[0].text);+ console.log("Suggestions for next steps:");+ result.suggestions.forEach((suggestion: string, index: number) => {+ console.log(`${index + 1}. ${suggestion}`);+ });++ await pipe.sendDesktopNotification({+ title: "Meeting Assistant Suggestions",+ body: result.suggestions.join("\n"),+ });+}++meetingAssistant();+++/**++# these are mandatory env variables+export SCREENPIPE_DIR="$HOME/.screenpipe"+export PIPE_ID="pipe-anthropic-computer-use-meeting-assistant"+export PIPE_FILE="pipe.ts"+export PIPE_DIR="$SCREENPIPE_DIR/pipes/pipe-anthropic-computer-use-meeting-assistant"++deno run --allow-read --allow-write --allow-env --allow-net --allow-run --allow-sys examples/typescript/pipe-anthropic-computer-use-meeting-assistant/pipe.ts+ */++diff --git a/screenpipe-js/main.ts b/screenpipe-js/main.tsindex 4557c6921..ef231176f 100644--- a/screenpipe-js/main.ts+++ b/screenpipe-js/main.ts@@ -99,10 +99,10 @@ export interface PaginationInfo {/*** Structure of the response from a Screenpipe query.*/- export interface ScreenpipeResponse {- data: ContentItem[];- pagination: PaginationInfo;- }+export interface ScreenpipeResponse {+ data: ContentItem[];+ pagination: PaginationInfo;+}/*** Parsed config@@ -425,6 +425,16 @@ class Scheduler {}}+export type InputAction =+ | { type: "WriteText"; data: string }+ | { type: "KeyPress"; data: string }+ | { type: "MouseMove"; data: { x: number; y: number } }+ | { type: "MouseClick"; data: "left" | "right" | "middle" };++interface InputControlResponse {+ success: boolean;+}+/*** The pipe object is used to interact with the screenpipe higher level functions.*@@ -504,4 +514,64 @@ export const pipe = {* ```*/scheduler: new Scheduler(),+ /**+ * Experimental input control methods.+ * Use with caution as these directly manipulate input devices.+ */+ input: {+ /**+ * Simulate typing text.+ * @example+ * pipe.input.type("Hello, Screenpipe!");+ */+ type: (text: string): Promise<boolean> => {+ return sendInputControl({ type: "WriteText", data: text });+ },++ /**+ * Simulate a key press.+ * @example+ * pipe.input.press("enter");+ */+ press: (key: string): Promise<boolean> => {+ return sendInputControl({ type: "KeyPress", data: key });+ },++ /**+ * Move the mouse to absolute coordinates.+ * @example+ * pipe.input.moveMouse(100, 200);+ */+ moveMouse: (x: number, y: number): Promise<boolean> => {+ return sendInputControl({ type: "MouseMove", data: { x, y } });+ },++ /**+ * Simulate a mouse click.+ * @example+ * pipe.input.click("left");+ */+ click: (button: "left" | "right" | "middle"): Promise<boolean> => {+ return sendInputControl({ type: "MouseClick", data: button });+ },+ },};++async function sendInputControl(action: InputAction): Promise<boolean> {+ const apiUrl = process.env.SCREENPIPE_SERVER_URL || "http://localhost:3030";+ try {+ const response = await fetch(`${apiUrl}/experimental/input_control`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ action }),+ });+ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }+ const data: InputControlResponse = await response.json();+ return data.success;+ } catch (error) {+ console.error("failed to control input:", error);+ return false;+ }+}diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 0453a76a4..8bb760871 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -91,6 +91,9 @@ uuid = "1.5.0"tempfile = { version = "3.3.0", optional = true }url = { version = "2.2.0", optional = true }++enigo = { version = "0.2.1", optional = true }+[dev-dependencies]tempfile = "3.3.0"@@ -115,6 +118,7 @@ cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]pipes = ["screenpipe-core/pipes", "tempfile", "url"]llm = ["screenpipe-core/llm"]beta = ["screenpipe-core/beta", "dep:screenpipe-actions"]+experimental = ["enigo"][[bin]]name = "screenpipe"diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex 24558f43a..fa0775792 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -269,7 +269,6 @@ async fn record_audio(friend_wearable_uid: Option<String>,audio_transcription_engine: Arc<AudioTranscriptionEngine>,) -> Result<()> {- const OVERLAP_DURATION: Duration = Duration::from_secs(2);let mut handles: HashMap<String, JoinHandle<()>> = HashMap::new();let mut previous_transcript = "".to_string();let mut previous_transcript_id: Option<i64> = None;diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex c24b0b0af..c1b442c20 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -40,6 +40,10 @@ use tokio::net::TcpListener;use tower_http::trace::TraceLayer;use tower_http::{cors::CorsLayer, trace::DefaultMakeSpan};+// At the top of the file, add:+#[cfg(feature = "experimental")]+use enigo::{Enigo, Key, Settings};+pub struct AppState {pub db: Arc<DatabaseManager>,pub vision_control: Arc<AtomicBool>,@@ -504,7 +508,9 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<Helet audio_status = if state.audio_disabled {"disabled"- } else if now.signed_duration_since(state.app_start_time) < chrono::Duration::from_std(app_start_threshold).unwrap() {+ } else if now.signed_duration_since(state.app_start_time)+ < chrono::Duration::from_std(app_start_threshold).unwrap()+ {"ok" // Consider audio healthy if app started recently} else {match last_audio {@@ -857,30 +863,94 @@ async fn execute_raw_sql(}}-#[cfg(not(feature = "llm"))]-pub fn create_router() -> Router<Arc<AppState>> {- Router::new()- .route("/search", get(search))- .route("/audio/list", get(api_list_audio_devices))- .route("/vision/list", post(api_list_monitors))- .route(- "/tags/:content_type/:id",- post(add_tags).delete(remove_tags),+#[cfg(feature = "experimental")]+async fn input_control_handler(+ JsonResponse(payload): JsonResponse<InputControlRequest>,+) -> Result<JsonResponse<InputControlResponse>, (StatusCode, JsonResponse<Value>)> {+ use enigo::{Keyboard, Mouse};++ info!("input control handler {:?}", payload);+ let mut enigo = Enigo::new(&Settings::default()).map_err(|e| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": format!("failed to initialize enigo: {}", e)})),)- .route("/pipes/info/:pipe_id", get(get_pipe_info_handler))- .route("/pipes/list", get(list_pipes_handler))- .route("/pipes/download", post(download_pipe_handler))- .route("/pipes/enable", post(run_pipe_handler))- .route("/pipes/disable", post(stop_pipe_handler))- .route("/pipes/update", post(update_pipe_config_handler))- .route("/experimental/frames/merge", post(merge_frames_handler))- .route("/health", get(health_check))- .route("/raw_sql", post(execute_raw_sql))+ })?;++ match payload.action {+ InputAction::KeyPress(key) => {+ let _ = enigo.key(key_from_string(&key).unwrap(), enigo::Direction::Press);+ }+ InputAction::MouseMove { x, y } => {+ let _ = enigo.move_mouse(x, y, enigo::Coordinate::Abs);+ }+ InputAction::MouseClick(button) => {+ let _ = enigo.button(+ mouse_button_from_string(&button).unwrap(),+ enigo::Direction::Press,+ );+ }+ InputAction::WriteText(text) => {+ let _ = enigo.text(&text);+ }+ }++ Ok(JsonResponse(InputControlResponse { success: true }))+}++#[cfg(feature = "experimental")]+fn key_from_string(key: &str) -> Result<Key, (StatusCode, JsonResponse<Value>)> {+ match key {+ "enter" => Ok(Key::Return),+ "space" => Ok(Key::Space),+ // Add more key mappings as needed+ _ => Err((+ StatusCode::BAD_REQUEST,+ JsonResponse(json!({"error": format!("Unsupported key: {}", key)})),+ )),+ }+}++#[cfg(feature = "experimental")]+fn mouse_button_from_string(+ button: &str,+) -> Result<enigo::Button, (StatusCode, JsonResponse<Value>)> {+ match button {+ "left" => Ok(enigo::Button::Left),+ "right" => Ok(enigo::Button::Right),+ // Add more button mappings as needed+ _ => Err((+ StatusCode::BAD_REQUEST,+ JsonResponse(json!({"error": format!("Unsupported mouse button: {}", button)})),+ )),+ }+}++// Add these new structs:+#[cfg(feature = "experimental")]+#[derive(Deserialize, Debug)]+struct InputControlRequest {+ action: InputAction,+}++#[cfg(feature = "experimental")]+#[derive(Deserialize, Debug)]+#[serde(tag = "type", content = "data")]+enum InputAction {+ KeyPress(String),+ MouseMove { x: i32, y: i32 },+ MouseClick(String),+ WriteText(String),+}++#[cfg(feature = "experimental")]+#[derive(Serialize)]+struct InputControlResponse {+ success: bool,}-#[cfg(feature = "llm")]pub fn create_router() -> Router<Arc<AppState>> {- Router::new()+ let router = Router::new().route("/search", get(search)).route("/audio/list", get(api_list_audio_devices)).route("/vision/list", post(api_list_monitors))@@ -896,9 +966,17 @@ pub fn create_router() -> Router<Arc<AppState>> {.route("/pipes/update", post(update_pipe_config_handler)).route("/experimental/frames/merge", post(merge_frames_handler)).route("/health", get(health_check))- .route("/raw_sql", post(execute_raw_sql))- .route("/llm/chat", post(llm_chat_handler))+ .route("/raw_sql", post(execute_raw_sql));++ #[cfg(feature = "llm")]+ let router = router.route("/llm/chat", post(llm_chat_handler));++ #[cfg(feature = "experimental")]+ let router = router.route("/experimental/input_control", post(input_control_handler));++ router}+/*Curl commands for reference:@@ -1108,3 +1186,4 @@ MERGED_VIDEO_PATH=$(echo "$MERGE_RESPONSE" | jq -r '.video_path')echo "Merged Video Path: $MERGED_VIDEO_PATH"*/+