Skip to content

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.

fix(host): let bots on a schedule go idle between runs

leepokaic014f70f5f44
diff --git a/docs/architecture/conversation-runtime.md b/docs/architecture/conversation-runtime.md
index dd679ec0..5e339525 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`), 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.
+- **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.
- **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.md
index a93f8763..643e8f54 100644
--- a/docs/features/routines.md
+++ b/docs/features/routines.md
@@ -72,7 +72,10 @@ next deadlines and run records are saved in SQLite (`routines.v1`). Due triggers
are coalesced into one run per routine; only one routine per bot is dispatched at a
time. Bot actors serialize routine work with ordinary conversation work.
-Each run gets its own conversation thread and agent session. Final results appear
+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
in 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 or
deleting cancels pending runs; work already running can finish. Deleting a bot
diff --git a/host/src/agent/bot/lifecycle.rs b/host/src/agent/bot/lifecycle.rs
index 32888eba..797d28e8 100644
--- a/host/src/agent/bot/lifecycle.rs
+++ b/host/src/agent/bot/lifecycle.rs
@@ -1,7 +1,7 @@
-//! Idle agents give their resources back. A session unused for [`IDLE`] is closed; once every
-//! session is idle, 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.
+//! 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.
+//! 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.
use super::Actor;
use serde_json::json;
@@ -86,9 +86,10 @@ 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) {
+ /// 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.
+ 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;
}
@@ -102,6 +103,8 @@ impl Actor {
tracing::info!(bot = %self.cfg.id, session = sid, "closed a session");
conn.loaded.remove(sid);
conn.fast_options.remove(sid);
+ conn.usage.remove(sid);
+ self.applied_system.remove(sid);
}
Err(error) => {
tracing::warn!(bot = %self.cfg.id, session = sid, error = format!("{error:#}"), "couldn't close a session");
diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rs
index a06efc33..88901385 100644
--- a/host/src/agent/bot/mod.rs
+++ b/host/src/agent/bot/mod.rs
@@ -379,10 +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));
+ 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);
self.finish_turn(&done);
- if let Some(sid) = failed_session {
- self.close_failed_session(&sid).await;
+ if let Some(sid) = reload {
+ 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.py
index 08dd919c..dd7b0003 100644
--- a/host/tests/fixtures/routine_agent.py
+++ b/host/tests/fixtures/routine_agent.py
@@ -125,13 +125,15 @@ for line in sys.stdin:
request = json.loads(line)
method = request.get("method")
if method == "initialize":
- send({"id": request["id"], "result": {"agentCapabilities": {"loadSession": not pathlib.Path("no-load").exists()}}})
+ capabilities = {"loadSession": not pathlib.Path("no-load").exists(), "sessionCapabilities": {"close": {}}}
+ send({"id": request["id"], "result": {"agentCapabilities": capabilities}})
elif method == "session/new":
servers = request["params"]["mcpServers"]
send({"id": request["id"], "result": {"sessionId": str(uuid.uuid4())}})
elif method == "session/load":
sid = request["params"]["sessionId"]
if sid in sessions:
+ log("loaded", sid, "")
send({"id": request["id"], "result": {"sessionId": sid}})
else:
send({"id": request["id"], "error": {"code": -32000, "message": "unknown session"}})
@@ -140,5 +142,8 @@ for line in sys.stdin:
threading.Thread(target=prompt, args=(request, cancel), daemon=True).start()
elif method == "session/cancel":
cancel.set()
+ elif method == "session/close":
+ log("closed", request["params"]["sessionId"], "")
+ send({"id": request["id"], "result": {}})
elif "id" in request:
send({"id": request["id"], "result": {}})
diff --git a/host/tests/routines_e2e.rs b/host/tests/routines_e2e.rs
index f5474f6e..83c04995 100644
--- a/host/tests/routines_e2e.rs
+++ b/host/tests/routines_e2e.rs
@@ -287,6 +287,29 @@ async fn crash_resumes_the_same_session_and_publishes_one_result() {
);
}
+#[tokio::test]
+async fn a_finished_run_closes_its_session_and_the_main_one_stays() {
+ let host = Host::start().await;
+ let bot = host.stable_bot("spent").await;
+ host.send(&bot, "MAIN_CHAT").await;
+ let main = host.wait_event("spent", "finished", "MAIN_CHAT").await;
+ let id = host.save(&bot, "one-off", "ONE_OFF", json!([{"type":"webhook"}]), 30).await;
+ host.call("runRoutine", json!({"botId":bot,"id":id})).await;
+ let run = host.wait_event("spent", "finished", "ONE_OFF").await;
+ let closed = host.wait_event("spent", "closed", "").await;
+ assert_eq!(closed["session"], run["session"]);
+ assert_ne!(run["session"], main["session"]);
+ host.send(&bot, "MAIN_AGAIN").await;
+ assert_eq!(host.wait_event("spent", "finished", "MAIN_AGAIN").await["session"], main["session"]);
+ assert_eq!(host.agent_events("spent").iter().filter(|e| e["event"] == "closed").count(), 1);
+ // The run's thread carries on in the run's session.
+ let run_id = host.call("routines", json!({"botId":bot})).await["runs"][0]["id"].as_str().unwrap().to_owned();
+ let thread = format!("routine-{run_id}");
+ host.call("send", json!({"botId":bot,"text":"IN_THREAD","threadId":thread,"clientNonce":"thread"})).await;
+ assert_eq!(host.wait_event("spent", "finished", "IN_THREAD").await["session"], run["session"]);
+ assert_eq!(host.wait_event("spent", "loaded", "").await["session"], run["session"]);
+}
+
#[tokio::test]
async fn busy_bot_keeps_work_pending_and_honors_pause_delete_and_edit_across_restart() {
let mut host = Host::start().await;