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): bring back a chat whose agent session ended, and report why turns fail
leepokai430e87e4dd08
diff --git a/docs/architecture/conversation-runtime.md b/docs/architecture/conversation-runtime.mdindex 1fa0bb12..dd679ec0 100644--- a/docs/architecture/conversation-runtime.md+++ b/docs/architecture/conversation-runtime.md@@ -3,6 +3,7 @@- **Chat ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is resumed with `session/load` or replaced by *New session*.- **Agent processes**: a bot's agent starts on its first message and keeps its sessions loaded between messages. A session unused for 30 minutes is closed (agents with `session/close`), and once all of them are idle the agent stops with its process group; the next message starts it again and loads the session (`agent/bot/lifecycle.rs`). Nothing is released mid-turn or while a queue, approval or request waits. Agents that can't load sessions stay, and so do agents with something running detached in a session of its own, like a dev server from Claude Code's shell tool (stopping the agent would orphan it); MCP servers don't count, even in a process group of their own as Codex starts them. Codex unloads a closed session's thread, and its MCP servers, only after another 30 minutes. Windows agents are never stopped for idleness: without process groups a dev server can't be told from an MCP server, and stopping ends the whole tree.- **Group chats and threads** are host features every client drives through the same methods (`send` with `threadId`, `thread`, `createBot {kind: group}`); clients never route, parse mentions or count replies themselves. A group is a roster row whose members answer in their own sessions (Grok Bot's room turns); a thread on a bot's message is a forked session: [docs/features/groups-and-threads.md](../features/groups-and-threads.md).+- **A session that fails** with an internal error its agent gives no category (JSON-RPC `-32603` without `data.errorKind`) is closed right after the turn, when the agent can close and load sessions: Claude's adapter otherwise answers every later prompt on it with "The Claude Agent session has ended". The next message loads it again and the conversation carries on (`acp::may_end_session`).- Bot collaboration: built-in `team` MCP (`chat/team.rs`) lists visible bots and asks one for a reply or sends it an independent message through its actor queue. Asks are separate turns, cycle-checked and cancellable; native subagents stay with the harness. See [docs/features/bot-collaboration.md](../features/bot-collaboration.md).- **Context & memory**: frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, memory in the host (a layer shared by all bots and one per bot, written by the user, the bots' tools and dreaming), busy-time messages folded into one turn, interrupted turns resumed: [docs/features/context-and-memory.md](../features/context-and-memory.md).- **Chat shows only**: user messages, the bot's messages (`data.final`: each `send_message` call from the built-in `chat` MCP, Grok Bot's way; a turn that sent none falls back to its last text), permission cards, notices. Nothing streams into a bubble; narration, thoughts, tool calls, plans are trace entries (Full conversation sheet): [docs/features/chat-messages.md](../features/chat-messages.md).diff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rsindex f7303ac1..4adbfed4 100644--- a/host/src/agent/acp.rs+++ b/host/src/agent/acp.rs@@ -37,10 +37,15 @@ type Pending = Arc<std::sync::Mutex<HashMap<i64, oneshot::Sender<Result<Value, Vpub struct RpcError {pub code: i64,pub message: String,+ /// The adapter's own category (`data.errorKind`: Claude's `rate_limit`, `overloaded`, …), kept only+ /// when it's an identifier, as it can go to usage analytics.+ pub kind: Option<String>,}/// ACP's "authentication required".pub const AUTH_REQUIRED: i64 = -32000;+/// JSON-RPC's "internal error".+pub const INTERNAL_ERROR: i64 = -32603;impl std::fmt::Display for RpcError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {@@ -59,6 +64,13 @@ pub fn needs_sign_in(e: &anyhow::Error) -> bool {e.chain().any(rpc) || e.to_string().to_lowercase().contains("auth")}+/// Whether a failed prompt may have left its session dead in the agent: an internal error the+/// adapter gave no category. Claude's adapter answers every later prompt on a session whose query+/// stream ended with one ("The Claude Agent session has ended") until the session is closed.+pub fn may_end_session(e: &anyhow::Error) -> bool {+ e.chain().filter_map(|c| c.downcast_ref::<RpcError>()).any(|r| r.code == INTERNAL_ERROR && r.kind.is_none())+}+/// A way an agent fails that the host itself recognizes, kept as a type so usage/// analytics can count it (`turn_finished.error`) without its text.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -106,7 +118,13 @@ impl Answer {Some(d) => format!("{msg} ({d})"),None => msg,};- Err(RpcError { code: e["code"].as_i64().unwrap_or_default(), message }.into())+ let kind = e["data"]["errorKind"]+ .as_str()+ .filter(|k| {+ !k.is_empty() && k.len() <= 40 && k.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')+ })+ .map(str::to_owned);+ Err(RpcError { code: e["code"].as_i64().unwrap_or_default(), message, kind }.into())}// The reader drops every waiter when the process goes away.Err(_) => Err(Failure::error(FailureKind::Exited, "agent process exited")),@@ -366,6 +384,20 @@ mod tests {assert_eq!(truncate("héllo", 2), "h…");}+ #[tokio::test]+ async fn an_error_keeps_the_adapters_category_only_when_it_is_an_identifier() {+ let kind = |data: Value| async move {+ let (tx, rx) = oneshot::channel();+ let _ = tx.send(Err(json!({"code": -32603, "message": "Internal error", "data": data})));+ let e = Answer { rx }.response().await.expect_err("an error answer");+ e.downcast::<RpcError>().expect("an RpcError").kind+ };+ assert_eq!(kind(json!({"errorKind": "rate_limit"})).await.as_deref(), Some("rate_limit"));+ assert_eq!(kind(json!({"errorKind": "Usage: /Users/me"})).await, None);+ assert_eq!(kind(json!({"errorKind": ""})).await, None);+ assert_eq!(kind(json!("details")).await, None);+ }+#[cfg(unix)]#[tokio::test]async fn stopping_an_agent_closes_its_descendants_pipes() {diff --git a/host/src/agent/bot/lifecycle.rs b/host/src/agent/bot/lifecycle.rsindex b41e6a3d..32888eba 100644--- a/host/src/agent/bot/lifecycle.rs+++ b/host/src/agent/bot/lifecycle.rs@@ -86,17 +86,25 @@ impl Actor {&& self.cancel_deadline.is_none()}+ /// A session a turn failed in (see `acp::may_end_session`), closed when the agent can load it+ /// again: the next turn then loads it afresh instead of finding it dead.+ pub(super) async fn close_failed_session(&mut self, sid: &str) {+ if self.conn.as_ref().is_some_and(|c| c.sessions.close && c.sessions.load && c.loaded.contains_key(sid)) {+ self.close_session(sid).await;+ }+ }+async fn close_session(&mut self, sid: &str) {let closed = self.session_request("session/close", json!({ "sessionId": sid })).await;let Some(conn) = self.conn.as_mut() else { return };match closed {Ok(_) => {- tracing::info!(bot = %self.cfg.id, session = sid, "closed an idle session");+ tracing::info!(bot = %self.cfg.id, session = sid, "closed a session");conn.loaded.remove(sid);conn.fast_options.remove(sid);}Err(error) => {- tracing::warn!(bot = %self.cfg.id, session = sid, error = format!("{error:#}"), "couldn't close an idle session");+ tracing::warn!(bot = %self.cfg.id, session = sid, error = format!("{error:#}"), "couldn't close a session");// Try again after another idle period rather than every check.conn.loaded.insert(sid.to_owned(), Instant::now());}diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex c5bd9c49..a06efc33 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -27,7 +27,7 @@ mod updates;pub(crate) use launch::{launch_commands, select_model, start_agent, system_prompt};-use crate::agent::acp::{Acp, Incoming};+use crate::agent::acp::{self, Acp, Incoming};use crate::agent::config::FastModeSupport;use crate::chat::context::{Identity, Snapshot};use crate::chat::group::GroupTurn;@@ -379,7 +379,11 @@ impl Actor {while let Some(inc) = self.conn.as_mut().and_then(|c| c.rx.try_recv().ok()) {self.on_incoming(Some(inc)).await;}+ let failed_session = self.turn_session.clone().filter(|_| done.as_ref().is_err_and(acp::may_end_session));self.finish_turn(&done);+ if let Some(sid) = failed_session {+ self.close_failed_session(&sid).await;+ }self.next_in_queue(&done_tx).await;}_ = flush_tick.tick() => {diff --git a/host/src/analytics.rs b/host/src/analytics.rsindex 9f54e64a..2006d11e 100644--- a/host/src/analytics.rs+++ b/host/src/analytics.rs@@ -233,18 +233,21 @@ pub fn turn_finished(};let mut p = json!({"agent": agent, "outcome": outcome, "stop_reason": stop_reason, "source": source, "seconds": ms.max(0) / 1000});if let Some(e) = failure {- let (kind, rpc_code) = failure_kind(e);+ let (kind, rpc) = failure_kind(e);p["error"] = kind.into();- if let Some(code) = rpc_code {- p["rpc_code"] = code.into();+ if let Some(rpc) = rpc {+ p["rpc_code"] = rpc.code.into();+ if let Some(reason) = &rpc.kind {+ p["agent_reason"] = reason.as_str().into();+ }}}capture(hub, Event::TurnFinished, p.as_object().cloned().unwrap_or_default());}-/// Why a turn failed, as a category (plus the agent's JSON-RPC code): never the error's text,-/// which can hold paths and agent output.-fn failure_kind(e: &anyhow::Error) -> (&'static str, Option<i64>) {+/// Why a turn failed, as a category (plus the agent's JSON-RPC error, for its code and own+/// category): never the error's text, which can hold paths and agent output.+fn failure_kind(e: &anyhow::Error) -> (&'static str, Option<&crate::agent::acp::RpcError>) {use crate::agent::acp::{Failure, FailureKind, RpcError};if let Some(f) = e.chain().find_map(|c| c.downcast_ref::<Failure>()) {let kind = match f.kind {@@ -259,7 +262,7 @@ fn failure_kind(e: &anyhow::Error) -> (&'static str, Option<i64>) {}for cause in e.chain() {if let Some(r) = cause.downcast_ref::<RpcError>() {- return ("agent_error", Some(r.code));+ return ("agent_error", Some(r));}if let Some(io) = cause.downcast_ref::<std::io::Error>() {return (if io.kind() == std::io::ErrorKind::NotFound { "not_installed" } else { "io" }, None);@@ -469,18 +472,26 @@ mod tests {fn a_failed_turn_names_its_kind_not_its_text() {use crate::agent::acp::{Failure, FailureKind, RpcError};use anyhow::Context as _;+ let code = |e: &anyhow::Error| {+ let (kind, rpc) = failure_kind(e);+ (kind, rpc.map(|r| r.code))+ };let setup = Failure::error(FailureKind::NotSetUp, "Codex isn't set up on this computer.");- assert_eq!(failure_kind(&setup), ("not_installed", None));+ assert_eq!(code(&setup), ("not_installed", None));let hung = Err::<(), _>(Failure::error(FailureKind::Timeout, "no answer")).context("starting");- assert_eq!(failure_kind(&hung.expect_err("failed")), ("timeout", None));+ assert_eq!(code(&hung.expect_err("failed")), ("timeout", None));let missing = std::io::Error::new(std::io::ErrorKind::NotFound, "/Users/me/bin/agent");let spawn = Err::<(), _>(missing).context("starting `/Users/me/bin/agent`");- assert_eq!(failure_kind(&spawn.expect_err("failed")), ("not_installed", None));- let auth = anyhow::Error::new(RpcError { code: -32000, message: "Authentication required".into() });- assert_eq!(failure_kind(&auth), ("sign_in", None));- let rpc = anyhow::Error::new(RpcError { code: -32603, message: "Internal error: /Users/me".into() });- assert_eq!(failure_kind(&rpc), ("agent_error", Some(-32603)));- assert_eq!(failure_kind(&anyhow::anyhow!("something else")), ("other", None));+ assert_eq!(code(&spawn.expect_err("failed")), ("not_installed", None));+ let auth = anyhow::Error::new(RpcError { code: -32000, message: "Authentication required".into(), kind: None });+ assert_eq!(code(&auth), ("sign_in", None));+ let rpc =+ anyhow::Error::new(RpcError { code: -32603, message: "Internal error: /Users/me".into(), kind: None });+ assert_eq!(code(&rpc), ("agent_error", Some(-32603)));+ let limited =+ anyhow::Error::new(RpcError { code: -32603, message: "x".into(), kind: Some("rate_limit".into()) });+ assert_eq!(failure_kind(&limited).1.and_then(|r| r.kind.as_deref()), Some("rate_limit"));+ assert_eq!(code(&anyhow::anyhow!("something else")), ("other", None));}#[test]diff --git a/host/tests/fixtures/ended_session_agent.py b/host/tests/fixtures/ended_session_agent.pynew file mode 100644index 00000000..7dd2c520--- /dev/null+++ b/host/tests/fixtures/ended_session_agent.py@@ -0,0 +1,51 @@+"""ACP agent whose session can end under it, like Claude's adapter when its query stream stops:+"end-this-session" fails the turn, and every later prompt on that session fails with the same uncategorized+internal error until the session is closed. Loading a session that's still open keeps it as it is."""++import json+import sys++ENDED = {"code": -32603, "message": "The Claude Agent session has ended. Please start a new session."}+open_sessions = {} # id -> ended+++def send(value):+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", **value}) + "\n")+ sys.stdout.flush()+++def say(sid, text):+ update = {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}}+ send({"method": "session/update", "params": {"sessionId": sid, "update": update}})+++for line in sys.stdin:+ message = json.loads(line)+ method, params = message.get("method"), message.get("params") or {}+ if "id" not in message or method is None:+ continue+ if method == "initialize":+ capabilities = {"loadSession": True, "sessionCapabilities": {"close": {}}}+ send({"id": message["id"], "result": {"protocolVersion": 1, "agentCapabilities": capabilities}})+ elif method == "session/new":+ open_sessions["s1"] = False+ send({"id": message["id"], "result": {"sessionId": "s1"}})+ elif method == "session/load":+ open_sessions.setdefault(params["sessionId"], False)+ send({"id": message["id"], "result": {}})+ elif method == "session/close":+ open_sessions.pop(params["sessionId"], None)+ send({"id": message["id"], "result": {}})+ elif method == "session/prompt":+ sid = params["sessionId"]+ text = " ".join(b.get("text", "") for b in params["prompt"])+ if open_sessions.get(sid, True):+ send({"id": message["id"], "error": ENDED})+ elif "end-this-session" in text:+ open_sessions[sid] = True+ send({"id": message["id"], "error": ENDED})+ else:+ say(sid, "still here" if "still there?" in text else "pong")+ send({"id": message["id"], "result": {"stopReason": "end_turn"}})+ else:+ send({"id": message["id"], "error": {"code": -32601, "message": "not supported"}})diff --git a/host/tests/turns_e2e.rs b/host/tests/turns_e2e.rsindex 76a8b25a..b26a1cb6 100644--- a/host/tests/turns_e2e.rs+++ b/host/tests/turns_e2e.rs@@ -226,3 +226,22 @@ async fn a_refused_fast_mode_is_reported_and_not_asked_for_again() {host.wait_for(&bot, Duration::from_secs(60), speed_reply("fast off", "three")).await;assert_eq!(log().matches(FAST_ON).count(), 2);}++#[tokio::test]+async fn a_session_that_ended_in_the_agent_is_closed_and_loaded_again() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let bot = host.bot("Ended", "tests/fixtures/ended_session_agent.py").await;+ host.call("send", json!({"botId": bot, "text": "hello"})).await;+ host.wait_for(&bot, Duration::from_secs(60), |e| e["kind"] == "agent" && e["data"]["text"] == "pong").await;+ host.call("send", json!({"botId": bot, "text": "end-this-session"})).await;+ host.wait_for(&bot, Duration::from_secs(30), |e| {+ e["kind"] == "notice" && e["data"]["text"].as_str().is_some_and(|t| t.contains("session has ended"))+ })+ .await;+ // Left open, the ended session would refuse this one too.+ host.call("send", json!({"botId": bot, "text": "still there?"})).await;+ host.wait_for(&bot, Duration::from_secs(30), |e| e["kind"] == "agent" && e["data"]["text"] == "still here").await;+}