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): auto-retry on 429 rate limits, stagger scheduled runs

Louis Beaumonte91a0aa5e08d
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index e77cce1bb..1e98aad02 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -585,7 +585,24 @@ function buildRateLimitMessage(errorStr: string): string {
: "Rate limited — try again in a moment or switch to a different model.";
}
-/** Extract the gateway-reported tier from an error string, if present. */
+/** How many times a single turn auto-retries on a 429 before giving up. */
+const PI_MAX_RATE_LIMIT_RETRIES = 3;
+
+/**
+ * Seconds to wait before retrying a rate-limited (429) request. Prefers the
+ * gateway's structured `reset_in` hint, falls back to the "wait N seconds"
+ * prose, then a safe default. Clamped to [1, 60].
+ */
+function parseRateLimitWaitSeconds(errorStr: string): number {
+ const DEFAULT_WAIT = 10;
+ const resetMatch = errorStr.match(/"reset_in"\s*:\s*(\d+)/i);
+ const waitMatch = errorStr.match(/wait (\d+) seconds/i);
+ const raw = resetMatch?.[1] ?? waitMatch?.[1];
+ const secs = raw ? parseInt(raw, 10) : DEFAULT_WAIT;
+ if (!Number.isFinite(secs) || secs <= 0) return DEFAULT_WAIT;
+ return Math.min(Math.max(secs, 1), 60);
+}
+
// Helper to get timezone offset string (e.g., "+1" or "-5")
function getTimezoneOffsetString(): string {
const offsetMinutes = new Date().getTimezoneOffset();
@@ -3249,6 +3266,8 @@ export function StandaloneChat({
const sendDispatchInFlightRef = useRef(false);
const forceQueueModeRef = useRef(false);
const piFirstCallRetried = useRef(false);
+ // Per-turn 429 auto-retry budget; reset on each new user send + on success.
+ const piRateLimitRetries = useRef(0);
const sessionActivityLastEmitAtRef = useRef<Record<string, number>>({});
const sessionActivityLastSigRef = useRef<Record<string, string>>({});
const piStoppedIntentionallyRef = useRef(false);
@@ -5546,6 +5565,7 @@ export function StandaloneChat({
piThinkingStartRef.current = null;
followUpFiredRef.current = false;
forceQueueModeRef.current = false;
+ piRateLimitRetries.current = 0;
setIsLoading(false);
setIsStreaming(false);
emitSessionActivity({ status: "idle" });
@@ -5572,6 +5592,46 @@ export function StandaloneChat({
}
return;
}
+ // Rate-limit (429) auto-retry — honor the gateway's reset_in hint and
+ // re-send the same prompt. The cloud LLM gateway caps free/logged-in
+ // tiers at a few dozen requests/minute; a single agentic run can trip
+ // it, after which a short wait clears the budget. Without this the turn
+ // dies silently (e.g. pipe creation stalls mid-skill).
+ if (
+ classifyQuotaError(errorStr) === "rate" &&
+ piRateLimitRetries.current < PI_MAX_RATE_LIMIT_RETRIES &&
+ piSessionIdRef.current &&
+ lastUserMessageRef.current
+ ) {
+ piRateLimitRetries.current += 1;
+ const attempt = piRateLimitRetries.current;
+ const waitSecs = parseRateLimitWaitSeconds(errorStr);
+ const retrySession = piSessionIdRef.current;
+ const retryPrompt = lastUserMessageRef.current;
+ console.warn(`[Pi] rate limited, auto-retry ${attempt}/${PI_MAX_RATE_LIMIT_RETRIES} in ${waitSecs}s:`, errorStr);
+ // Reset the in-flight buffers so the retried turn renders cleanly into
+ // the same bubble instead of appending onto any pre-429 partial output.
+ piStreamingTextRef.current = "";
+ piContentBlocksRef.current = [];
+ const retryTurnId = piMessageIdRef.current;
+ if (retryTurnId) {
+ setMessages((prev) =>
+ prev.map((m) => m.id === retryTurnId
+ ? { ...m, content: `Rate limited — retrying in ${waitSecs}s… (attempt ${attempt}/${PI_MAX_RATE_LIMIT_RETRIES})`, contentBlocks: [] }
+ : m)
+ );
+ }
+ setTimeout(() => {
+ // Guard the delayed re-send: bail if the user unmounted, switched
+ // sessions, or started a new turn during the wait, so we never
+ // inject a stale prompt into the wrong place.
+ if (!mountedRef.current) return;
+ if (piSessionIdRef.current !== retrySession) return;
+ if (piMessageIdRef.current && piMessageIdRef.current !== retryTurnId) return;
+ commands.piPrompt(retrySession, retryPrompt, null, null).catch(() => {});
+ }, waitSecs * 1000);
+ return;
+ }
if (piMessageIdRef.current) {
const msgId = piMessageIdRef.current;
@@ -6429,6 +6489,7 @@ export function StandaloneChat({
// Clear follow-ups for new message
setFollowUpSuggestions([]);
followUpFiredRef.current = false;
+ piRateLimitRetries.current = 0;
if (followUpAbortRef.current) {
followUpAbortRef.current.abort();
followUpAbortRef.current = null;
@@ -7210,6 +7271,7 @@ export function StandaloneChat({
setFollowUpSuggestions([]);
followUpFiredRef.current = false;
+ piRateLimitRetries.current = 0;
if (followUpAbortRef.current) {
followUpAbortRef.current.abort();
followUpAbortRef.current = null;
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rs
index 1e2224b88..0778c55a5 100644
--- a/crates/screenpipe-core/src/agents/pi.rs
+++ b/crates/screenpipe-core/src/agents/pi.rs
@@ -20,6 +20,51 @@ const PI_AI_PACKAGE: &str = "@earendil-works/[email protected]";
const PI_NAMESPACE_DIR: &str = "@earendil-works";
pub const SCREENPIPE_API_URL: &str = "https://api.screenpipe.com/v1";
+/// Bounded retries for provider rate limiting (HTTP 429) in streaming runs.
+const MAX_RATE_LIMIT_RETRIES: usize = 3;
+/// Fallback wait when the 429 payload carries no `reset_in` hint.
+const RATE_LIMIT_DEFAULT_WAIT_SECS: u64 = 10;
+/// Cap so an oversized `reset_in` can't stall a pipe run indefinitely.
+const RATE_LIMIT_MAX_WAIT_SECS: u64 = 60;
+
+/// Parse the rate-limit retry hint (in seconds) from a pi error payload.
+///
+/// The cloud gateway returns a 429 body containing `"reset_in":<secs>` plus a
+/// human-readable "Please wait N seconds". We prefer the structured `reset_in`
+/// field and fall back to the prose. Returns `None` when no hint is present.
+fn parse_rate_limit_reset_secs(text: &str) -> Option<u64> {
+ // Prefer the structured "reset_in" field.
+ if let Some(idx) = text.find("\"reset_in\"") {
+ let rest = &text[idx + "\"reset_in\"".len()..];
+ let rest = rest.trim_start_matches(|c: char| c == ':' || c.is_whitespace());
+ let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
+ if let Ok(secs) = digits.parse::<u64>() {
+ return Some(secs);
+ }
+ }
+ // Fall back to the human-readable "wait N seconds".
+ let lower = text.to_lowercase();
+ if let Some(idx) = lower.find("wait ") {
+ let rest = &lower[idx + "wait ".len()..];
+ let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
+ if let Ok(secs) = digits.parse::<u64>() {
+ return Some(secs);
+ }
+ }
+ None
+}
+
+/// Whether a pi failure was caused by provider rate limiting (HTTP 429).
+fn is_rate_limit_error(text: &str) -> bool {
+ let lower = text.to_lowercase();
+ lower.contains("429")
+ || lower.contains("rate limit")
+ || lower.contains("rate_limit")
+ || lower.contains("requests per minute")
+ || lower.contains("too many requests")
+ || lower.contains("\"reset_in\"")
+}
+
/// Fetch the model catalog from the Cloudflare Worker gateway and convert
/// it into the format Pi's `models.json` expects.
///
@@ -1268,7 +1313,7 @@ impl AgentExecutor for PiExecutor {
resolved_provider, resolved_model
);
- let output = self
+ let mut output = self
.spawn_pi_streaming(
&pi_path,
prompt,
@@ -1300,7 +1345,7 @@ impl AgentExecutor for PiExecutor {
provider_url,
)
.await?;
- return self
+ output = self
.spawn_pi_streaming(
&pi_path,
prompt,
@@ -1309,11 +1354,58 @@ impl AgentExecutor for PiExecutor {
&resolved_provider,
provider_api_key,
None,
- line_tx,
+ line_tx.clone(),
continue_session,
pipe_system_prompt,
)
- .await;
+ .await?;
+ }
+
+ // Retry on provider rate limiting (HTTP 429). The cloud gateway caps
+ // requests per minute; concurrent scheduler pressure or a single busy
+ // run can trip it. pi exits 0 but surfaces the 429 as an assistant
+ // error, so `output.success` is false with the payload (including
+ // "reset_in") in stderr. Honor that hint, wait, and re-run instead of
+ // failing the whole pipe — which previously left automations silently
+ // doing nothing. (Runs that legitimately exceed the per-minute budget
+ // also need scheduler pacing, but a wait-and-retry still beats a hard
+ // stop.)
+ let mut rate_limit_retries = 0usize;
+ while !output.success
+ && rate_limit_retries < MAX_RATE_LIMIT_RETRIES
+ && is_rate_limit_error(&output.stderr)
+ {
+ rate_limit_retries += 1;
+ let wait_secs = parse_rate_limit_reset_secs(&output.stderr)
+ .unwrap_or(RATE_LIMIT_DEFAULT_WAIT_SECS)
+ .clamp(1, RATE_LIMIT_MAX_WAIT_SECS);
+ warn!(
+ "pi rate limited (attempt {}/{}), waiting {}s before retry (stderr: {})",
+ rate_limit_retries,
+ MAX_RATE_LIMIT_RETRIES,
+ wait_secs,
+ output.stderr.trim()
+ );
+ // Surface the wait to any UI/log consumer draining line_tx.
+ let _ = line_tx.send(format!(
+ r#"{{"type":"status","kind":"rate_limit_retry","wait_secs":{},"attempt":{},"max_attempts":{}}}"#,
+ wait_secs, rate_limit_retries, MAX_RATE_LIMIT_RETRIES
+ ));
+ tokio::time::sleep(std::time::Duration::from_secs(wait_secs)).await;
+ output = self
+ .spawn_pi_streaming(
+ &pi_path,
+ prompt,
+ &resolved_model,
+ working_dir,
+ &resolved_provider,
+ provider_api_key,
+ None,
+ line_tx.clone(),
+ continue_session,
+ pipe_system_prompt,
+ )
+ .await?;
}
Ok(output)
@@ -2146,6 +2238,38 @@ mod tests {
assert_eq!(lines[1], "OK");
}
+ #[test]
+ fn test_parse_rate_limit_reset_secs() {
+ // Real gateway 429 payload: prefer the structured "reset_in" field.
+ let payload = r#"{"error":"You've exceeded 25 requests per minute. Please wait 12 seconds before retrying.","tier":"logged_in","reset_in":12}"#;
+ assert_eq!(parse_rate_limit_reset_secs(payload), Some(12));
+
+ // As surfaced through pi (prefixed "LLM error:") with whitespace
+ // around the colon.
+ let wrapped = r#"LLM error: {"reset_in" : 9, "tier":"logged_in"}"#;
+ assert_eq!(parse_rate_limit_reset_secs(wrapped), Some(9));
+
+ // No structured field — fall back to the prose hint.
+ assert_eq!(
+ parse_rate_limit_reset_secs("rate limited, please wait 8 seconds"),
+ Some(8)
+ );
+
+ // Unrelated error carries no hint.
+ assert_eq!(parse_rate_limit_reset_secs("model not found"), None);
+ }
+
+ #[test]
+ fn test_is_rate_limit_error() {
+ assert!(is_rate_limit_error("HTTP 429 Too Many Requests"));
+ assert!(is_rate_limit_error(
+ "You've exceeded 25 requests per minute"
+ ));
+ assert!(is_rate_limit_error(r#"{"reset_in":12}"#));
+ assert!(!is_rate_limit_error("model not found"));
+ assert!(!is_rate_limit_error("credits_exhausted"));
+ }
+
#[tokio::test]
async fn test_ensure_pi_config_adds_ollama_provider() {
// Call ensure_pi_config with ollama provider info
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index 35906bf56..4c80fc602 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -1159,6 +1159,12 @@ pub type ConnectionCheck = Arc<
/// Default execution timeout: 10 minutes.
const DEFAULT_TIMEOUT_SECS: u64 = 600;
+/// Cooldown held after a scheduled run finishes *when other scheduled pipes
+/// are still queued behind the execution semaphore*. Spaces consecutive runs
+/// so the tail of one and the head of the next don't pile into the same
+/// rolling-minute rate-limit window. No-op when nothing is waiting.
+const SCHEDULED_RUN_SPACING_SECS: u64 = 5;
+
/// Set up permissions for a Pi pipe: install extension, filtered skills,
/// write the permissions JSON file, and register the token with the server.
/// Returns the generated token (if any) so the caller can clean it up later.
@@ -3898,6 +3904,26 @@ impl PipeManager {
if let Some(ref token) = pipe_token {
cleanup_pipe_token(token, token_registry_ref.as_ref());
}
+
+ // Stagger consecutive scheduled runs: if other pipes are
+ // still queued behind the semaphore, hold this permit a few
+ // seconds longer before releasing it. This smooths the gap
+ // between the tail of this run and the head of the next so
+ // they don't collide in the same rolling-minute rate-limit
+ // window. Skipped for event-triggered pipes (latency-
+ // sensitive, queue-bypassing) and a no-op under no contention.
+ if !is_event_triggered {
+ let others_waiting = {
+ let qr = queued_ref.lock().await;
+ !qr.is_empty()
+ };
+ if others_waiting {
+ tokio::time::sleep(std::time::Duration::from_secs(
+ SCHEDULED_RUN_SPACING_SECS,
+ ))
+ .await;
+ }
+ }
});
}