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 a routine's agent when its run is done
leepokaie900c92b5221
diff --git a/docs/architecture/conversation-runtime.md b/docs/architecture/conversation-runtime.mdindex 5e339525..d040ed1d 100644--- a/docs/architecture/conversation-runtime.md+++ b/docs/architecture/conversation-runtime.md@@ -1,7 +1,7 @@# Conversation runtime- **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`; a routine run's session as soon as the run ends), 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 frees a closed session's thread and its MCP servers within about a minute, but codex-acp never closes the thread it titles each new session in, so that thread's MCP servers from the user's Codex config stay until the agent stops ([codex-acp#628](https://github.com/agentclientprotocol/codex-acp/issues/628)). 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.+- **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`; a routine run's session as soon as the run ends), and once all of them are idle the agent stops with its process group, as it does right after a routine run when no other session is open; 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 frees a closed session's thread and its MCP servers within about a minute, but codex-acp never closes the thread it titles each new session in, so that thread's MCP servers from the user's Codex config stay until the agent stops ([codex-acp#628](https://github.com/agentclientprotocol/codex-acp/issues/628)). 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).diff --git a/docs/features/routines.md b/docs/features/routines.mdindex 643e8f54..de67350f 100644--- a/docs/features/routines.md+++ b/docs/features/routines.md@@ -72,10 +72,11 @@ next deadlines and run records are saved in SQLite (`routines.v1`). Due triggersare coalesced into one run per routine; only one routine per bot is dispatched at atime. Bot actors serialize routine work with ordinary conversation work.-Each run gets its own conversation thread and agent session. The session closes-when the run ends (agents that can close and resume sessions), so a frequent-schedule doesn't keep a set of MCP servers alive per run; opening the run's-thread resumes it. Final results appear+Each run gets its own conversation thread and agent session. When the run ends,+the agent stops if nothing else has a session open (it ran just for the run);+otherwise only the run's session closes (agents that can close sessions). Either+way a frequent schedule doesn't keep a set of MCP servers alive per run, and+opening the run's thread resumes its session (agents that can resume sessions). Final results appearin the main conversation and use normal encrypted push delivery. Returning `(pass)`or no text completes silently. A test run can run a paused routine. Pausing ordeleting cancels pending runs; work already running can finish. Deleting a botdiff --git a/host/src/agent/bot/lifecycle.rs b/host/src/agent/bot/lifecycle.rsindex 797d28e8..dd511cef 100644--- a/host/src/agent/bot/lifecycle.rs+++ b/host/src/agent/bot/lifecycle.rs@@ -1,5 +1,6 @@//! Idle agents give their resources back. A session unused for [`IDLE`] is closed (a routine run's-//! as soon as the run ends); once every session is idle, the agent stops with its process group.+//! as soon as the run ends); once every session is idle, or a routine run ends with none other open,+//! the agent stops with its process group.//! The next message starts the agent again and loads the session, so the conversation carries on.//! Agents that can't load a session keep everything: stopping them would lose the conversation.@@ -86,9 +87,28 @@ impl Actor {&& self.cancel_deadline.is_none()}- /// Closes a session the agent can load again when it's next needed: one a routine run is done with, so a bot on- /// a short schedule doesn't hold a set of MCP servers per run until [`IDLE`], or one a turn failed in (see- /// `acp::may_end_session`), so the next turn loads it afresh instead of finding it dead.+ /// A routine run's session is spent once the run is. When it was the only session open and nothing waits, the+ /// agent ran just for the run and stops with it, with everything it started; otherwise the session alone closes,+ /// so a bot on a short schedule doesn't hold a set of MCP servers per run until [`IDLE`]. Opening the run's thread+ /// loads it again.+ pub(super) async fn release_spent(&mut self, sid: &str) {+ let Some(conn) = &self.conn else { return };+ if !conn.sessions.load {+ return;+ }+ let alone = conn.loaded.keys().all(|s| s == sid) && self.queue.is_empty();+ if alone && !background_work(conn.acp.pid()).await {+ tracing::info!(bot = %self.cfg.id, "stopping the agent after its routine run");+ if let Some(conn) = self.conn.take() {+ conn.acp.kill().await;+ }+ } else {+ self.close_reloadable(sid).await;+ }+ }++ /// Closes a session the agent can load again when it's next needed, like one a turn failed in (see+ /// `acp::may_end_session`): the next turn loads it afresh instead of finding it dead.pub(super) async fn close_reloadable(&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;diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex 88901385..fe6c3653 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -379,11 +379,13 @@ 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 spent = self.active_routine.is_some() || done.as_ref().is_err_and(acp::may_end_session);- let reload = self.turn_session.clone().filter(|_| spent);+ let (session, routine) = (self.turn_session.clone(), self.active_routine.is_some());+ let failed = done.as_ref().is_err_and(acp::may_end_session);self.finish_turn(&done);- if let Some(sid) = reload {- self.close_reloadable(&sid).await;+ match session {+ Some(sid) if routine => self.release_spent(&sid).await,+ Some(sid) if failed => self.close_reloadable(&sid).await,+ _ => {}}self.next_in_queue(&done_tx).await;}diff --git a/host/tests/fixtures/routine_agent.py b/host/tests/fixtures/routine_agent.pyindex dd7b0003..692959a8 100644--- a/host/tests/fixtures/routine_agent.py+++ b/host/tests/fixtures/routine_agent.py@@ -1,5 +1,6 @@"""Persistent deterministic ACP sessions for routine restart and queue tests."""import json+import osimport pathlibimport reimport subprocess@@ -125,6 +126,7 @@ for line in sys.stdin:request = json.loads(line)method = request.get("method")if method == "initialize":+ log("initialize", "", str(os.getpid()))capabilities = {"loadSession": not pathlib.Path("no-load").exists(), "sessionCapabilities": {"close": {}}}send({"id": request["id"], "result": {"agentCapabilities": capabilities}})elif method == "session/new":diff --git a/host/tests/routines_e2e.rs b/host/tests/routines_e2e.rsindex 83c04995..ec328e77 100644--- a/host/tests/routines_e2e.rs+++ b/host/tests/routines_e2e.rs@@ -287,6 +287,21 @@ async fn crash_resumes_the_same_session_and_publishes_one_result() {);}+#[tokio::test]+async fn an_agent_started_for_a_run_stops_when_the_run_ends() {+ let host = Host::start().await;+ let bot = host.stable_bot("only-runs").await;+ let id = host.save(&bot, "one-off", "ONE_OFF", json!([{"type":"webhook"}]), 30).await;+ host.call("runRoutine", json!({"botId":bot,"id":id})).await;+ host.wait_event("only-runs", "finished", "ONE_OFF").await;+ host.send(&bot, "LATER").await;+ host.wait_event("only-runs", "finished", "LATER").await;+ let events = host.agent_events("only-runs");+ // The message started the agent again: the run's agent stopped with the run instead of closing its session.+ assert_eq!(events.iter().filter(|e| e["event"] == "initialize").count(), 2);+ assert!(!events.iter().any(|e| e["event"] == "closed"));+}+#[tokio::test]async fn a_finished_run_closes_its_session_and_the_main_one_stays() {let host = Host::start().await;