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(pi): guide enabled subagent delegation (#5215)
Louis Beaumontc09e31df6578
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rsindex 0a8b18cc9..c24be6de0 100644--- a/crates/screenpipe-core/src/agents/pi.rs+++ b/crates/screenpipe-core/src/agents/pi.rs@@ -2043,6 +2043,49 @@ pub fn pi_config_dir() -> Result<PathBuf> {Ok(dir)}+fn pi_package_source_matches(source: &str, package_name: &str) -> bool {+ let Some(spec) = source.trim().strip_prefix("npm:") else {+ return false;+ };+ if spec == package_name {+ return true;+ }+ spec.strip_prefix(package_name)+ .is_some_and(|suffix| suffix.starts_with('@'))+}++fn pi_settings_enable_package(settings: &serde_json::Value, package_name: &str) -> bool {+ settings+ .get("packages")+ .and_then(serde_json::Value::as_array)+ .is_some_and(|packages| {+ packages.iter().any(|package| {+ package+ .as_str()+ .or_else(|| package.get("source").and_then(serde_json::Value::as_str))+ .is_some_and(|source| pi_package_source_matches(source, package_name))+ })+ })+}++/// Return whether a Pi npm package is enabled in screenpipe's isolated config.+///+/// Packages can be strings or filtered objects and can include an npm version.+/// Any read or parse failure is treated as disabled so prompts never advertise+/// tools that Pi cannot actually load.+pub fn pi_package_enabled(package_name: &str) -> bool {+ let Ok(config_dir) = pi_config_dir() else {+ return false;+ };+ let Ok(raw) = std::fs::read_to_string(config_dir.join("settings.json")) else {+ return false;+ };+ let Ok(settings) = serde_json::from_str::<serde_json::Value>(&raw) else {+ return false;+ };+ pi_settings_enable_package(&settings, package_name)+}+fn get_pi_config_dir() -> Result<PathBuf> {pi_config_dir()}@@ -3343,6 +3386,89 @@ mod tests {assert!(parts.iter().any(|path| path == &existing_b));}+ #[test]+ fn pi_package_detection_handles_versions_and_filtered_objects() {+ let settings = serde_json::json!({+ "packages": [+ "npm:pi-web-agent",+ "npm:[email protected]",+ {"source": "npm:@eko24ive/pi-ask", "extensions": ["index.ts"]}+ ]+ });++ assert!(pi_settings_enable_package(&settings, "pi-subagents"));+ assert!(pi_settings_enable_package(&settings, "@eko24ive/pi-ask"));+ assert!(!pi_settings_enable_package(&settings, "pi-subagent"));+ assert!(!pi_settings_enable_package(&settings, "subagents"));+ }++ /// Live parent -> subagent -> parent smoke test.+ ///+ /// Run with:+ /// SCREENPIPE_E2E_CLOUD_TOKEN=... cargo test -p screenpipe-core \+ /// pi_subagents_parent_child_e2e -- --ignored --nocapture+ #[tokio::test]+ #[ignore]+ async fn pi_subagents_parent_child_e2e() {+ let token = std::env::var("SCREENPIPE_E2E_CLOUD_TOKEN")+ .expect("SCREENPIPE_E2E_CLOUD_TOKEN is required for this live test");+ assert!(+ pi_package_enabled("pi-subagents"),+ "enable npm:pi-subagents in Settings > Pi extensions first"+ );++ let working_dir = tempfile::tempdir().expect("temp working dir");+ let output = PiExecutor::new(Some(token))+ .run(+ "Use the subagent tool exactly once. Ask the child to reply with only CHILD_OK. This is read-only, so pass acceptance.level=none. After the child succeeds, reply with only PARENT_OK.",+ "auto",+ working_dir.path(),+ None,+ None,+ None,+ None,+ false,+ )+ .await+ .expect("run parent Pi agent");++ assert!(output.success, "parent failed: {}", output.stderr);+ assert!(+ output.stdout.contains("PARENT_OK"),+ "parent did not finish after its child: {}",+ output.stdout+ );++ let artifacts_dir = working_dir.path().join(".pi-subagents").join("artifacts");+ let child_succeeded = std::fs::read_dir(&artifacts_dir)+ .into_iter()+ .flatten()+ .filter_map(Result::ok)+ .filter(|entry| entry.file_name().to_string_lossy().ends_with("_meta.json"))+ .any(|entry| {+ let Ok(raw_meta) = std::fs::read_to_string(entry.path()) else {+ return false;+ };+ let Ok(meta) = serde_json::from_str::<serde_json::Value>(&raw_meta) else {+ return false;+ };+ let output_name = entry+ .file_name()+ .to_string_lossy()+ .replace("_meta.json", "_output.md");+ let output = std::fs::read_to_string(entry.path().with_file_name(output_name))+ .unwrap_or_default();+ meta.get("exitCode").and_then(serde_json::Value::as_i64) == Some(0)+ && output.contains("CHILD_OK")+ });+ assert!(+ child_succeeded,+ "no successful CHILD_OK run found under {} (parent output: {})",+ artifacts_dir.display(),+ output.stdout+ );+ }+#[test]fn clear_screenpipe_auth_preserves_other_provider_tokens() {let dir = tempfile::tempdir().expect("tempdir");diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rsindex 5f3f5c468..6f0e39623 100644--- a/crates/screenpipe-core/src/pipes/mod.rs+++ b/crates/screenpipe-core/src/pipes/mod.rs@@ -20,7 +20,7 @@ pub mod sync;pub(crate) mod trajectory;use crate::agents::{- pi::{PiExecutor, SCREENPIPE_API_URL},+ pi::{pi_package_enabled, PiExecutor, SCREENPIPE_API_URL},AgentExecutor, ExecutionHandle, SharedPid, STOP_REQUESTED_PID,};use crate::pipes::connections::parse_mcp_connection_id;@@ -2901,6 +2901,7 @@ impl PipeManager {preset_prompt.as_deref(),self.connections_context.as_deref(),self.local_api_key.as_deref(),+ config.agent == "pi" && pi_package_enabled("pi-subagents"),);let prompt = self.render_prompt(&config, &body, preset_prompt.as_deref());let pipe_name = name.to_string();@@ -3448,6 +3449,7 @@ impl PipeManager {preset_prompt.as_deref(),self.connections_context.as_deref(),self.local_api_key.as_deref(),+ config.agent == "pi" && pi_package_enabled("pi-subagents"),);let prompt = self.render_prompt(&config, &body, preset_prompt.as_deref());@@ -4760,6 +4762,7 @@ impl PipeManager {preset_prompt.as_deref(),connections_context.as_deref(),local_api_key.as_deref(),+ config.agent == "pi" && pi_package_enabled("pi-subagents"),);let prompt = render_prompt_with_port(config,@@ -5618,6 +5621,7 @@ fn render_pipe_system_prompt(system_prompt: Option<&str>,connections_context: Option<&str>,local_api_key: Option<&str>,+ subagents_available: bool,) -> String {let os = std::env::consts::OS;let mut sys = String::new();@@ -5640,6 +5644,9 @@ fn render_pipe_system_prompt(sys.push_str(&format!("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.\nNotifications support action buttons (`\"actions\": [...]`) so you can ASK the user instead of sending a passive FYI — when a human decision or follow-up would help (send/share/draft/fix/dig deeper), attach actions rather than doing nothing or acting unilaterally. Schema + examples: screenpipe-api skill, Notifications section.\n\n"));+ if subagents_available {+ sys.push_str("Subagents: the `subagent` tool is enabled. Use it when this task has at least two independent research, review, or implementation workstreams that can run in parallel, then synthesize the child results. Keep simple or sequential work in this agent. For read-only child tasks, pass `acceptance.level: \"none\"` so a successful child is not rejected for making no edits.\n\n");+ }sys.push_str(body);if let Some(ctx) = connections_context {@@ -8116,7 +8123,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, None, None);+ let sys = render_pipe_system_prompt("body text", 3031, None, None, None, false);assert!(sys.contains("http://localhost:3031"));assert!(!sys.contains("http://localhost:3030"));assert!(sys.contains("body text"));@@ -8145,7 +8152,7 @@ mod tests {artifacts: vec![],trigger: None,};- let sys = render_pipe_system_prompt("hello", 3030, None, None, None);+ let sys = render_pipe_system_prompt("hello", 3030, None, None, None, false);assert!(sys.contains("http://localhost:3030"));}@@ -8178,6 +8185,7 @@ mod tests {Some("You are a helpful assistant"),None,None,+ false,);assert!(sys.starts_with("You are a helpful assistant\n\n"));assert!(sys.contains("body text"));@@ -8207,14 +8215,14 @@ mod tests {artifacts: vec![],trigger: None,};- let sys = render_pipe_system_prompt("body text", 3030, None, None, None);+ let sys = render_pipe_system_prompt("body text", 3030, None, None, None, false);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, None, None);+ let sys = render_pipe_system_prompt("task body", 3030, None, None, None, false);assert!(sys.contains("NEVER run `screenpipe pipe run`"));assert!(sys.contains("You ARE this pipe"));}@@ -8224,7 +8232,8 @@ mod tests {// Pass the key explicitly — the renderer must not depend on parent// process env (which is empty in tests and was the root cause of the// 403 reported by the security-requests-grc pipe in prod).- let sys = render_pipe_system_prompt("task body", 3030, None, None, Some("sp-test-key"));+ let sys =+ render_pipe_system_prompt("task body", 3030, None, None, Some("sp-test-key"), false);assert!(sys.contains("API Authentication: REQUIRED"),"auth note must be emitted when local_api_key is Some"@@ -8234,13 +8243,23 @@ mod tests {#[test]fn test_system_prompt_omits_auth_note_when_no_key() {- let sys = render_pipe_system_prompt("task body", 3030, None, None, None);+ let sys = render_pipe_system_prompt("task body", 3030, None, None, None, false);assert!(!sys.contains("API Authentication: REQUIRED"),"auth note must not be emitted when local_api_key is None");}+ #[test]+ fn test_system_prompt_explains_enabled_subagent_tool() {+ let enabled = render_pipe_system_prompt("task body", 3030, None, None, None, true);+ assert!(enabled.contains("the `subagent` tool is enabled"));+ assert!(enabled.contains("acceptance.level: \"none\""));++ let disabled = render_pipe_system_prompt("task body", 3030, None, None, None, false);+ assert!(!disabled.contains("the `subagent` tool is enabled"));+ }+// -- PipeExecution / SchedulerState serde roundtrip ----------------------#[test]