Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix(host): stop the sign-in loop when an agent's login is revoked
leepokaif7ce3410f44f
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.mdindex 87aab2f3..58a72137 100644--- a/docs/features/marketplace.md+++ b/docs/features/marketplace.md@@ -44,6 +44,10 @@ Clicking a skill (an Extensions row, an installed skill, or the info button besiRegistry-backed package connectors follow their upstream release. The host checks the Registry periodically after credentials are unlocked and checks again immediately before a package process starts. If a newer pinned npm, PyPI, OCI or NuGet reference is available, only that package/image argument is replaced; the running process is not interrupted, and the new version applies on its next launch. Network failures, missing packages and attempted downgrades leave the installed reference unchanged. Custom command connectors are never updated automatically.+## A login that stops working++An agent's process keeps the credentials it started with, and its account check can still say signed in when they no longer work (`claude auth status` reports `loggedIn: true` with a revoked OAuth token). So a prompt the agent refuses for auth (`acp::needs_sign_in`, `agent/bot/queue.rs` `invite_sign_in`) always drops the bot's process. When that process was already running before the turn, the turn's messages go out again on a new one first (`agent_sign_in::send_again`), which picks up a sign-in done elsewhere. Only a refusal on a process started for the turn posts the sign-in card and marks the agent refused (`note_prompt_refused`): from then on its account check reads signed out, so the sheet offers to sign in instead of showing *Signed in*, until a prompt goes through or a sign-in finishes in Codync (a setup terminal that exits 0, `authenticate`, saved keys).+## Codex usageThe host asks the installed Codex CLI's app-server `account/rateLimits/read` method for the current account's plan windows every five minutes. Executable lookup and process startup run on a blocking worker. It initializes the CLI transport without creating a thread or model turn, then stops the probe through the host's existing process-tree cleanup. Startup, handshake and account-read failures retain their phase and cause in structured debug logs. The canonical `rateLimitsByLimitId.codex` bucket takes precedence over the older single `rateLimits` view. Reset timestamps are Unix seconds and become milliseconds in the existing `usage` event.diff --git a/host/src/agent/auth.rs b/host/src/agent/auth.rsindex 92fceab0..afc48a05 100644--- a/host/src/agent/auth.rs+++ b/host/src/agent/auth.rs@@ -291,6 +291,8 @@ pub async fn set_env(store: &Store, backend: &str, vars: &Map<String, Value>) ->};}crate::market::vault::write(store, &env_slot(backend), &serde_json::to_string(&saved)?)?;+ // New keys are a new sign-in: the prompt the old ones got refused no longer counts.+ backends::clear_prompt_refused(backend);check(store, backend).await}diff --git a/host/src/agent/backends/sign_in.rs b/host/src/agent/backends/sign_in.rsindex 7a4494d6..3f5811f4 100644--- a/host/src/agent/backends/sign_in.rs+++ b/host/src/agent/backends/sign_in.rs@@ -37,17 +37,13 @@ pub fn signed_in(id: &str) -> Option<bool> {SIGNED_IN.locked().iter().find(|(h, _)| h == id).map(|(_, ok)| *ok)}-/// A prompt was refused because the agent asked for auth. Only an agent whose new session does-/// not prove sign-in (`WorkBuddy`) can still report an account after that. Other agents' own-/// checks stand, so a setup terminal or saved keys can sign them in.+/// Agents whose prompt was refused because they asked for auth. Their own account check can still+/// say signed in after that (`claude auth status` with a revoked token, `WorkBuddy`'s account).static PROMPT_REFUSED: Mutex<Vec<String>> = Mutex::new(Vec::new());-/// The latest prompt for `id` was refused for auth. Stands until a prompt succeeds or the user signs in again.-/// An agent whose session proves sign-in is not recorded: its next check is the proof.+/// The latest prompt for `id` was refused for auth. Stands until a prompt succeeds or a sign-in+/// finishes in Codync (a setup terminal, the browser, saved keys).pub fn note_prompt_refused(id: &str) {- if super::workbuddy::session_proves_sign_in(id) {- return;- }let mut refused = PROMPT_REFUSED.locked();if !refused.iter().any(|known| known == id) {refused.push(id.to_owned());@@ -59,11 +55,7 @@ pub fn clear_prompt_refused(id: &str) {}/// An account check that says signed in loses to a prompt that was just refused for auth.-/// Other agents are unchanged: their check is what a finished terminal or saved keys report.pub fn apply_prompt_refusal(id: &str, probe: Option<bool>) -> Option<bool> {- if super::workbuddy::session_proves_sign_in(id) {- return probe;- }if probe == Some(true) && PROMPT_REFUSED.locked().iter().any(|known| known == id) { Some(false) } else { probe }}@@ -82,7 +74,7 @@ pub async fn refresh_sign_in() {let results =futures::future::join_all(installed.map(|h| async move { (h.id, cli_signed_in(h, &[]).await) })).await;for (id, ok) in results {- set_signed_in(id, ok);+ set_signed_in(id, apply_prompt_refusal(id, ok));}}@@ -126,11 +118,17 @@ mod tests {}#[test]- fn another_agents_sign_in_check_is_not_held_back() {- let id = "qwen";+ fn a_revoked_claude_login_is_not_signed_in() {+ let id = "claude";clear_prompt_refused(id);note_prompt_refused(id);- assert_eq!(apply_prompt_refusal(id, Some(true)), Some(true), "a setup terminal or saved keys can sign it in");+ assert_eq!(+ apply_prompt_refusal(id, Some(true)),+ Some(false),+ "`claude auth status` doesn't see a revoked token"+ );assert_eq!(apply_prompt_refusal(id, None), None);+ clear_prompt_refused(id);+ assert_eq!(apply_prompt_refusal(id, Some(true)), Some(true), "a finished sign-in counts again");}}diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex 7bbce246..aed34621 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -8,7 +8,7 @@ use crate::market::agent_sign_in;use crate::store::{Lane, now_ms};use anyhow::{Result, anyhow};use serde_json::json;-use std::time::Instant;+use std::time::{Duration, Instant};use tokio::sync::mpsc;impl Actor {@@ -337,23 +337,36 @@ impl Actor {/// When `e` asks for signing in: marks the harness signed out and puts a sign-in card in the/// chat, which sends this turn's messages again once the user has signed in. Whether it did.+ /// A process older than the turn may hold a sign-in replaced since: a new one tries its messages first.pub(super) fn invite_sign_in(&mut self, e: &anyhow::Error) -> bool {let backend = self.cfg.backend.clone();if crate::agent::backends::harness(&backend).is_none() || !crate::agent::acp::needs_sign_in(e) {return false;}+ // The process keeps the credentials it started with (Claude's revoked token): the next turn starts a new one.+ self.restart_after_turn = true;let held = self.held_for_sign_in().to_vec();+ if self.process_predates_turn() && !held.is_empty() {+ match agent_sign_in::send_again(&self.hub, &self.cfg.id, held.iter().map(String::as_str)) {+ Ok(()) => return true,+ Err(error) => tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't retry"),+ }+ }crate::agent::backends::set_signed_in(&backend, Some(false));- // WorkBuddy can still report an account after this, which is not a working login.- // Other agents' own checks are left alone, so a terminal or saved keys can sign them in.- // WorkBuddy's current process was opened before that, so drop it.+ // An account check can still say signed in (`claude auth status` with a revoked token): this refusal wins.crate::agent::backends::note_prompt_refused(&backend);- if !crate::agent::backends::session_proves_sign_in(&backend) {- self.restart_after_turn = true;- }self.sign_in_card(&backend, &held)}+ /// The agent's process was already running when this turn started.+ fn process_predates_turn(&self) -> bool {+ let (Some(conn), Some(started_at)) = (&self.conn, self.hub.runtime(&self.id()).started_at) else {+ return false;+ };+ let turn_age = Duration::from_millis(u64::try_from(now_ms() - started_at).unwrap_or(0));+ conn.started.elapsed() > turn_age+ }+/// Agent `backend`'s sign-in card in the chat, holding `entries`. Whether it's there.pub(super) fn sign_in_card(&self, backend: &str, entries: &[String]) -> bool {let Some(h) = crate::agent::backends::harness(backend) else { return false };diff --git a/host/src/agent/term.rs b/host/src/agent/term.rsindex ffb8b8b2..e3b4852c 100644--- a/host/src/agent/term.rs+++ b/host/src/agent/term.rs@@ -259,6 +259,10 @@ async fn run(_ => -1,};tracing::info!(term = %id, code, "setup terminal finished");+ // A finished sign-in is believed again, over the prompt its agent refused before.+ if term.key.1 == Step::Login && code == 0 {+ backends::clear_prompt_refused(&term.key.0);+ }term.finish(code);tokio::time::sleep(LINGER).await;terms.0.locked().remove(&id);diff --git a/host/src/market/agent_sign_in.rs b/host/src/market/agent_sign_in.rsindex 88aedcc3..e4600875 100644--- a/host/src/market/agent_sign_in.rs+++ b/host/src/market/agent_sign_in.rs@@ -142,16 +142,22 @@ pub fn agent_signed_in(hub: &Hub, backend: &str) -> Result<()> {let mut data = card.data.clone();data["connectionRequest"]["status"] = serde_json::to_value(RequestStatus::Ready)?;hub.set_entry(&card.id, &data).ok_or_else(|| anyhow!("Could not complete the sign-in request"))?;- let Some(bot) = hub.store.bot(&card.bot_id)?.filter(|b| !b.deleted) else { continue };let ids = data["connectionRequest"]["entryIds"].as_array().cloned().unwrap_or_default();- let held = ids.iter().filter_map(Value::as_str).filter_map(|id| hub.store.entry(id));- for mut entry in held.filter(|entry| now_ms() - entry.created_at <= MAX_AGE) {- let prompt = crate::chat::prompt::of_entry(hub, &bot.config, &entry.data);- entry.data["status"] = "queued".into();- hub.set_entry(&entry.id, &entry.data);- let lane = Lane::main(&entry.bot_id);- hub.send_cmd(&card.bot_id, Cmd::Send { lane, entry_id: entry.id, text: prompt })?;- }+ send_again(hub, &card.bot_id, ids.iter().filter_map(Value::as_str))?;+ }+ Ok(())+}++/// `bot` answers the user messages `ids` it couldn't answer (a message older than a day doesn't go out).+pub fn send_again<'a>(hub: &Hub, bot: &str, ids: impl IntoIterator<Item = &'a str>) -> Result<()> {+ let Some(bot) = hub.store.bot(bot)?.filter(|b| !b.deleted) else { return Ok(()) };+ let held = ids.into_iter().filter_map(|id| hub.store.entry(id));+ for mut entry in held.filter(|entry| now_ms() - entry.created_at <= MAX_AGE) {+ let prompt = crate::chat::prompt::of_entry(hub, &bot.config, &entry.data);+ entry.data["status"] = "queued".into();+ hub.set_entry(&entry.id, &entry.data);+ let lane = Lane::main(&entry.bot_id);+ hub.send_cmd(&bot.config.id, Cmd::Send { lane, entry_id: entry.id, text: prompt })?;}Ok(())}diff --git a/host/tests/fallback_e2e.rs b/host/tests/fallback_e2e.rsindex a02bd164..37c1e90e 100644--- a/host/tests/fallback_e2e.rs+++ b/host/tests/fallback_e2e.rs@@ -280,3 +280,38 @@ async fn an_error_inside_a_refusal_holds_the_message_or_says_what_it_is() {host.call("send", json!({"botId": bot, "text": "Once more", "clientNonce": "n3"})).await;wait_for(&host, &bot, "declined notice", |e| e["data"]["text"] == "The agent declined to continue.").await;}++#[tokio::test]+async fn a_process_with_a_replaced_sign_in_starts_again_before_asking_to_sign_in() {+ let host = Host::start().await;+ let bot =+ json!({"name": "Solo", "backend": "kimi", "command": agent("primary"), "connectors": [], "notify": false});+ let bot = host.call("createBot", bot).await["bot"]["id"].as_str().unwrap().to_owned();+ let folder = host.home.join("bots").join(&bot).join("workspace");+ host.reply(&bot, "Hello").await;+ wait_for(&host, &bot, "first reply", |e| e["data"]["final"] == true).await;+ let prompts = || host.log(&bot, "primary.jsonl").iter().filter(|r| r["method"] == "session/prompt").count();+ let answered = |history: &Value| {+ history["entries"].as_array().unwrap().iter().filter(|e| e["data"]["text"] == "primary answered").count()+ };++ // The running process holds a sign-in replaced since (Claude's revoked token): a new process answers, no card.+ std::fs::write(folder.join("primary.revoked"), "").unwrap();+ host.call("send", json!({"botId": bot, "text": "Fix the build", "clientNonce": "n1"})).await;+ let deadline = Instant::now() + Duration::from_secs(30);+ while answered(&host.call("history", json!({"botId": bot})).await) < 2 {+ assert!(Instant::now() < deadline, "the message wasn't answered again");+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert!(last_prompt(&host, &bot, "primary").contains("Fix the build"));+ assert_eq!(prompts(), 3, "the old process's try and the new one's");+ let history = host.call("history", json!({"botId": bot})).await;+ assert!(!history["entries"].as_array().unwrap().iter().any(|e| e["data"]["connectionRequest"].is_object()));++ // Signed out for real: the new process is refused too, and only then the card holds the message.+ std::fs::write(folder.join("primary.signedout"), "").unwrap();+ host.call("send", json!({"botId": bot, "text": "Again", "clientNonce": "n2"})).await;+ let card = wait_for(&host, &bot, "sign-in card", |e| e["data"]["connectionRequest"]["kind"] == "agent").await;+ assert_eq!(card["data"]["connectionRequest"]["entryIds"].as_array().map(Vec::len), Some(1), "{card}");+ assert_eq!(prompts(), 5, "tried once more on a new process, then no more");+}diff --git a/host/tests/fixtures/relay_agent.py b/host/tests/fixtures/relay_agent.pyindex 545daf17..d4306b02 100644--- a/host/tests/fixtures/relay_agent.py+++ b/host/tests/fixtures/relay_agent.py@@ -1,6 +1,7 @@"""ACP agent for the fallback chain test, run as `relay_agent.py <name>`. While `<name>.limit` exists in its folder,every prompt edits a file and then fails the way Claude's adapter reports a usage limit; otherwise it answers-"<name> answered". While `<name>.signedout` exists, every prompt fails asking to sign in (ACP's -32000). While+"<name> answered". While `<name>.signedout` exists, every prompt fails asking to sign in (ACP's -32000); while+`<name>.revoked` exists, only a process started before it does (it holds the sign-in that file replaced). While`<name>.refusal` exists, every prompt answers `refusal` with the file's text as `_meta["codebuddy.ai/errorMessage"]`, theway CodeBuddy's CLI reports an error (an empty file: a plain refusal). Sessions load (`<name>-s<n>`) unless`<name>.noload` exists; every request goes to `<name>.jsonl` in its folder."""@@ -8,7 +9,9 @@ way CodeBuddy's CLI reports an error (an empty file: a plain refusal). Sessionsimport jsonimport osimport sys+import time+STARTED = time.time()NAME = sys.argv[1]LIMIT = {"code": -32603,@@ -45,7 +48,8 @@ for line in sys.stdin:send({"id": message["id"], "result": {}})elif method == "session/prompt":sid = params["sessionId"]- if os.path.exists(f"{NAME}.signedout"):+ revoked = os.path.exists(f"{NAME}.revoked") and os.path.getmtime(f"{NAME}.revoked") > STARTED+ if os.path.exists(f"{NAME}.signedout") or revoked:send({"id": message["id"], "error": {"code": -32000, "message": "Authentication required"}})elif os.path.exists(f"{NAME}.refusal"):with open(f"{NAME}.refusal", encoding="utf-8") as f:diff --git a/web/content/docs/agents.mdx b/web/content/docs/agents.mdxindex 23963569..e7603613 100644--- a/web/content/docs/agents.mdx+++ b/web/content/docs/agents.mdx@@ -2,6 +2,8 @@ Every bot runs one coding agent on your computer. Codync drives agents through tCodync uses the agents with the accounts they're already signed in to on your computer, such as Claude Code with your Claude plan or Codex with your ChatGPT plan. It never calls a provider's API with your login.+If an agent's login stops working (for example, signing in somewhere else revoked it), the bot first tries your message again on a fresh start of the agent, which picks up a newer login on the computer. If that fails too, the chat shows the agent's sign-in card: **Sign in** opens the agent's sign-in options, and your message goes out again once you've signed in.+## Usage limitsOn desktop, open **Settings > Usage** to see the limits reported by your connected computers. The host refreshes usage every five minutes.