Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
AutoFix: usage limits are a quota class, never retried
Lin (kwant bot)2f6927b9d6f1
diff --git a/docs/mission-control.md b/docs/mission-control.mdindex cfc11465..0f6af2c6 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -461,13 +461,13 @@ acceptance, a routine) is only ever proposed; it applies when the person approve### Failures- `task_failures` (append-only): `id`, `task_id`, `attempt`, `source` (`check`, `turn`, `lease`, `budget`, `routine`, `handoff`), `class`, `summary`, `excerpt`, `checkpoint_id` (the last good `after_run`), `created_at`, and server-only `diagnostics_path`.-- `classify(source, status, text)` is deterministic. A check that failed is `check_failed`, or `bad_spec` when its command can't run (exit 127, "command not found"). A check that errored is `transient` for a timeout or 429/5xx (an `http` check whose connection was refused, dropped or timed out says "network error" by reqwest's error kind, not its wording), else `bad_spec`. A lease that ran out or a turn that ended without a review is `stalled`; over budget is `budget`; a denied action is `denied`; a task waiting on the person is `needs_input`. Other errors are `auth` (not logged in, 401, expired token, credit too low, and kwant's own "signed out or its key was rejected" / "No account can run bots" / no other account on), then `transient` (rate limit, overloaded, timeouts, connection errors, 429/500/502/503/504/529 as whole numbers), else `unknown`.+- `classify(source, status, text)` is deterministic. A check that failed is `check_failed`, or `bad_spec` when its command can't run (exit 127, "command not found"). A check that errored is `transient` for a timeout or 429/5xx (an `http` check whose connection was refused, dropped or timed out says "network error" by reqwest's error kind, not its wording), else `bad_spec`. A lease that ran out or a turn that ended without a review is `stalled`; over budget is `budget`; a denied action is `denied`; a task waiting on the person is `needs_input`. Other errors are `quota` (a usage limit or empty balance: Claude's "usage limit reached" / "hit your limit" / "5-hour limit reached", credit too low, insufficient_quota, 402, and kwant's own "is out of usage" / "Quota exceeded"), then `auth` (not logged in, 401, expired token, and kwant's own "signed out or its key was rejected" / "No account can run bots" / no other account on), then `transient` (rate limit, overloaded, timeouts, connection errors, 429/500/502/503/504/529 as whole numbers), else `unknown`.- The text is redacted (credentials in URLs, `sk-`/`xai-`/`ghp_`… prefixes, long digit-bearing tokens) before it is stored. A check's spec is masked the same way wherever it is shown (task JSON, Needs-you text, failure excerpt, retry prompt, workflow changes); the stored spec keeps the real values, and a `workflow_propose` whose spec still holds `[redacted]` is refused. The excerpt is at most 2,000 characters. The full redacted output goes to `<data_dir>/autofix/<task_id>/<uuid>.log` (folder 0700, file 0600, 256 KB). No route returns that path.### Attempts- `autofix_attempts`: `id`, `task_id`, `failure_id`, `strategy`, `status` (`suggested`, `scheduled`, `running`, `succeeded`, `failed`, `skipped`), `not_before`, `reason`, `retry_task_id`, `tokens_spent`, `created_at`, `finished_at`, and server-only `idempotency_key` (unique: sha256 of task, failure and strategy, so a failure is never planned twice). At most one `scheduled`/`running` attempt per task (`autofix_one_live`), and a trigger refuses one past the task's `max_attempts`.-- Strategies: `transient` → `wait_and_retry` after 1, 5, then 25 minutes; `stalled` → `retry_from_checkpoint` (the folder is as the run left it) or `retry_same`; `check_failed` → `retry_with_diagnostics`; `bad_spec` → `propose_change` (a `check_spec` proposal making the check optional; the attempt stays `suggested` and never runs); `unknown` → `retry_same`, once per task. `auth`, `budget` and `denied` are never retried: a `skipped` attempt with what to do and a `fix_needed` Needs-you item. `needs_input` and hand-off tasks get no attempt.+- Strategies: `transient` → `wait_and_retry` after 1, 5, then 25 minutes; `stalled` → `retry_from_checkpoint` (the folder is as the run left it) or `retry_same`; `check_failed` → `retry_with_diagnostics`; `bad_spec` → `propose_change` (a `check_spec` proposal making the check optional; the attempt stays `suggested` and never runs); `unknown` → `retry_same`, once per task. `auth`, `quota`, `budget` and `denied` are never retried: a `skipped` attempt with what to do and a `fix_needed` Needs-you item. `needs_input` and hand-off tasks get no attempt.- Limits, checked when planning and again when starting: a `blocked` task is never moved (`not_retryable`); no attempts left (`no_attempts_left`); `recovery_spent_tokens` plus the average spend per attempt over the recovery budget (`over_recovery_budget`). A limit makes the attempt `skipped` with that reason; a skip for `over_recovery_budget` also gives the failed task a `fix_needed` Needs-you item ("Retry budget used up: raise it or retry by hand.").- While attempts are left and AutoFix isn't off, a failure parks the task in `failed` instead of `ready` (no "failed" chat line). The retry moves it `failed → ready` as `Actor::AutoFix`, the only move that actor may make, with a task event of kind `autofix`. A routine run is retried as a new routine run; its task gets `forked_from` = the failed task and counts on from its attempts, and the failed task stays `failed`.- Recovery spend: a claim taken while an attempt runs carries its `autofix_id`, and that claim's spend (at hand-in and at turn end) also adds to `tasks.recovery_spent_tokens` and the attempt's `tokens_spent`. Plain runs never count as recovery. Token budgets (the task's and the recovery budget) count fresh input, cache writes and output, as Phase A spend does; cached input that is read again (`cache_read`) is left out. `model_usage.cost_usd` is the real-money figure.diff --git a/frontend/src/missions.ts b/frontend/src/missions.tsindex 1fb434a5..c571a915 100644--- a/frontend/src/missions.ts+++ b/frontend/src/missions.ts@@ -124,7 +124,7 @@ export interface Task {export type AutofixMode = 'off' | 'suggest' | 'on';export type FailureClass =- | 'transient' | 'stalled' | 'check_failed' | 'bad_spec' | 'auth' | 'budget' | 'denied' | 'needs_input' | 'unknown';+ | 'transient' | 'stalled' | 'check_failed' | 'bad_spec' | 'auth' | 'quota' | 'budget' | 'denied' | 'needs_input' | 'unknown';export type FailureSource = 'check' | 'turn' | 'lease' | 'budget' | 'routine' | 'handoff';export type AutofixStrategy =| 'wait_and_retry' | 'retry_from_checkpoint' | 'retry_with_diagnostics' | 'retry_same' | 'propose_change' | 'none';diff --git a/src/db/autofix.rs b/src/db/autofix.rsindex 235aa6ca..c0561b04 100644--- a/src/db/autofix.rs+++ b/src/db/autofix.rs@@ -14,7 +14,7 @@ use sqlx::FromRow;use uuid::Uuid;pub const SOURCES: [&str; 6] = ["check", "turn", "lease", "budget", "routine", "handoff"];-pub const CLASSES: [&str; 9] = ["transient", "stalled", "check_failed", "auth", "budget", "denied", "bad_spec", "needs_input", "unknown"];+pub const CLASSES: [&str; 10] = ["transient", "stalled", "check_failed", "auth", "quota", "budget", "denied", "bad_spec", "needs_input", "unknown"];pub const STRATEGIES: [&str; 6] = ["retry_same", "retry_with_diagnostics", "retry_from_checkpoint", "wait_and_retry", "propose_change", "none"];pub const TARGETS: [&str; 5] = ["routine_instructions", "routine_schedule", "check_spec", "task_acceptance", "max_attempts"];@@ -127,7 +127,7 @@ impl Database {task_id TEXT NOT NULL REFERENCES tasks(id),attempt INTEGER NOT NULL,source TEXT NOT NULL CHECK (source IN ('check', 'turn', 'lease', 'budget', 'routine', 'handoff')),- class TEXT NOT NULL CHECK (class IN ('transient', 'stalled', 'check_failed', 'auth', 'budget', 'denied', 'bad_spec', 'needs_input', 'unknown')),+ class TEXT NOT NULL CHECK (class IN ('transient', 'stalled', 'check_failed', 'auth', 'quota', 'budget', 'denied', 'bad_spec', 'needs_input', 'unknown')),summary TEXT NOT NULL,excerpt TEXT,diagnostics_path TEXT,diff --git a/src/server/missions/autofix.rs b/src/server/missions/autofix.rsindex 60ff42df..a8568828 100644--- a/src/server/missions/autofix.rs+++ b/src/server/missions/autofix.rs@@ -58,7 +58,7 @@ pub fn settings_error(mode: Option<&str>, pct: Option<i64>) -> Option<String> {// Classification-const AUTH: [&str; 17] = [+const AUTH: [&str; 16] = ["not logged in","not signed in","/login",@@ -70,7 +70,6 @@ const AUTH: [&str; 17] = ["authentication_error","token has expired","login has expired",- "credit balance is too low",// kwant's own messages when no account can take the turn (profile_turn.rs, drivers/engines.rs)"signed out","key was rejected",@@ -79,6 +78,24 @@ const AUTH: [&str; 17] = ["no custom api account is on",];+// A usage limit or empty balance: a retry before it resets only burns an attempt+const QUOTA: [&str; 13] = [+ "usage limit",+ "hit your limit",+ "reached your limit",+ "hour limit reached",+ "weekly limit reached",+ "out of credits",+ "insufficient_quota",+ "exceeded your current quota",+ "usage_limit_exceeded",+ "credit balance is too low",+ "billing_error",+ // kwant's own messages when an account ran out (profile_turn.rs, drivers/engines.rs)+ "out of usage",+ "quota exceeded",+];+const TRANSIENT: [&str; 18] = ["rate limit","rate-limit",@@ -115,6 +132,10 @@ fn is_auth(t: &str) -> bool {AUTH.iter().any(|p| t.contains(p)) || has_code(t, "401")}+fn is_quota(t: &str) -> bool {+ QUOTA.iter().any(|p| t.contains(p)) || has_code(t, "402")+}+fn is_transient(t: &str) -> bool {TRANSIENT.iter().any(|p| t.contains(p)) || TRANSIENT_CODES.iter().any(|c| has_code(t, c))}@@ -133,7 +154,9 @@ pub fn classify(source: &str, status: &str, text: &str) -> &'static str {("turn", "stalled") => "stalled",("turn", "denied") => "denied",("turn", "needs_input") => "needs_input",- // auth before transient: "401" next to "Reconnecting… timed out" is still a login problem+ // quota and auth before transient: "429 usage limit reached" won't pass in a minute, and+ // "401" next to "Reconnecting… timed out" is still a login problem+ (_, _) if is_quota(&t) => "quota",(_, _) if is_auth(&t) => "auth",(_, _) if is_transient(&t) => "transient",_ => "unknown",@@ -159,6 +182,7 @@ pub const RECOVERY_BUDGET_FIX: &str = "Retry budget used up: raise it or retry bfn fix_text(class: &str, summary: &str) -> Option<String> {match class {"auth" => Some(format!("Sign in to the bot's engine again, then retry: {summary}")),+ "quota" => Some(format!("Usage limit reached: wait for it to reset or switch account, then retry: {summary}")),"budget" => Some("Raise the task's budget, then retry it.".into()),"denied" => Some("An action was denied during the run. Decide whether it may run, then retry.".into()),_ => None,@@ -746,7 +770,7 @@ pub async fn run_autofix(State(state): State<AppState>, RawQuery(q): RawQuery, hSome(fid) => failures.iter().find(|f| &f.id == fid).cloned().ok_or_else(|| not_found("failure"))?,None => failures.last().cloned().ok_or_else(|| coded(StatusCode::CONFLICT, "not_retryable", "the task has no failure to fix"))?,};- if t.state != "failed" || matches!(failure.class.as_str(), "auth" | "budget" | "denied" | "needs_input" | "bad_spec") || t.source_kind == "delegation" {+ if t.state != "failed" || matches!(failure.class.as_str(), "auth" | "quota" | "budget" | "denied" | "needs_input" | "bad_spec") || t.source_kind == "delegation" {return Err(coded(StatusCode::CONFLICT, "not_retryable", "AutoFix can't retry this; see the task's Needs-you item"));}if let Some(code) = limit(&state, &t).await {@@ -1061,6 +1085,50 @@ mod tests {assert!(!texts[0].contains("401"), "{}", texts[0]);}+ #[test]+ fn kwants_own_out_of_usage_messages_are_quota() {+ use crate::db::models::LlmProfile;+ use crate::profiles::classify::{FailClass, ProviderFailure};+ use crate::server::profile_turn::{give_up_notice, switch_notice};+ let p = |name: &str| LlmProfile {+ id: name.into(),+ engine: "claude".into(),+ name: name.into(),+ kind: "subscription".into(),+ home_dir: None,+ priority: 0,+ enabled: true,+ is_default: true,+ created_at: None,+ space_id: "spc_default".into(),+ };+ let reset = chrono::Utc::now() + chrono::Duration::hours(2);+ let until = ProviderFailure { class: FailClass::Quota, retry_at: Some(reset), detail: "429".into() };+ let open = ProviderFailure { class: FailClass::Quota, retry_at: None, detail: String::new() };+ // The exact texts a turn ends with, built by the code that writes them: a rewording breaks this+ let texts = [+ give_up_notice("Ann", &p("This machine"), &until, 1),+ give_up_notice("Ann", &p("Work"), &open, 2),+ switch_notice(&p("Work"), &p("Personal"), &until),+ // and the Claude CLI's own usage-limit lines+ "Claude AI usage limit reached|1792162800".to_string(),+ "You've hit your limit · resets 5pm".to_string(),+ "You've hit your usage limit. Upgrade to Pro or try again in 3 hours 20 minutes.".to_string(),+ "5-hour limit reached ∙ resets 3pm".to_string(),+ "Your credit balance is too low to access the Anthropic API".to_string(),+ "API Error: 429 {\"type\":\"error\",\"error\":{\"message\":\"usage limit reached\"}}".to_string(),+ ];+ for t in &texts {+ assert_eq!(classify("turn", "error", t), "quota", "{t}");+ assert_eq!(strategy_for(classify("turn", "error", t)), "none", "{t}");+ let fix = fix_text("quota", t).unwrap();+ assert!(fix.starts_with("Usage limit reached: wait for it to reset or switch account"), "{fix}");+ }+ // A plain rate limit still passes in a minute+ assert_eq!(classify("turn", "error", "stream error: rate-limiting (HTTP 429)"), "transient");+ assert_eq!(classify("turn", "error", "rate limit exceeded, retry in 20s"), "transient");+ }+#[tokio::test]async fn an_http_check_on_a_closed_port_is_transient_and_waits() {let port = {diff --git a/tests/mission_autofix_test.rs b/tests/mission_autofix_test.rsindex d4da0557..e27e23d7 100644--- a/tests/mission_autofix_test.rs+++ b/tests/mission_autofix_test.rs@@ -289,10 +289,15 @@ fn classify_maps_every_signal_to_its_class() {("turn", "error", "OAuth token has expired. Please obtain a new token or refresh your existing token.", "auth"),("turn", "error", "API key rejected (401)", "auth"),("turn", "error", "unexpected status 401 Unauthorized: Reconnecting… timed out", "auth"),- ("turn", "error", "Credit balance is too low", "auth"),+ ("turn", "error", "Credit balance is too low", "quota"),+ ("turn", "error", "Claude AI usage limit reached|1792162800", "quota"),+ ("turn", "error", "You've hit your limit · resets 5pm", "quota"),+ ("turn", "error", "5-hour limit reached ∙ resets 3pm", "quota"),+ ("turn", "error", "API Error: 429 usage limit reached", "quota"),+ ("turn", "error", "Error: insufficient_quota: You exceeded your current quota", "quota"),("turn", "error", "API Error: 529 {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\"}}", "transient"),("turn", "error", "stream error: rate-limiting (HTTP 429)", "transient"),- ("routine", "error", "Quota exceeded (429)", "transient"),+ ("routine", "error", "Quota exceeded (429)", "quota"),("handoff", "error", "error sending request: connection refused", "transient"),("turn", "error", "upstream 503 Service Unavailable", "transient"),("turn", "error", "the model said something odd", "unknown"),@@ -513,6 +518,11 @@ async fn auth_budget_and_denied_are_never_retried_and_ask_the_person() {let started = Utc::now();claim(&e, &auth).await;runner::after_turn(&e.state, &auth, Some("Not logged in · Please run /login"), started).await;+ // a usage limit: a retry before it resets only burns an attempt+ let quota = person_task(&e, json!([])).await;+ let started = Utc::now();+ claim(&e, "a).await;+ runner::after_turn(&e.state, "a, Some("Claude AI usage limit reached|1792162800"), started).await;// deniedlet denied = person_task(&e, json!([])).await;let started = Utc::now();@@ -523,7 +533,7 @@ async fn auth_budget_and_denied_are_never_retried_and_ask_the_person() {.await.unwrap();runner::after_turn(&e.state, &denied, None, started).await;- for (tid, class) in [(&auth, "auth"), (&denied, "denied")] {+ for (tid, class) in [(&auth, "auth"), ("a, "quota"), (&denied, "denied")] {let t = task(&e, tid).await;assert_eq!(t["state"], "failed", "{t}");assert_eq!(t["last_failure"]["class"], class, "{t}");@@ -531,6 +541,10 @@ async fn auth_budget_and_denied_are_never_retried_and_ask_the_person() {assert_eq!(a.len(), 1, "{a:?}");assert_eq!((a[0].strategy.as_str(), a[0].status.as_str()), ("none", "skipped"), "{a:?}");assert!(kinds(&t["needs_you"]).contains(&"fix_needed".to_string()), "{t}");+ if class == "quota" {+ let texts = t["needs_you"].to_string();+ assert!(texts.contains("Usage limit reached: wait for it to reset or switch account"), "{t}");+ }let (status, v) = send(&e.app, "POST", &format!("/api/tasks/{tid}/autofix"), None, None).await;assert_eq!((status, v["code"].as_str()), (StatusCode::CONFLICT, Some("not_retryable")), "{v}");}