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

fix(pi): write tagged credentials so pi 0.83 can resolve provider auth

Louis Beaumont05a4ef6b1e84
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rs
index a81131e68..423e8f129 100644
--- a/crates/screenpipe-core/src/agents/pi.rs
+++ b/crates/screenpipe-core/src/agents/pi.rs
@@ -1141,8 +1141,8 @@ impl PiExecutor {
// -- auth.json: merge/remove screenpipe token, preserve other providers --
// Only manage screenpipe auth when screenpipe provider is actually being used.
+ let auth_path = config_dir.join("auth.json");
if should_add_screenpipe {
- let auth_path = config_dir.join("auth.json");
if let Some(token) = user_token.filter(|token| !token.is_empty()) {
let mut auth: serde_json::Value = if auth_path.exists() {
let content = std::fs::read_to_string(&auth_path).unwrap_or_default();
@@ -1151,31 +1151,21 @@ impl PiExecutor {
json!({})
};
+ upgrade_legacy_pi_credentials(&mut auth);
+
if let Some(obj) = auth.as_object_mut() {
- obj.insert("screenpipe".to_string(), json!(token));
+ obj.insert("screenpipe".to_string(), api_key_credential(token));
}
- let auth_tmp = config_dir.join(format!(
- "auth.json.{}.{}.tmp",
- std::process::id(),
- format!("{:?}", std::thread::current().id())
- .chars()
- .filter(|c| c.is_ascii_digit())
- .collect::<String>()
- ));
- std::fs::write(&auth_tmp, serde_json::to_string_pretty(&auth)?)?;
- std::fs::rename(&auth_tmp, &auth_path)?;
-
- // Set restrictive permissions (user read/write only)
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- let perms = std::fs::Permissions::from_mode(0o600);
- let _ = std::fs::set_permissions(&auth_path, perms);
- }
+ write_auth_json(&auth_path, &auth)?;
} else {
remove_screenpipe_auth_from_path(&auth_path)?;
}
+ } else {
+ // BYOK-only users never reach the screenpipe branch, but their
+ // auth.json can still hold legacy entries seeded from the user's
+ // global `~/.pi/agent/auth.json` — upgrade those too.
+ upgrade_legacy_pi_credentials_at_path(&auth_path)?;
}
debug!("pi config written at {:?}", models_path);
@@ -2377,22 +2367,81 @@ fn seed_from_global(global: &Path, dest: &Path, data_dir: &Path) -> bool {
true
}
-fn remove_screenpipe_auth_from_path(auth_path: &Path) -> Result<()> {
+/// A pi credential in the tagged form pi >=0.83 requires.
+fn api_key_credential(key: &str) -> serde_json::Value {
+ json!({ "type": "api_key", "key": key })
+}
+
+/// Upgrade one legacy `auth.json` entry to pi >=0.83's tagged form.
+///
+/// pi 0.83 rejects any stored credential it cannot tag. `resolveProviderAuth`
+/// (pi-ai `auth/resolve.js`) short-circuits on *any* stored entry and returns
+/// `undefined` unless it matches `{"type": "oauth"|"api_key", …}` — there is no
+/// fallback to the provider's `apiKey` in models.json once a credential exists.
+/// Screenpipe wrote the cloud token as a bare string, which pi <=0.80 accepted,
+/// so after the 0.83 bump every signed-in user's hosted AI (chat *and* every
+/// background pipe) fails with "Provider is not configured: screenpipe".
+/// Legacy `{"apiKey": …}` entries — seeded from a user's global
+/// `~/.pi/agent/auth.json` for BYOK providers — fail identically.
+///
+/// Returns `None` for entries that are already tagged, so oauth credentials and
+/// anything pi writes itself are left untouched.
+fn upgrade_legacy_pi_credential(value: &serde_json::Value) -> Option<serde_json::Value> {
+ match value {
+ // pi <=0.80 screenpipe format: the bare token string.
+ serde_json::Value::String(key) => Some(api_key_credential(key)),
+ // Legacy BYOK format: `{"apiKey": "…"}` with no discriminant.
+ serde_json::Value::Object(obj) if !obj.contains_key("type") => {
+ let key = obj.get("apiKey").or_else(|| obj.get("key"))?.as_str()?;
+ let mut upgraded = api_key_credential(key);
+ // `env` drives pi's `resolveConfigValue` indirection — preserve it.
+ if let Some(env) = obj.get("env") {
+ upgraded["env"] = env.clone();
+ }
+ Some(upgraded)
+ }
+ _ => None,
+ }
+}
+
+/// Upgrade every legacy entry in an `auth.json` value. Returns whether
+/// anything changed.
+fn upgrade_legacy_pi_credentials(auth: &mut serde_json::Value) -> bool {
+ let Some(obj) = auth.as_object_mut() else {
+ return false;
+ };
+ let upgrades: Vec<(String, serde_json::Value)> = obj
+ .iter()
+ .filter_map(|(provider, value)| {
+ upgrade_legacy_pi_credential(value).map(|upgraded| (provider.clone(), upgraded))
+ })
+ .collect();
+ if upgrades.is_empty() {
+ return false;
+ }
+ for (provider, upgraded) in upgrades {
+ obj.insert(provider, upgraded);
+ }
+ true
+}
+
+/// Rewrite `auth.json` in place if it holds any legacy credential shape.
+fn upgrade_legacy_pi_credentials_at_path(auth_path: &Path) -> Result<()> {
if !auth_path.exists() {
return Ok(());
}
let content = std::fs::read_to_string(auth_path)?;
let mut auth: serde_json::Value = serde_json::from_str(&content).unwrap_or_else(|_| json!({}));
- let removed = auth
- .as_object_mut()
- .map(|obj| obj.remove("screenpipe").is_some())
- .unwrap_or(false);
-
- if !removed {
+ if !upgrade_legacy_pi_credentials(&mut auth) {
return Ok(());
}
+ write_auth_json(auth_path, &auth)
+}
+
+/// Atomically write `auth.json` with owner-only permissions.
+fn write_auth_json(auth_path: &Path, auth: &serde_json::Value) -> Result<()> {
let auth_tmp = auth_path.with_file_name(format!(
"auth.json.{}.{}.tmp",
std::process::id(),
@@ -2401,7 +2450,7 @@ fn remove_screenpipe_auth_from_path(auth_path: &Path) -> Result<()> {
.filter(|c| c.is_ascii_digit())
.collect::<String>()
));
- std::fs::write(&auth_tmp, serde_json::to_string_pretty(&auth)?)?;
+ std::fs::write(&auth_tmp, serde_json::to_string_pretty(auth)?)?;
std::fs::rename(&auth_tmp, auth_path)?;
#[cfg(unix)]
@@ -2414,6 +2463,27 @@ fn remove_screenpipe_auth_from_path(auth_path: &Path) -> Result<()> {
Ok(())
}
+fn remove_screenpipe_auth_from_path(auth_path: &Path) -> Result<()> {
+ if !auth_path.exists() {
+ return Ok(());
+ }
+
+ let content = std::fs::read_to_string(auth_path)?;
+ let mut auth: serde_json::Value = serde_json::from_str(&content).unwrap_or_else(|_| json!({}));
+ let removed = auth
+ .as_object_mut()
+ .map(|obj| obj.remove("screenpipe").is_some())
+ .unwrap_or(false);
+ // Signed-out users keep their BYOK credentials — upgrade those too.
+ let upgraded = upgrade_legacy_pi_credentials(&mut auth);
+
+ if !removed && !upgraded {
+ return Ok(());
+ }
+
+ write_auth_json(auth_path, &auth)
+}
+
pub fn find_bun_executable() -> Option<String> {
// Check next to our own executable (bundled bun)
if let Ok(exe_path) = std::env::current_exe() {
@@ -3606,11 +3676,77 @@ mod tests {
let auth: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&auth_path).unwrap()).unwrap();
assert!(auth.get("screenpipe").is_none());
- assert_eq!(auth["openai"], serde_json::json!("sk-keep"));
+ // Preserved, and upgraded to the tagged form pi >=0.83 accepts.
+ assert_eq!(
+ auth["openai"],
+ serde_json::json!({"type": "api_key", "key": "sk-keep"})
+ );
+ assert_eq!(
+ auth["anthropic"],
+ serde_json::json!({"type": "api_key", "key": "anthropic-keep"})
+ );
+ }
+
+ /// pi >=0.83 returns `undefined` from `resolveProviderAuth` for any stored
+ /// credential that is not tagged, with no fallback to models.json — so a
+ /// bare-string token makes hosted AI fail with
+ /// "Provider is not configured: screenpipe".
+ #[test]
+ fn legacy_credentials_upgrade_to_tagged_api_key() {
+ let mut auth = serde_json::json!({
+ "screenpipe": "bare-jwt",
+ "anthropic": {"apiKey": "sk-ant"},
+ "openai": {"apiKey": "sk-oai", "env": {"FOO": "BAR"}},
+ });
+
+ assert!(upgrade_legacy_pi_credentials(&mut auth));
+
+ assert_eq!(
+ auth["screenpipe"],
+ serde_json::json!({"type": "api_key", "key": "bare-jwt"})
+ );
assert_eq!(
- auth["anthropic"]["apiKey"],
- serde_json::json!("anthropic-keep")
+ auth["anthropic"],
+ serde_json::json!({"type": "api_key", "key": "sk-ant"})
);
+ // `env` drives pi's resolveConfigValue indirection — must survive.
+ assert_eq!(
+ auth["openai"],
+ serde_json::json!({"type": "api_key", "key": "sk-oai", "env": {"FOO": "BAR"}})
+ );
+ }
+
+ #[test]
+ fn already_tagged_credentials_are_left_alone() {
+ let original = serde_json::json!({
+ "screenpipe": {"type": "api_key", "key": "jwt"},
+ "anthropic": {"type": "oauth", "access": "a", "refresh": "r", "expires": 1},
+ });
+ let mut auth = original.clone();
+
+ assert!(!upgrade_legacy_pi_credentials(&mut auth));
+ assert_eq!(auth, original);
+ }
+
+ #[test]
+ fn upgrade_at_path_rewrites_legacy_file_and_skips_clean_one() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let auth_path = dir.path().join("auth.json");
+ std::fs::write(&auth_path, r#"{"screenpipe":"bare-jwt"}"#).expect("write auth");
+
+ upgrade_legacy_pi_credentials_at_path(&auth_path).expect("upgrade");
+
+ let auth: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&auth_path).unwrap()).unwrap();
+ assert_eq!(
+ auth["screenpipe"],
+ serde_json::json!({"type": "api_key", "key": "bare-jwt"})
+ );
+
+ // Second pass is a no-op: already tagged, file must not be rewritten.
+ let before = std::fs::read_to_string(&auth_path).unwrap();
+ upgrade_legacy_pi_credentials_at_path(&auth_path).expect("second upgrade");
+ assert_eq!(std::fs::read_to_string(&auth_path).unwrap(), before);
}
#[test]