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
fix: write pipe's provider config to Pi models.json so Ollama/OpenAI models resolve
Louis Beaumontdaf514968389
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rsindex 15c27a832..fffbc3614 100644--- a/crates/screenpipe-core/src/agents/pi.rs+++ b/crates/screenpipe-core/src/agents/pi.rs@@ -14,7 +14,7 @@ use std::path::{Path, PathBuf};use tracing::{debug, error, info, warn};const PI_PACKAGE: &str = "@mariozechner/pi-coding-agent";-const SCREENPIPE_API_URL: &str = "https://api.screenpi.pe/v1";+pub const SCREENPIPE_API_URL: &str = "https://api.screenpi.pe/v1";/// Returns the screenpipe cloud models array as a serde_json::Value./// Shared between server-side pipe executor and desktop Pi chat so the@@ -103,12 +103,23 @@ impl PiExecutor {Ok(())}- /// Merge screenpipe provider into pi's existing config files.+ /// Merge screenpipe provider (and optionally the pipe's own provider) into+ /// pi's existing config files.////// Unlike the old `write_pi_config`, this preserves any existing providers/// and auth credentials the user set up via `pi /login` or by editing/// `~/.pi/agent/auth.json` directly.- pub fn ensure_pi_config(user_token: Option<&str>, api_url: &str) -> Result<()> {+ ///+ /// When a pipe uses a non-screenpipe provider (e.g. ollama, openai), pass+ /// the resolved `provider`, `model`, and optional `provider_url` so the+ /// corresponding entry is written to `models.json`.+ pub fn ensure_pi_config(+ user_token: Option<&str>,+ api_url: &str,+ provider: Option<&str>,+ model: Option<&str>,+ provider_url: Option<&str>,+ ) -> Result<()> {let config_dir = get_pi_config_dir()?;std::fs::create_dir_all(&config_dir)?;@@ -138,6 +149,51 @@ impl PiExecutor {models_config = json!({"providers": {"screenpipe": screenpipe_provider}});}+ // Add the pipe's own provider (ollama, openai, custom) if specified+ if let (Some(prov), Some(mdl)) = (provider, model) {+ if prov != "screenpipe" {+ let (pi_provider_name, base_url, api_key) = match prov {+ "ollama" => (+ "ollama",+ provider_url.unwrap_or("http://localhost:11434/v1"),+ "ollama",+ ),+ "openai" => (+ "openai-byok",+ provider_url.unwrap_or("https://api.openai.com/v1"),+ "OPENAI_API_KEY",+ ),+ other => (other, provider_url.unwrap_or(""), "CUSTOM_API_KEY"),+ };++ let user_provider = json!({+ "baseUrl": base_url,+ "api": "openai-completions",+ "apiKey": api_key,+ "models": [{+ "id": mdl,+ "name": mdl,+ "input": ["text"],+ "contextWindow": 128000,+ "maxTokens": 16384,+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}+ }]+ });++ if let Some(providers) = models_config+ .get_mut("providers")+ .and_then(|p| p.as_object_mut())+ {+ providers.insert(pi_provider_name.to_string(), user_provider);+ }++ info!(+ "pi config: added provider '{}' with model '{}'",+ pi_provider_name, mdl+ );+ }+ }+std::fs::write(&models_path, serde_json::to_string_pretty(&models_config)?)?;// -- auth.json: merge screenpipe token, preserve other providers --@@ -180,7 +236,13 @@ impl AgentExecutor for PiExecutor {provider: Option<&str>,pid_tx: Option<tokio::sync::oneshot::Sender<u32>>,) -> Result<AgentOutput> {- Self::ensure_pi_config(self.user_token.as_deref(), &self.api_url)?;+ Self::ensure_pi_config(+ self.user_token.as_deref(),+ &self.api_url,+ provider,+ Some(model),+ None, // URL resolved from provider name defaults+ )?;Self::ensure_screenpipe_skill(working_dir)?;Self::ensure_web_search_extension(working_dir)?;@@ -457,3 +519,43 @@ pub fn kill_process_group(pid: u32) -> Result<()> {}Ok(())}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_ensure_pi_config_adds_ollama_provider() {+ // Call ensure_pi_config with ollama provider info+ PiExecutor::ensure_pi_config(+ None,+ SCREENPIPE_API_URL,+ Some("ollama"),+ Some("qwen3:8b"),+ Some("http://localhost:11434/v1"),+ )+ .expect("ensure_pi_config should succeed");++ // Read models.json and verify ollama provider was added+ let config_dir = get_pi_config_dir().unwrap();+ let models_path = config_dir.join("models.json");+ let content = std::fs::read_to_string(&models_path).unwrap();+ let config: serde_json::Value = serde_json::from_str(&content).unwrap();++ let providers = config.get("providers").unwrap().as_object().unwrap();++ // Should have both screenpipe and ollama providers+ assert!(providers.contains_key("screenpipe"), "missing screenpipe provider");+ assert!(providers.contains_key("ollama"), "missing ollama provider");++ let ollama = &providers["ollama"];+ assert_eq!(+ ollama.get("baseUrl").unwrap().as_str().unwrap(),+ "http://localhost:11434/v1"+ );++ let models = ollama.get("models").unwrap().as_array().unwrap();+ assert_eq!(models.len(), 1);+ assert_eq!(models[0].get("id").unwrap().as_str().unwrap(), "qwen3:8b");+ }+}diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rsindex c14b8680f..f2e9d555d 100644--- a/crates/screenpipe-core/src/pipes/mod.rs+++ b/crates/screenpipe-core/src/pipes/mod.rs@@ -10,7 +10,10 @@//! parses configs, runs the scheduler, and delegates execution to an//! [`AgentExecutor`].-use crate::agents::{AgentExecutor, ExecutionHandle};+use crate::agents::{+ pi::{PiExecutor, SCREENPIPE_API_URL},+ AgentExecutor, ExecutionHandle,+};use anyhow::{anyhow, Result};use chrono::{DateTime, Local, Utc};use cron::Schedule as CronSchedule;@@ -192,6 +195,8 @@ pub trait PipeStore: Send + Sync {struct ResolvedPreset {model: String,provider: Option<String>,+ /// Provider base URL (e.g. `http://localhost:11434/v1` for Ollama).+ url: Option<String>,}/// Read `~/.screenpipe/store.bin` and find the preset by id.@@ -253,7 +258,13 @@ fn resolve_preset(pipes_dir: &Path, preset_id: &str) -> Option<ResolvedPreset> {}).map(|s| s.to_string());- Some(ResolvedPreset { model, provider })+ let url = preset+ .get("url")+ .and_then(|v| v.as_str())+ .filter(|s| !s.is_empty())+ .map(|s| s.to_string());++ Some(ResolvedPreset { model, provider, url })}// ---------------------------------------------------------------------------@@ -614,23 +625,23 @@ impl PipeManager {let pipe_dir = self.pipes_dir.join(name);// Resolve preset → model/provider overrides- let (run_model, run_provider) = if let Some(ref preset_id) = config.preset {+ let (run_model, run_provider, run_provider_url) = if let Some(ref preset_id) = config.preset {match resolve_preset(&self.pipes_dir, preset_id) {Some(resolved) => {info!("pipe '{}': using preset '{}' → model={}, provider={:?}",name, preset_id, resolved.model, resolved.provider);- (resolved.model, resolved.provider)+ (resolved.model, resolved.provider, resolved.url)}None => {warn!("pipe '{}': preset '{}' not found in store.bin, falling back to pipe config",name, preset_id);- (config.model.clone(), config.provider.clone())+ (config.model.clone(), config.provider.clone(), None)}}} else {- (config.model.clone(), config.provider.clone())+ (config.model.clone(), config.provider.clone(), None)};// Create DB execution row@@ -689,6 +700,20 @@ impl PipeManager {}});+ // Pre-configure pi with the pipe's provider so models.json has the+ // right entry before the agent subprocess starts.+ if config.agent == "pi" {+ if let Err(e) = PiExecutor::ensure_pi_config(+ None,+ SCREENPIPE_API_URL,+ run_provider.as_deref(),+ Some(&run_model),+ run_provider_url.as_deref(),+ ) {+ warn!("failed to pre-configure pi provider: {}", e);+ }+ }+// Run with timeoutlet timeout_duration = std::time::Duration::from_secs(DEFAULT_TIMEOUT_SECS);let run_result = tokio::time::timeout(@@ -1182,19 +1207,32 @@ impl PipeManager {}// Resolve preset → model/provider overrides (same as run_pipe)- let (model, provider) = if let Some(ref preset_id) = config.preset {+ let (model, provider, provider_url) = if let Some(ref preset_id) = config.preset {match resolve_preset(&pipes_dir, preset_id) {Some(resolved) => {info!("scheduler: pipe '{}' using preset '{}' → model={}, provider={:?}",name, preset_id, resolved.model, resolved.provider);- (resolved.model, resolved.provider)+ (resolved.model, resolved.provider, resolved.url)}- None => (config.model.clone(), config.provider.clone()),+ None => (config.model.clone(), config.provider.clone(), None),}} else {- (config.model.clone(), config.provider.clone())+ (config.model.clone(), config.provider.clone(), None)};+ // Pre-configure pi with the pipe's provider+ if config.agent == "pi" {+ if let Err(e) = PiExecutor::ensure_pi_config(+ None,+ SCREENPIPE_API_URL,+ provider.as_deref(),+ Some(&model),+ provider_url.as_deref(),+ ) {+ warn!("scheduler: failed to pre-configure pi provider: {}", e);+ }+ }+let prompt = render_prompt_with_port(config, body, api_port);let pipe_dir = pipes_dir.join(name);let pipe_name = name.clone();