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(connections): wire connected integrations into Pi's system prompt for chat & pipes (#3254)
Ansh Grover74853994d6cb
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex 7b083566a..81526a080 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -170,7 +170,7 @@ function buildSystemPrompt(): string {const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;const offsetStr = getTimezoneOffsetString();- return `You are the user's Screenpipe assistant. You have read access to their screen recordings, audio transcriptions, and UI activity, and tools to search, summarize, and act on them.+ return `You are the user's Screenpipe assistant. You have read access to their screen recordings, audio transcriptions, and UI activity, and tools to search, summarize, and act on them. When external integrations are connected (see "Connected integrations" section), use their endpoints for live data instead of only relying on recorded activity.# Voice and length — the most important rule@@ -204,9 +204,14 @@ When summarizing what the user did, write like a friend recapping their day. Con- If a search returns empty, silently widen and retry. Don't enumerate possibilities or ask the user to choose.- Never say "no data found" after one filtered search — verify first with an unfiltered time-only search.+# Connection write policy++Never POST, PUT, or PATCH to a connection proxy unless the user explicitly asks you to create, write, or modify something in that service. For ambiguous requests, read first. Ask before writing.+# Tool selection-- "meeting / call / conversation / what did I/they say" → search with content_type: "audio", no q param+- "upcoming meetings / calendar events / what's on my calendar / schedule" → if a calendar integration is connected (google-calendar, apple-calendar), call its events endpoint first; only fall back to audio search if no calendar is connected+- "meeting / call / conversation / what did I/they say" → search with content_type: "audio", no q param (for past meetings/calls captured by screenpipe)- "how long / time spent / which apps / most used" → activity-summary (not raw frame counts or SQL)- "what was on screen / what was I reading" → search with content_type: "all" or "accessibility"- "what was I doing" → activity-summary first; the windows field usually has enough without further searches@@ -262,6 +267,17 @@ User's timezone: ${timezone} (UTC${offsetStr})User's local time: ${now.toLocaleString()}`;}+function buildConnectionsContext(+ connections: Array<{ id: string; name: string; category?: string; description?: string }>+): string {+ const withDesc = connections.filter((c) => c.description);+ if (withDesc.length === 0) return "";+ const entries = withDesc+ .map((c) => `## ${c.name} (${c.id})\n${c.description}`)+ .join("\n\n");+ return `\n\n# Connected integrations\n\nThe user has connected the following external services. Use the endpoints listed under each to fetch live data when relevant. All endpoints are on http://localhost:3030 and require \`-H "Authorization: Bearer $SCREENPIPE_API_AUTH_KEY"\`.\n\n${entries}`;+}+interface SearchResult {type: "OCR" | "Audio" | "UI";content: {@@ -1304,7 +1320,7 @@ export function StandaloneChat({// filter popover so users can mention them directly with @id — helps the// agent pick the right connection for a query instead of having to guess.const [connections, setConnections] = useState<- Array<{ id: string; name: string; category?: string }>+ Array<{ id: string; name: string; category?: string; description?: string }>>([]);// Watch the input section's width so suggestion chips can collapse into// a popover on narrow chat columns.@@ -1325,11 +1341,11 @@ export function StandaloneChat({const res = await localFetch("/connections");if (!res.ok) return;const json = (await res.json()) as {- data?: Array<{ id: string; name: string; connected: boolean; category?: string }>;+ data?: Array<{ id: string; name: string; connected: boolean; category?: string; description?: string }>;};const list = (json.data ?? []).filter((c) => c.connected)- .map((c) => ({ id: c.id, name: c.name, category: c.category }));+ .map((c) => ({ id: c.id, name: c.name, category: c.category, description: c.description }));if (!cancelled) setConnections(list);} catch {// silent — filter just won't surface connections, no UI regression@@ -1340,6 +1356,29 @@ export function StandaloneChat({};}, []);+ // Re-fetch connections whenever the window becomes visible — picks up any+ // integrations connected in Settings while the chat was open.+ useEffect(() => {+ const fetchConnections = async () => {+ try {+ const res = await localFetch("/connections");+ if (!res.ok) return;+ const json = (await res.json()) as {+ data?: Array<{ id: string; name: string; connected: boolean; category?: string; description?: string }>;+ };+ const list = (json.data ?? [])+ .filter((c) => c.connected)+ .map((c) => ({ id: c.id, name: c.name, category: c.category, description: c.description }));+ setConnections(list);+ } catch { /* silent */ }+ };+ const onVisible = () => {+ if (document.visibilityState === "visible") fetchConnections();+ };+ document.addEventListener("visibilitychange", onVisible);+ return () => document.removeEventListener("visibilitychange", onVisible);+ }, []);+// Custom summary templates (persisted in settings)const [customTemplates, setCustomTemplates] = useState<CustomTemplate[]>([]);@@ -2542,7 +2581,8 @@ export function StandaloneChat({// This is passed via --append-system-prompt to Pi, enabling Anthropic prompt// caching (90% input cost reduction on subsequent messages).const presetPrompt = p.prompt || "";- const systemPrompt = `${buildSystemPrompt()}\n\n${presetPrompt}`.trim() || null;+ const connectionsCtx = buildConnectionsContext(connections);+ const systemPrompt = `${buildSystemPrompt()}\n\n${presetPrompt}${connectionsCtx}`.trim() || null;return {provider: p.provider,url: p.url || "",@@ -2552,7 +2592,26 @@ export function StandaloneChat({systemPrompt,};// eslint-disable-next-line react-hooks/exhaustive-deps- }, [activePreset?.provider, activePreset?.url, activePreset?.model, activePreset?.apiKey, (activePreset as any)?.maxTokens, activePreset?.prompt]);+ }, [activePreset?.provider, activePreset?.url, activePreset?.model, activePreset?.apiKey, (activePreset as any)?.maxTokens, activePreset?.prompt, connections]);++ // When connections change (e.g., user connected Google Calendar in Settings),+ // silently restart Pi if the system prompt changed and no message is in-flight.+ useEffect(() => {+ if (connections.length === 0) return;+ const config = buildProviderConfig();+ if (!config) return;+ const running = piRunningConfigRef.current;+ if (!running || running.systemPrompt === config.systemPrompt) return;+ if (piMessageIdRef.current) return; // don't interrupt an active turn+ commands.piUpdateConfig(settings.user?.token ?? null, config)+ .then(() => {+ if (piRunningConfigRef.current) {+ piRunningConfigRef.current = { ...piRunningConfigRef.current, systemPrompt: config.systemPrompt };+ }+ })+ .catch(() => {});+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [connections]);// Check Pi status on mount — Pi is auto-started at app boot by RustuseEffect(() => {diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rsindex e54114480..ad2187398 100644--- a/crates/screenpipe-core/src/pipes/mod.rs+++ b/crates/screenpipe-core/src/pipes/mod.rs@@ -1194,6 +1194,9 @@ pub struct PipeManager {token_registry: Option<Arc<dyn permissions::PipeTokenRegistry>>,/// Extra context appended to every pipe prompt (e.g. connected integrations).extra_context: Option<String>,+ /// Connected integrations context injected into every pipe *system* prompt.+ /// Set by the engine layer (which owns the SecretStore) via `set_connections_context`.+ connections_context: Option<String>,/// Local API auth key — injected into pipe subprocesses as SCREENPIPE_LOCAL_API_KEY/// so pipes can authenticate to localhost:3030 when API auth is enabled.local_api_key: Option<String>,@@ -1235,6 +1238,7 @@ impl PipeManager {)),token_registry: None,extra_context: None,+ connections_context: None,local_api_key: None,fallback_registry: registry,}@@ -1265,6 +1269,18 @@ impl PipeManager {self.extra_context = None;}+ /// Set connected integrations context for the system prompt.+ /// Called by the engine layer after computing it via `render_context`.+ pub fn set_connections_context(&mut self, ctx: String) {+ self.connections_context = if ctx.is_empty() { None } else { Some(ctx) };+ }++ /// Expose the API port so callers (e.g. engine layer) can pass it to+ /// `render_context` without needing a separate field.+ pub fn api_port(&self) -> u16 {+ self.api_port+ }+/// Set the local API auth key. Injected into pipe subprocesses as/// `SCREENPIPE_LOCAL_API_KEY` so they can authenticate to localhost.///@@ -1824,8 +1840,12 @@ impl PipeManager {let pipe_dir = self.pipes_dir.clone().join(name);- let pipe_system_prompt =- render_pipe_system_prompt(&body, self.api_port, preset_prompt.as_deref());+ let pipe_system_prompt = render_pipe_system_prompt(+ &body,+ self.api_port,+ preset_prompt.as_deref(),+ self.connections_context.as_deref(),+ );let prompt = self.render_prompt(&config, &body, preset_prompt.as_deref());let pipe_name = name.to_string();@@ -2300,8 +2320,12 @@ impl PipeManager {.unwrap_or(false);// Build prompt with context header- let pipe_system_prompt =- render_pipe_system_prompt(&body, self.api_port, preset_prompt.as_deref());+ let pipe_system_prompt = render_pipe_system_prompt(+ &body,+ self.api_port,+ preset_prompt.as_deref(),+ self.connections_context.as_deref(),+ );let prompt = self.render_prompt(&config, &body, preset_prompt.as_deref());// Shared PID — set synchronously by the executor right after spawn@@ -3049,6 +3073,7 @@ impl PipeManager {let api_port = self.api_port;let token_registry = self.token_registry.clone();let extra_context = self.extra_context.clone();+ let connections_context = self.connections_context.clone();let _local_api_key = self.local_api_key.clone();let handle = tokio::spawn(async move {@@ -3411,8 +3436,12 @@ impl PipeManager {let pipe_dir = pipes_dir.join(name);- let pipe_system_prompt =- render_pipe_system_prompt(body, api_port, preset_prompt.as_deref());+ let pipe_system_prompt = render_pipe_system_prompt(+ body,+ api_port,+ preset_prompt.as_deref(),+ connections_context.as_deref(),+ );let prompt = render_prompt_with_port(config,body,@@ -4018,7 +4047,12 @@ pub fn serialize_pipe(config: &PipeConfig, body: &str) -> Result<String> {/// Contains the pipe body (instructions from pipe.md) and the preset system prompt./// These are identical across runs and across turns within a run, making them/// ideal for Anthropic prompt caching (90% input cost reduction on cache hits).-fn render_pipe_system_prompt(body: &str, api_port: u16, system_prompt: Option<&str>) -> String {+fn render_pipe_system_prompt(+ body: &str,+ api_port: u16,+ system_prompt: Option<&str>,+ connections_context: Option<&str>,+) -> String {let os = std::env::consts::OS;let mut sys = String::new();@@ -4038,6 +4072,13 @@ fn render_pipe_system_prompt(body: &str, api_port: u16, system_prompt: Option<&s"CRITICAL: You ARE this pipe. You are already running inside it. NEVER run `screenpipe pipe run` — that would create a recursive duplicate. Execute the task directly using the tools available to you (bash, file I/O, HTTP requests, etc.).\n\nOS: {os}\nOutput directory: ./output/\nScreenpipe API: http://localhost:{api_port}{api_auth_note}\nPrefer bun/TypeScript for scripts. Python may not be installed.\nSend notifications via POST http://localhost:11435/notify with {{\"title\": \"...\", \"body\": \"...\"}}. Body supports markdown. File links MUST use absolute paths (e.g. [View log](/Users/me/file.md)), never relative paths like ./output/file.md — relative paths break the notification link handler.\n\n"));sys.push_str(body);++ if let Some(ctx) = connections_context {+ sys.push_str("\n\n");+ sys.push_str(ctx);+ sys.push_str("\n\nConnection write policy: never POST, PUT, or PATCH to a connection proxy unless the pipe body or user explicitly asks you to create, write, or modify something in that service. Read first, write only when clearly instructed.");+ }+sys}@@ -5136,7 +5177,7 @@ mod tests {assert!(prompt.contains("Time range:"));assert!(prompt.contains("Do the work described above now."));// Port / body go into system prompt, not user prompt- let sys = render_pipe_system_prompt("body text", 3031, None);+ let sys = render_pipe_system_prompt("body text", 3031, None, None);assert!(sys.contains("http://localhost:3031"));assert!(!sys.contains("http://localhost:3030"));assert!(sys.contains("body text"));@@ -5163,7 +5204,7 @@ mod tests {privacy_filter: false,trigger: None,};- let sys = render_pipe_system_prompt("hello", 3030, None);+ let sys = render_pipe_system_prompt("hello", 3030, None, None);assert!(sys.contains("http://localhost:3030"));}@@ -5188,7 +5229,7 @@ mod tests {privacy_filter: false,trigger: None,};- let sys = render_pipe_system_prompt("body text", 3030, Some("You are a helpful assistant"));+ let sys = render_pipe_system_prompt("body text", 3030, Some("You are a helpful assistant"), None);assert!(sys.starts_with("You are a helpful assistant\n\n"));assert!(sys.contains("body text"));assert!(sys.contains("http://localhost:3030"));@@ -5215,14 +5256,14 @@ mod tests {privacy_filter: false,trigger: None,};- let sys = render_pipe_system_prompt("body text", 3030, None);+ let sys = render_pipe_system_prompt("body text", 3030, None, None);assert!(!sys.contains("System prompt:"));assert!(sys.contains("body text"));}#[test]fn test_system_prompt_contains_anti_recursion_warning() {- let sys = render_pipe_system_prompt("task body", 3030, None);+ let sys = render_pipe_system_prompt("task body", 3030, None, None);assert!(sys.contains("NEVER run `screenpipe pipe run`"));assert!(sys.contains("You ARE this pipe"));}diff --git a/crates/screenpipe-engine/src/pipes_api.rs b/crates/screenpipe-engine/src/pipes_api.rsindex 79cb93b80..4c17712cc 100644--- a/crates/screenpipe-engine/src/pipes_api.rs+++ b/crates/screenpipe-engine/src/pipes_api.rs@@ -9,6 +9,7 @@use axum::extract::{Path, Query, State};use axum::http::StatusCode;use axum::Json;+use screenpipe_connect::connections::render_context;use screenpipe_core::pipes::PipeManager;use screenpipe_secrets::SecretStore;use serde::Deserialize;@@ -196,6 +197,14 @@ pub async fn run_pipe_now(}}+ // Refresh connections context so the pipe system prompt includes currently+ // connected integrations (Google Calendar, Gmail, etc.).+ let screenpipe_dir = mgr.pipes_dir().parent().unwrap_or(mgr.pipes_dir()).to_path_buf();+ let api_port = mgr.api_port();+ let ss = secret_store.as_ref().map(|e| e.0.as_ref());+ let conn_ctx = render_context(&screenpipe_dir, api_port, ss).await;+ mgr.set_connections_context(conn_ctx);+let result = mgr.start_pipe_background(&id).await;// Restore previous extra context