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): give back idle agents' helpers on Windows and DeepSeek
leepokaie54f1ae797ec
diff --git a/docs/architecture/conversation-runtime.md b/docs/architecture/conversation-runtime.mdindex 389122a8..43ffa55a 100644--- a/docs/architecture/conversation-runtime.md+++ b/docs/architecture/conversation-runtime.md@@ -1,10 +1,10 @@# 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*. The chat never says when the session underneath changes (New session, an agent, model or folder change, a failed resume); only a rollover's handoff card mentions a fresh conversation ([context and memory](../features/context-and-memory.md)), and one line says when another agent takes over or the bot's own comes back.+- **Chat ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is reopened with `session/load`, or `session/resume` on an agent without it (DeepSeek Harness), or replaced by *New session*. The chat never says when the session underneath changes (New session, an agent, model or folder change, a failed resume); only a rollover's handoff card mentions a fresh conversation ([context and memory](../features/context-and-memory.md)), and one line says when another agent takes over or the bot's own comes back.- **Agent fallbacks**: when the bot's agent can't answer (out of usage, rate limited, signed out, won't start), the next agent in its list carries the same turn on, told what the last one did; each agent keeps its own session, parked while another answers, and agents rest computer-wide until they recover: [docs/features/agent-fallback.md](../features/agent-fallback.md).-- **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.+- **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 reopens the session (`agent/bot/lifecycle.rs`). Nothing is released mid-turn or while a queue, approval or request waits. Agents that can't reopen 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 keeps a closed session's MCP servers until the agent stops, and codex-acp never closes the thread it titles each new session in ([codex-acp#628](https://github.com/agentclientprotocol/codex-acp/issues/628)), so on Codex only the agent stopping gives them back. Windows has no sessions to tell a dev server from an MCP server, so there the agent's job is checked instead: anything that isn't the agent or Codync's MCP servers holds it, which also keeps an agent with an MCP server from the user's own config or a shell it keeps open, and one with no MCP server left, whose own last process can't be told from a dev server (`agent/bot/background_work.rs`).- **Group chats and replies** are host features every client drives through the same methods (`send` with `replyTo`, `createBot {kind: group}`); clients never route, parse mentions or build quotes themselves. A group is a roster row whose members answer in their own sessions (Grok Bot's room turns); a reply stays in its chat and session, its quote read before its text: [docs/features/groups-and-replies.md](../features/groups-and-replies.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`).+- **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 reopen sessions: Claude's adapter otherwise answers every later prompt on it with "The Claude Agent session has ended". The next message reopens it and the conversation carries on (`acp::may_end_session`).- **Lead bot**: the host makes the first one per computer (`chat/lead.rs`), and the user may pick another (`setLead`) or delete it; on top of every roster, never hidden; its instructions ask for initiative, the *Check in* routine made with the first runs twice a day, and it opens a call with a turn of its own (`Cmd::Prompt`, no user message): [docs/features/lead-bot.md](../features/lead-bot.md).- Bot collaboration: built-in `team` MCP (`chat/team.rs`) lists visible bots and sends one a request through its actor queue (`message_bot`); nothing waits, and the reply comes back to the sender as a turn of its own in its main chat. Requests and replies are separate turns, bounded by the chain's hop count; 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 or steered into the running one, interrupted turns resumed: [docs/features/context-and-memory.md](../features/context-and-memory.md).diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.mdindex 41155a43..9bf16bb1 100644--- a/docs/features/context-and-memory.md+++ b/docs/features/context-and-memory.md@@ -197,7 +197,7 @@ Claude Code's own memory; the rules live in the `codync-mem` crate, and `chat/me- Bot-to-bot requests and the replies to them occupy separate turns in the same queue (replies waiting together are one turn); user messages are only folded together up to the next request or reply. Neither feeds dreaming. See [bot collaboration](bot-collaboration.md).- A request turn (the recipient's) doesn't set the restart marker: its pending notices become interrupted errors instead of automatically replaying work. A reply turn is the sender's own chat turn and sets it, so it resumes like a user turn.- Stop sends `session/cancel`; an agent still running 15 seconds later is stopped (it resumes its session on- the next turn). `session/new`, `session/load` and `session/fork` get three minutes before the agent is+ the next turn). `session/new`, `session/load`, `session/resume` and `session/fork` get three minutes before the agent isstopped. Connector or computer changes restart an agent that can resume sessions before its next turn; onethat can't keeps its session, and its next new session gets them.- `turn.inflight.<bot>` records when the running turn in the bot's chat started. If the host stops mid-turn (update, crash, restart), the nextdiff --git a/docs/features/routines.md b/docs/features/routines.mdindex 5651cd47..4897294e 100644--- a/docs/features/routines.md+++ b/docs/features/routines.md@@ -88,10 +88,11 @@ its reply, which is the result, all in the turn the notice takes when the run bemessage sent meanwhile gets the next one). It runs in a fresh agent session of its own(`routines::session_slot`, kept in kv `lane.session.<bot>@<bot>/routine-<run>` so arestart can resume it, and forgotten once the run's outcome is saved). When the run ends, the agent stops if nothing else has a-session open (it ran just for the run; not on Windows, see-[agent processes](../architecture/conversation-runtime.md)); otherwise only the run's+session open (it ran just for the run) and nothing it started holds it, see+[agent processes](../architecture/conversation-runtime.md); otherwise only the run'ssession closes (agents that can close sessions). Either way a frequent schedule-doesn't keep a set of MCP servers alive per run. A successful run alerts with its+doesn't keep a set of MCP servers alive per run, except on Codex while another session+is open: it keeps a closed session's until the agent stops. A successful run alerts with itsreply through normal encrypted push delivery; a failed or interrupted one leaves a"Routine could not finish" notice. Returning `(pass)` or no text completes silently.Replying to a run's result goes to the bot's main session, with the result quoted. A test run can run a paused routine. Pausing or@@ -135,7 +136,7 @@ host checks the run's turn for a tool call whose ACP kind isn't `read`, `search`Each run has a timeout (default one hour, configurable from 1 to 86400 seconds).A hung agent is terminated so subsequent work can proceed. When the time limit cuts-session setup short, an agent that can load sessions is stopped too, so a session it was+session setup short, an agent that can reopen sessions is stopped too, so a session it wasstill opening can't stay open unknown to the host; one that can't keeps running with thesessions it has. A run's outcome issaved before it is reported, and a failure notice has a stable transcript ID, so adiff --git a/docs/reference/acp-adapter-workarounds.md b/docs/reference/acp-adapter-workarounds.mdindex 34c11cef..a40cf261 100644--- a/docs/reference/acp-adapter-workarounds.md+++ b/docs/reference/acp-adapter-workarounds.md@@ -40,6 +40,7 @@ qwen-code 0.26.5.| `/compact` ignores its instructions | `host/src/agent/bot/session.rs`: `CODEX_CONFIG={"compact_prompt": KEEP}` | none | `/compact <text>` uses the text || Sets no tool timeout for Codync's servers, so Codex's 300 s default drops a call without telling the server | `host/src/chat/manage.rs`: `APPROVAL_TIMEOUT` is 270 s | none | A per-server timeout, or Codex sends `notifications/cancelled` || Sends 429s and overloads as reply text, not as errors | **Not patched**: only `usageLimitExceeded` moves a Codex bot to its fallback ([agent fallbacks](../features/agent-fallback.md)) | [#647](https://github.com/agentclientprotocol/codex-acp/issues/647) | When fixed, map the new categories in `host/src/agent/fallback/reason.rs` |+| Keeps a closed session's MCP servers until the agent stops | Nothing beyond the idle stop in `host/src/agent/bot/lifecycle.rs` ([conversation runtime](../architecture/conversation-runtime.md)) | none | Upstream fix: nothing to delete || Never closes the thread it titles each new session in, so that thread's MCP servers stay up until the agent stops | Nothing beyond the idle stop in `host/src/agent/bot/lifecycle.rs` ([conversation runtime](../architecture/conversation-runtime.md)) | [#628](https://github.com/agentclientprotocol/codex-acp/issues/628) | Upstream fix: nothing to delete || The Codex CLI deletes the current credentials as soon as a new sign-in starts | `host/src/agent/term.rs`: no Login step while signed in | none | The CLI keeps them until the new login succeeds |@@ -90,7 +91,7 @@ Not one adapter's bug: the protocol leaves these open, and the host covers them- No structured MCP server and tool name on a tool call: `host/src/agent/bot/tool_entry.rs` parses titles (`mcp__x__y`, `mcp.x.y`).- Every adapter names its error category differently (`errorKind`, `category`, `codexErrorInfo`): `host/src/agent/acp.rs`.-- Agents that ignore `session/cancel` are killed after 15 s; a hung `session/new` or `session/load` after 3 min;+- Agents that ignore `session/cancel` are killed after 15 s; a hung `session/new`, `session/load` or `session/resume` after 3 min;an old CLI that hangs on `initialize` gets 20 s when another way to start it is left (`host/src/agent/bot/mod.rs`,`host/src/agent/bot/session.rs`).- Agents that send no `compaction_update`: a drop in context use by more than half stands in for onediff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rsindex 25de8969..e2654ea4 100644--- a/host/src/agent/acp.rs+++ b/host/src/agent/acp.rs@@ -177,7 +177,8 @@ pub struct Acp {pending: Pending,/// Owns the agent's whole process tree: dropping it kills what the agent started.child: Arc<tokio::sync::Mutex<Process>>,- /// The process (and, on Unix, process group) leader.+ /// The process and process group leader.+ #[cfg(unix)]pid: Option<u32>,}@@ -206,6 +207,7 @@ impl Acp {let stdin = child.stdin.take().expect("stdin is piped");let stdout = child.stdout.take().expect("stdout is piped");let stderr = child.stderr.take().expect("stderr is piped");+ #[cfg(unix)]let pid = child.id();let child = Arc::new(tokio::sync::Mutex::new(Process::new(child)?));Process::monitor(&child);@@ -273,16 +275,25 @@ impl Acp {next_id: AtomicI64::new(1),pending,child,+ #[cfg(unix)]pid,});note_started(&acp);Ok((acp, rx))}+ #[cfg(unix)]pub fn pid(&self) -> Option<u32> {self.pid}+ /// Everything still running in the agent's job.+ #[cfg(windows)]+ pub(crate) async fn job_processes(&self) -> Result<Vec<super::process::JobProcess>> {+ let members = self.child.lock().await.job_members()?;+ tokio::task::spawn_blocking(move || super::process_windows::named(&members)).await?+ }+async fn write(&self, msg: Value) -> Result<()> {let mut line = serde_json::to_vec(&msg)?;line.push(b'\n');diff --git a/host/src/agent/acp/tests.rs b/host/src/agent/acp/tests.rsindex 9f86467d..93b1320f 100644--- a/host/src/agent/acp/tests.rs+++ b/host/src/agent/acp/tests.rs@@ -113,6 +113,23 @@ async fn stopping_an_agent_closes_its_descendants_pipes() {assert!(matches!(closed, Some(Incoming::Closed { .. })));}+#[cfg(windows)]+#[tokio::test]+async fn an_agents_job_lists_what_it_started() {+ let (acp, _rx) = Acp::spawn("ping -n 30 127.0.0.1", ".", &[]).unwrap();+ let deadline = tokio::time::Instant::now() + Duration::from_secs(15);+ loop {+ let listed = acp.job_processes().await.unwrap();+ if let Some(ping) = listed.iter().find(|p| p.name.eq_ignore_ascii_case("ping.exe")) {+ let shell = listed.iter().find(|p| p.pid == ping.parent).expect("what started ping is in the job");+ assert!(shell.name.eq_ignore_ascii_case("cmd.exe"), "{}", shell.name);+ return;+ }+ assert!(tokio::time::Instant::now() < deadline, "ping never showed up in the job");+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+}+#[cfg(unix)]#[tokio::test]async fn a_stopped_agent_finishes_by_itself_first() {diff --git a/host/src/agent/bot/background_work.rs b/host/src/agent/bot/background_work.rsnew file mode 100644index 00000000..f7242559--- /dev/null+++ b/host/src/agent/bot/background_work.rs@@ -0,0 +1,196 @@+//! Whether an agent still runs something that stopping it would end, which keeps it running when it's idle.++use crate::agent::acp::Acp;+#[cfg(any(windows, test))]+use crate::agent::process::JobProcess;+use std::collections::HashMap;++/// Whether something the agent started runs detached, in a session of its own, like a dev server+/// from its shell tool. Stopping the agent would orphan it and lose track of it, so the agent+/// stays. MCP servers stay in the agent's session and don't count, even in a process group of+/// their own (Codex starts each one in its own group). Unsure counts as busy.+// ponytail: a dev server keeps its agent (and memory) indefinitely; add a cap if that matters.+#[cfg(unix)]+pub(super) async fn background_work(acp: &Acp) -> bool {+ detached_work(acp.pid()).await+}++#[cfg(unix)]+async fn detached_work(leader: Option<u32>) -> bool {+ let Some(leader) = leader else { return true };+ let listed = tokio::process::Command::new("ps").args(["-A", "-o", "pid=,ppid="]).output().await;+ let Ok(listed) = listed.inspect_err(|e| tracing::warn!(error = format!("{e:#}"), "couldn't list processes")) else {+ return true;+ };+ if !listed.status.success() {+ return true;+ }+ let processes: Vec<(u32, u32)> = String::from_utf8_lossy(&listed.stdout)+ .lines()+ .filter_map(|line| {+ let mut fields = line.split_whitespace().map(str::parse);+ Some((fields.next()?.ok()?, fields.next()?.ok()?))+ })+ .collect();+ detached_descendant(&processes, leader, session)+}++/// `pid`'s session, or `None` once it's gone.+#[cfg(unix)]+fn session(pid: u32) -> Option<i32> {+ let pid = libc::pid_t::try_from(pid).ok()?;+ // SAFETY: getsid only reads the process table.+ let sid = unsafe { libc::getsid(pid) };+ (sid >= 0).then_some(sid)+}++/// Windows has no sessions to tell a dev server from an MCP server, and stopping the agent ends everything in its+/// job there, so the job's processes are judged by what they are ([`runs_something_else`]). Unsure counts as busy.+#[cfg(windows)]+pub(super) async fn background_work(acp: &Acp) -> bool {+ let Ok(exe) = std::env::current_exe() else { return true };+ let Some(own) = exe.file_name().and_then(|n| n.to_str()) else { return true };+ match acp.job_processes().await {+ Ok(processes) => runs_something_else(&processes, own),+ Err(error) => {+ tracing::warn!(error = format!("{error:#}"), "couldn't list the agent's processes");+ true+ }+ }+}++/// The console window Windows gives a process started without one: no work of its own.+#[cfg(any(windows, test))]+const CONSOLE_HOST: &str = "conhost.exe";++/// Whether an agent's job holds a process that isn't the agent or Codync's MCP servers (`own`: the host's own+/// program name, and whatever those servers start). The agent is what leads to them, so anything else that starts+/// nothing further counts: a dev server from its shell tool, but also an MCP server from the user's own config, a+/// shell the agent keeps open, and the agent's own last process once its servers have all gone.+// ponytail: those last three keep their agent as before; tell them from a dev server by the agent's config, or by+// remembering which process started the servers, if it matters.+#[cfg(any(windows, test))]+fn runs_something_else(processes: &[JobProcess], own: &str) -> bool {+ let by_pid: HashMap<u32, &JobProcess> = processes.iter().map(|p| (p.pid, p)).collect();+ let is_console = |p: &JobProcess| p.name.eq_ignore_ascii_case(CONSOLE_HOST);+ // Every step stays inside `processes`, so `take` reaches every ancestor and ends pid links that loop (reused pids).+ let ours = |p: &JobProcess| {+ std::iter::successors(Some(p), |c| by_pid.get(&c.parent).copied())+ .take(processes.len())+ .any(|c| c.name.eq_ignore_ascii_case(own))+ };+ let starts_nothing =+ |p: &JobProcess| !processes.iter().any(|c| c.parent == p.pid && c.pid != p.pid && !is_console(c));+ processes.iter().filter(|p| !is_console(p) && !ours(p)).any(starts_nothing)+}++/// `processes`: (pid, parent pid) rows; `session` finds a live process's session.+#[cfg(any(unix, test))]+fn detached_descendant(processes: &[(u32, u32)], leader: u32, session: impl Fn(u32) -> Option<i32>) -> bool {+ let Some(own) = session(leader) else { return true };+ let mut children: HashMap<u32, Vec<u32>> = HashMap::new();+ for &(pid, parent) in processes {+ children.entry(parent).or_default().push(pid);+ }+ let mut stack = vec![leader];+ while let Some(parent) = stack.pop() {+ for &pid in children.get(&parent).into_iter().flatten() {+ // One that exited since the listing holds nothing.+ if session(pid).is_some_and(|sid| sid != own) {+ return true;+ }+ stack.push(pid);+ }+ }+ false+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_work_in_another_session_holds_the_agent() {+ // 10 agent -> 11 codex -> 12 MCP server in a group of its own; all in the host's session 5.+ let sessions: HashMap<u32, i32> = [(10, 5), (11, 5), (12, 5), (20, 20), (21, 20), (30, 30)].into();+ let session = |pid| sessions.get(&pid).copied();+ let agent = [(10, 1), (11, 10), (12, 11), (40, 1)];+ assert!(!detached_descendant(&agent, 10, session));+ // The shell tool runs `npm run dev` in a session of its own.+ let mut busy = agent.to_vec();+ busy.extend([(20, 11), (21, 20)]);+ assert!(detached_descendant(&busy, 10, session));+ // Someone else's process in another session isn't the agent's.+ assert!(!detached_descendant(&[(10, 1), (30, 1)], 10, session));+ // A child that exited since the listing holds nothing; an agent that can't be looked up is unsure.+ assert!(!detached_descendant(&[(10, 1), (50, 10)], 10, session));+ assert!(detached_descendant(&agent, 99, session));+ }++ #[test]+ fn on_windows_only_what_isnt_the_agent_or_codyncs_servers_holds_the_agent() {+ let own = "codync-host.exe";+ let process = |pid, parent, name: &str| JobProcess { pid, parent, name: name.to_owned() };+ // cmd -> node (adapter) -> codex (engine) -> Codync's MCP servers, with a console window.+ let agent = vec![+ process(1, 900, "cmd.exe"),+ process(2, 1, "conhost.exe"),+ process(3, 1, "node.exe"),+ process(4, 3, "codex.exe"),+ process(5, 4, "CODYNC-HOST.EXE"),+ process(6, 4, "codync-host.exe"),+ ];+ assert!(!runs_something_else(&agent, own));+ assert!(!runs_something_else(&[], own), "nothing left in the job");++ // A dev server from the shell tool, alive or with the shell that started it gone.+ let mut server = agent.clone();+ server.extend([process(7, 4, "powershell.exe"), process(8, 7, "node.exe")]);+ assert!(runs_something_else(&server, own));+ let mut orphan = agent.clone();+ orphan.push(process(8, 777, "node.exe"));+ assert!(runs_something_else(&orphan, own));+ // A console window of its own doesn't hide it.+ let mut windowed = agent.clone();+ windowed.extend([process(8, 4, "node.exe"), process(9, 8, "conhost.exe")]);+ assert!(runs_something_else(&windowed, own));++ // What Codync's own servers start is theirs, like a connector they launch.+ let mut connector = agent.clone();+ connector.extend([process(10, 5, "cmd.exe"), process(11, 10, "node.exe")]);+ assert!(!runs_something_else(&connector, own));++ // Pid links that loop (a reused pid) end the walk, and an agent with no server left is unsure.+ assert!(runs_something_else(&[process(1, 2, "a.exe"), process(2, 1, "b.exe"), process(3, 1, "c.exe")], own));+ assert!(runs_something_else(&[process(1, 900, "cmd.exe"), process(3, 1, "node.exe")], own));+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn a_process_started_in_its_own_session_is_background_work() {+ use std::process::Stdio;+ let spawn = |script: &str| {+ let mut command = tokio::process::Command::new("perl");+ command.args(["-e", script]).stdin(Stdio::null()).kill_on_drop(true).process_group(0);+ command.spawn().expect("perl runs")+ };+ let plain = spawn("my $pid = fork; if (!$pid) { sleep 30; exit } sleep 30");+ // How Codex starts an MCP server.+ let grouped = spawn("my $pid = fork; if (!$pid) { setpgrp; sleep 30; exit } sleep 30");+ let detached = spawn("use POSIX (); my $pid = fork; if (!$pid) { POSIX::setsid(); sleep 30; exit } sleep 30");+ // The children exist once perl has forked them: wait for that instead of a fixed pause,+ // which a busy CI runner can outlast.+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);+ while !detached_work(detached.id()).await {+ assert!(tokio::time::Instant::now() < deadline, "the detached child never showed up");+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;+ }+ assert!(!detached_work(plain.id()).await);+ assert!(!detached_work(grouped.id()).await);+ for child in [plain, grouped, detached] {+ if let Some(pid) = child.id() {+ let _ = std::process::Command::new("/bin/kill").args(["-KILL", "--", &format!("-{pid}")]).status();+ }+ }+ }+}diff --git a/host/src/agent/bot/launch.rs b/host/src/agent/bot/launch.rsindex 7d460fab..21f26784 100644--- a/host/src/agent/bot/launch.rs+++ b/host/src/agent/bot/launch.rs@@ -46,7 +46,7 @@ pub(crate) fn launch_commands(cfg: &BotConfig) -> Result<Vec<Candidate>> {})}-/// Switches a session (`session/new` or `session/load` answered `res`) to the bot's+/// Switches a session (`session/new`, `session/load` or `session/resume` answered `res`) to the bot's/// chosen model, then sets that model's options (effort, fast…). Returns the answer holding/// the session's config options now: a model can change them.pub(crate) async fn select_model(acp: &Acp, res: &Value, sid: &str, cfg: &BotConfig) -> Result<Value> {@@ -152,8 +152,13 @@ pub(crate) async fn start_agent(command: &str, cwd: &str, env: &[(String, Stringreturn Err(acp::Failure::error(acp::FailureKind::Timeout, message));}};+ let reopen = if init["agentCapabilities"]["loadSession"].as_bool().unwrap_or(false) {+ Some("session/load")+ } else {+ init["agentCapabilities"]["sessionCapabilities"]["resume"].is_object().then_some("session/resume")+ };let sessions = SessionCaps {- load: init["agentCapabilities"]["loadSession"].as_bool().unwrap_or(false),+ reopen,close: init["agentCapabilities"]["sessionCapabilities"]["close"].is_object(),system_prompt: init["agentCapabilities"]["sessionCapabilities"]["systemPrompt"].is_object(),additional_directories: init["agentCapabilities"]["sessionCapabilities"]["additionalDirectories"].is_object(),diff --git a/host/src/agent/bot/lifecycle.rs b/host/src/agent/bot/lifecycle.rsindex 95b8cc3f..3d002d26 100644--- a/host/src/agent/bot/lifecycle.rs+++ b/host/src/agent/bot/lifecycle.rs@@ -1,15 +1,16 @@//! 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, 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.+//! The next message starts the agent again and reopens the session, so the conversation carries on.+//! Agents that can't reopen a session keep everything: stopping them would lose the conversation.use super::Actor;+use super::background_work::background_work;use serde_json::json;use std::collections::HashMap;use std::time::{Duration, Instant};-/// Coming back costs a relaunch plus `session/load` (seconds), so ordinary pauses in a chat+/// Coming back costs a relaunch plus reopening the session (seconds), so ordinary pauses in a chat/// stay warm.const IDLE: Duration = Duration::from_mins(30);/// How often an idle bot looks for something to give back.@@ -25,7 +26,7 @@ enum Release {}/// `used`: each live session's last use. Only an agent that can close sessions releases them one-/// by one; any agent that can load them is stopped once all are idle.+/// by one; any agent that can reopen them is stopped once all are idle.fn plan(used: &HashMap<String, Instant>, started: Instant, can_close: bool, now: Instant) -> Release {let mut idle: Vec<String> =used.iter().filter(|(_, at)| now.duration_since(**at) >= IDLE).map(|(sid, _)| sid.clone()).collect();@@ -52,12 +53,11 @@ impl Actor {return;}let Some(conn) = &self.conn else { return };- if !conn.sessions.load {+ if conn.sessions.reopen.is_none() {return;}let release = plan(&conn.loaded, conn.started, conn.sessions.close, Instant::now());- let leader = conn.acp.pid();- if release == Release::Nothing || background_work(leader).await {+ if release == Release::Nothing || background_work(&conn.acp).await {return;}match release {@@ -92,24 +92,28 @@ impl Actor {/// so a bot on a short schedule doesn't hold a set of MCP servers per run until [`IDLE`].pub(super) async fn release_spent(&mut self, sid: &str) {let Some(conn) = &self.conn else { return };- if !conn.sessions.load {+ if conn.sessions.reopen.is_none() {return;}let alone = conn.loaded.keys().all(|s| s == sid) && self.queue.is_empty();- if alone && !background_work(conn.acp.pid()).await {+ if alone && !background_work(&conn.acp).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;+ self.close_reopenable(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)) {+ /// Closes a session the agent can reopen when it's next needed, like one a turn failed in (see+ /// `acp::may_end_session`): the next turn reopens it instead of finding it dead.+ pub(super) async fn close_reopenable(&mut self, sid: &str) {+ if self+ .conn+ .as_ref()+ .is_some_and(|c| c.sessions.close && c.sessions.reopen.is_some() && c.loaded.contains_key(sid))+ {self.close_session(sid).await;}}@@ -137,69 +141,6 @@ impl Actor {}}-/// Whether something the agent started runs detached, in a session of its own, like a dev server-/// from its shell tool. Stopping the agent would orphan it and lose track of it, so the agent-/// stays. MCP servers stay in the agent's session and don't count, even in a process group of-/// their own (Codex starts each one in its own group). Unsure counts as busy.-// ponytail: a dev server keeps its agent (and memory) indefinitely; add a cap if that matters.-#[cfg(unix)]-async fn background_work(leader: Option<u32>) -> bool {- let Some(leader) = leader else { return true };- let listed = tokio::process::Command::new("ps").args(["-A", "-o", "pid=,ppid="]).output().await;- let Ok(listed) = listed.inspect_err(|e| tracing::warn!(error = format!("{e:#}"), "couldn't list processes")) else {- return true;- };- if !listed.status.success() {- return true;- }- let processes: Vec<(u32, u32)> = String::from_utf8_lossy(&listed.stdout)- .lines()- .filter_map(|line| {- let mut fields = line.split_whitespace().map(str::parse);- Some((fields.next()?.ok()?, fields.next()?.ok()?))- })- .collect();- detached_descendant(&processes, leader, session)-}--/// `pid`'s session, or `None` once it's gone.-#[cfg(unix)]-fn session(pid: u32) -> Option<i32> {- let pid = libc::pid_t::try_from(pid).ok()?;- // SAFETY: getsid only reads the process table.- let sid = unsafe { libc::getsid(pid) };- (sid >= 0).then_some(sid)-}--/// Windows has no process groups to tell a dev server from an MCP server, and stopping the agent-/// ends its whole process tree there, so its agents are never released.-#[cfg(windows)]-#[allow(clippy::unused_async)] // the Unix check's signature-async fn background_work(_leader: Option<u32>) -> bool {- true-}--/// `processes`: (pid, parent pid) rows; `session` finds a live process's session.-#[cfg(any(unix, test))]-fn detached_descendant(processes: &[(u32, u32)], leader: u32, session: impl Fn(u32) -> Option<i32>) -> bool {- let Some(own) = session(leader) else { return true };- let mut children: HashMap<u32, Vec<u32>> = HashMap::new();- for &(pid, parent) in processes {- children.entry(parent).or_default().push(pid);- }- let mut stack = vec![leader];- while let Some(parent) = stack.pop() {- for &pid in children.get(&parent).into_iter().flatten() {- // One that exited since the listing holds nothing.- if session(pid).is_some_and(|sid| sid != own) {- return true;- }- stack.push(pid);- }- }- false-}-#[cfg(test)]mod tests {use super::*;@@ -222,51 +163,4 @@ mod tests {assert_eq!(plan(&used(&[]), now, true, now), Release::Nothing);assert_eq!(plan(&used(&[("main", fresh)]), started, true, now), Release::Nothing);}-- #[test]- fn only_work_in_another_session_holds_the_agent() {- // 10 agent -> 11 codex -> 12 MCP server in a group of its own; all in the host's session 5.- let sessions: HashMap<u32, i32> = [(10, 5), (11, 5), (12, 5), (20, 20), (21, 20), (30, 30)].into();- let session = |pid| sessions.get(&pid).copied();- let agent = [(10, 1), (11, 10), (12, 11), (40, 1)];- assert!(!detached_descendant(&agent, 10, session));- // The shell tool runs `npm run dev` in a session of its own.- let mut busy = agent.to_vec();- busy.extend([(20, 11), (21, 20)]);- assert!(detached_descendant(&busy, 10, session));- // Someone else's process in another session isn't the agent's.- assert!(!detached_descendant(&[(10, 1), (30, 1)], 10, session));- // A child that exited since the listing holds nothing; an agent that can't be looked up is unsure.- assert!(!detached_descendant(&[(10, 1), (50, 10)], 10, session));- assert!(detached_descendant(&agent, 99, session));- }-- #[cfg(unix)]- #[tokio::test]- async fn a_process_started_in_its_own_session_is_background_work() {- use std::process::Stdio;- let spawn = |script: &str| {- let mut command = tokio::process::Command::new("perl");- command.args(["-e", script]).stdin(Stdio::null()).kill_on_drop(true).process_group(0);- command.spawn().expect("perl runs")- };- let plain = spawn("my $pid = fork; if (!$pid) { sleep 30; exit } sleep 30");- // How Codex starts an MCP server.- let grouped = spawn("my $pid = fork; if (!$pid) { setpgrp; sleep 30; exit } sleep 30");- let detached = spawn("use POSIX (); my $pid = fork; if (!$pid) { POSIX::setsid(); sleep 30; exit } sleep 30");- // The children exist once perl has forked them: wait for that instead of a fixed pause,- // which a busy CI runner can outlast.- let deadline = tokio::time::Instant::now() + Duration::from_secs(10);- while !background_work(detached.id()).await {- assert!(tokio::time::Instant::now() < deadline, "the detached child never showed up");- tokio::time::sleep(Duration::from_millis(50)).await;- }- assert!(!background_work(plain.id()).await);- assert!(!background_work(grouped.id()).await);- for child in [plain, grouped, detached] {- if let Some(pid) = child.id() {- let _ = std::process::Command::new("/bin/kill").args(["-KILL", "--", &format!("-{pid}")]).status();- }- }- }}diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex 7eff88a6..35d1962f 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -16,6 +16,7 @@//! written to the group's transcript; see `group`). A routine run talks in its chat//! from a session of its own (see `session`).+mod background_work;mod cmd;mod codex_names;mod compaction;@@ -145,8 +146,9 @@ pub fn spawn(hub: Arc<Hub>, base: BotConfig) -> BotHandle {#[allow(clippy::struct_excessive_bools)]#[derive(Clone, Copy)]struct SessionCaps {- /// `session/load`: resume a session after a restart.- load: bool,+ /// The request that opens a session the agent isn't holding, when it can: `session/load`, whose replay is thrown+ /// away as the host keeps the chat itself, or `session/resume` on an agent without it.+ reopen: Option<&'static str>,/// `session/close`: an idle session can be released while the agent keeps running.close: bool,/// ACP `systemPrompt`: instructions on `session/new` and `load` that the agent keeps at system level.@@ -366,7 +368,7 @@ impl Actor {self.finish_turn(&done);match session {Some(sid) if routine => self.release_spent(&sid).await,- Some(sid) if failed => self.close_reloadable(&sid).await,+ Some(sid) if failed => self.close_reopenable(&sid).await,_ => {}}self.next_in_queue(done_tx).await;diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex 44c709d9..64717539 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -79,7 +79,7 @@ impl Actor {// The harness reads its own memory's switch when it starts: an agent that can resume its session// restarts into it, one that can't starts afresh.let memory_changed = own_memory::kept(&cfg) != own_memory::kept(&self.cfg);- let resumes = self.conn.as_ref().is_none_or(|c| c.sessions.load);+ let resumes = self.conn.as_ref().is_none_or(|c| c.sessions.reopen.is_some());let restart = cfg.backend != self.cfg.backend|| cfg.command != self.cfg.command|| cfg.cwd != self.cfg.cwddiff --git a/host/src/agent/bot/session.rs b/host/src/agent/bot/session.rsindex 1dbfac08..cd7e5e45 100644--- a/host/src/agent/bot/session.rs+++ b/host/src/agent/bot/session.rs@@ -1,4 +1,4 @@-//! The bot's ACP sessions: starting its agent, new/load, routine runs' sessions.+//! The bot's ACP sessions: starting its agent, new/reopen, routine runs' sessions.use super::fast_mode::Listing;use super::launch::{claude_meta, launch_commands, select_model, start_agent, system_prompt};@@ -161,7 +161,7 @@ impl Actor {}// An agent that can't resume keeps its session; its next new session gets the new tools.if std::mem::take(&mut self.tools_changed)- && self.conn.as_ref().is_some_and(|c| c.sessions.load)+ && self.conn.as_ref().is_some_and(|c| c.sessions.reopen.is_some())&& let Some(c) = self.conn.take(){c.acp.kill().await;@@ -229,11 +229,11 @@ impl Actor {self.turn_session = Some(sid);return Ok(());}- if !conn.sessions.load {+ let Some(reopen) = conn.sessions.reopen else {tracing::info!(bot = %self.cfg.id, "the agent can't resume sessions; starting a fresh one");self.set_session(slot, None);return Box::pin(self.ensure_session(slot)).await;- }+ };self.hub.set_runtime(&self.cfg.id, |r| r.activity = "Resuming session…".into());let mut params = self.session_params(&servers, Some(&sid));if let Some(s) = &snapshot {@@ -242,7 +242,7 @@ impl Actor {if instructions == Instructions::SystemPrompt {params["systemPrompt"] = system_prompt(&self.snapshot(&sid).await?.system);}- let res = self.session_request("session/load", params).await;+ let res = self.session_request(reopen, params).await;let Some(conn) = self.conn.as_mut() else { return res.map(drop) };// The agent replays history as session/update before answering; drop it.while let Ok(inc) = conn.rx.try_recv() {@@ -255,7 +255,19 @@ impl Actor {// A resumed session can come back on the agent's last-used model (Cursor// keeps one for all its sessions), so the bot's own is set again.let res = if res.get("configOptions").is_some() || res.get("models").is_some() {- select_model(&conn.acp, &res, &sid, &self.cfg).await?+ match select_model(&conn.acp, &res, &sid, &self.cfg).await {+ Ok(selected) => selected,+ Err(error) => {+ // The agent now holds a session the host doesn't track, and `session/resume` refuses+ // one it holds. Stopped, it takes the session again on the next message.+ if reopen == "session/resume"+ && let Some(c) = self.conn.take()+ {+ c.acp.kill().await;+ }+ return Err(error);+ }+ }} else {res};@@ -272,7 +284,7 @@ impl Actor {return Ok(());}Err(e) => {- tracing::warn!(bot = %self.cfg.id, error = format!("{e:#}"), "session/load failed; starting fresh");+ tracing::warn!(bot = %self.cfg.id, method = reopen, error = format!("{e:#}"), "couldn't reopen the session; starting fresh");}}}@@ -310,7 +322,7 @@ impl Actor {/// would otherwise hold the bot, and its Stop, forever.pub(super) async fn session_request(&mut self, method: &str, params: Value) -> Result<Value> {let conn = self.conn.as_mut().ok_or_else(|| anyhow!("agent not running"))?;- conn.opening = matches!(method, "session/new" | "session/load");+ conn.opening = matches!(method, "session/new" | "session/load" | "session/resume");let answered = tokio::time::timeout(SESSION_TIMEOUT, conn.acp.request(method, params)).await;conn.opening = false;if let Ok(result) = answered {@@ -330,7 +342,7 @@ impl Actor {if !std::mem::take(&mut conn.opening) {return;}- if !conn.sessions.load {+ if conn.sessions.reopen.is_none() {// ponytail: that session lasts until the agent next stops; keep the cut-short request's Answer past the// time limit and session/close the id it returns, if that ever matters.tracing::warn!(bot = %self.cfg.id, "a session request was cut short; the agent can't resume, so it keeps running");@@ -347,5 +359,5 @@ impl Actor {}}-/// How long `session/new` and `session/load` may take.+/// How long opening a session (`session/new`, `session/load`, `session/resume`) may take.const SESSION_TIMEOUT: Duration = Duration::from_mins(3);diff --git a/host/src/agent/process.rs b/host/src/agent/process.rsindex 8f05613e..88e224b1 100644--- a/host/src/agent/process.rs+++ b/host/src/agent/process.rs@@ -10,6 +10,15 @@ use tokio::time::Instant;const REAP_TIMEOUT: Duration = Duration::from_secs(5);const POLL: Duration = Duration::from_millis(100);+/// One process in an agent's job on Windows.+#[cfg(any(windows, test))]+#[derive(Clone)]+pub(crate) struct JobProcess {+ pub(crate) pid: u32,+ pub(crate) parent: u32,+ pub(crate) name: String,+}+pub(super) struct Process {// Drop the tree before Child can reap the leader and make its PID reusable.tree: Tree,@@ -90,6 +99,12 @@ impl Process {Ok(status == WAIT_OBJECT_0)}+ /// The ids of what is running in the agent's job.+ #[cfg(windows)]+ pub(super) fn job_members(&self) -> Result<Vec<u32>> {+ super::process_windows::job_members(&self.tree.handle)+ }+/// The graceful-shutdown task keeps ownership until its deadline.pub(super) fn begin_stop(&mut self) -> bool {!std::mem::replace(&mut self.stopping, true)diff --git a/host/src/agent/process_windows.rs b/host/src/agent/process_windows.rsindex c9ce4af8..5cdec248 100644--- a/host/src/agent/process_windows.rs+++ b/host/src/agent/process_windows.rs@@ -1,23 +1,88 @@-//! Resume the suspended ACP shell only after its job owns future descendants.+//! Resume the suspended ACP shell only after its job owns future descendants; list what the job holds.+use super::process::JobProcess;use anyhow::{Context, Result, bail};use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};use tokio::process::Child;use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;use windows_sys::Win32::System::Diagnostics::ToolHelp::{- CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,+ CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS, TH32CS_SNAPTHREAD,+ THREADENTRY32, Thread32First, Thread32Next,+};+use windows_sys::Win32::System::JobObjects::{+ JOBOBJECT_BASIC_PROCESS_ID_LIST, JobObjectBasicProcessIdList, QueryInformationJobObject,};use windows_sys::Win32::System::Threading::{OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};-pub(super) fn resume(child: &Child) -> Result<()> {- let pid = child.id().context("agent exited before it could be resumed")?;- // SAFETY: this creates an owned thread snapshot; no pointers are supplied.- let raw = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };+/// More processes than any agent runs; a job past it fails the listing, which counts as busy.+const MOST_PROCESSES: usize = 1024;++/// A snapshot of the system's `flags` (processes, threads).+fn snapshot(flags: u32) -> std::io::Result<OwnedHandle> {+ // SAFETY: this creates an owned snapshot; no pointers are supplied.+ let raw = unsafe { CreateToolhelp32Snapshot(flags, 0) };if raw == INVALID_HANDLE_VALUE {- return Err(std::io::Error::last_os_error()).context("finding suspended agent thread");+ return Err(std::io::Error::last_os_error());}// SAFETY: a successful snapshot transfers a unique valid handle to us.- let snapshot = unsafe { OwnedHandle::from_raw_handle(raw) };+ Ok(unsafe { OwnedHandle::from_raw_handle(raw) })+}++/// The ids of the processes in `job`.+pub(super) fn job_members(job: &OwnedHandle) -> Result<Vec<u32>> {+ let header = size_of::<JOBOBJECT_BASIC_PROCESS_ID_LIST>().div_ceil(size_of::<usize>());+ // usize: the list's own alignment.+ let mut buffer = vec![0_usize; header + MOST_PROCESSES];+ let size = u32::try_from(buffer.len() * size_of::<usize>())?;+ // SAFETY: the job handle is owned and valid, and the buffer is writable for `size` bytes.+ let queried = unsafe {+ QueryInformationJobObject(+ job.as_raw_handle(),+ JobObjectBasicProcessIdList,+ buffer.as_mut_ptr().cast(),+ size,+ std::ptr::null_mut(),+ )+ };+ if queried == 0 {+ return Err(std::io::Error::last_os_error()).context("listing the agent's job");+ }+ // SAFETY: the query wrote a whole list at the buffer's start, aligned for it.+ let list = unsafe { &*buffer.as_ptr().cast::<JOBOBJECT_BASIC_PROCESS_ID_LIST>() };+ if list.NumberOfProcessIdsInList != list.NumberOfAssignedProcesses {+ bail!("the agent's job holds more processes than its list");+ }+ let count = usize::try_from(list.NumberOfProcessIdsInList)?;+ let first = std::mem::offset_of!(JOBOBJECT_BASIC_PROCESS_ID_LIST, ProcessIdList) / size_of::<usize>();+ buffer[first..first + count].iter().map(|id| Ok(u32::try_from(*id)?)).collect()+}++/// `members` with their parents and program names; one that exited since is left out.+pub(super) fn named(members: &[u32]) -> Result<Vec<JobProcess>> {+ let snapshot = snapshot(TH32CS_SNAPPROCESS).context("listing processes")?;+ let mut entry = PROCESSENTRY32W::default();+ entry.dwSize = u32::try_from(size_of_val(&entry))?;+ let mut processes = Vec::new();+ // SAFETY: the snapshot is valid and entry has the required initialized size.+ let mut present = unsafe { Process32FirstW(snapshot.as_raw_handle(), &raw mut entry) };+ while present != 0 {+ if members.contains(&entry.th32ProcessID) {+ let end = entry.szExeFile.iter().position(|c| *c == 0).unwrap_or(entry.szExeFile.len());+ processes.push(JobProcess {+ pid: entry.th32ProcessID,+ parent: entry.th32ParentProcessID,+ name: String::from_utf16_lossy(&entry.szExeFile[..end]),+ });+ }+ // SAFETY: the snapshot and writable entry remain valid during iteration.+ present = unsafe { Process32NextW(snapshot.as_raw_handle(), &raw mut entry) };+ }+ Ok(processes)+}++pub(super) fn resume(child: &Child) -> Result<()> {+ let pid = child.id().context("agent exited before it could be resumed")?;+ let snapshot = snapshot(TH32CS_SNAPTHREAD).context("finding suspended agent thread")?;let mut entry = THREADENTRY32::default();entry.dwSize = u32::try_from(size_of_val(&entry))?;// SAFETY: the snapshot is valid and entry has the required initialized size.diff --git a/host/tests/fixtures/relay_agent.py b/host/tests/fixtures/relay_agent.pyindex d4306b02..6dd0e95c 100644--- a/host/tests/fixtures/relay_agent.py+++ b/host/tests/fixtures/relay_agent.py@@ -38,7 +38,9 @@ for line in sys.stdin:with open(f"{NAME}.jsonl", "a", encoding="utf-8") as log:log.write(json.dumps({"method": method, "params": params}) + "\n")if method == "initialize":- send({"id": message["id"], "result": {"protocolVersion": 1, "agentCapabilities": {"loadSession": True}}})+ # Both ways to reopen a session, like codex-acp; only `session/load` is answered, as the host should prefer it.+ capabilities = {"loadSession": True, "sessionCapabilities": {"resume": {}}}+ send({"id": message["id"], "result": {"protocolVersion": 1, "agentCapabilities": capabilities}})elif method == "session/new":sessions += 1send({"id": message["id"], "result": {"sessionId": f"{NAME}-s{sessions}"}})diff --git a/host/tests/fixtures/resume_agent.py b/host/tests/fixtures/resume_agent.pynew file mode 100644index 00000000..96675f36--- /dev/null+++ b/host/tests/fixtures/resume_agent.py@@ -0,0 +1,53 @@+"""ACP agent that can't load a session but can resume one, like DeepSeek Harness: no `loadSession`, `session/load` is+an unknown method, and resuming a session it's still holding is refused. While the file model.refused is in its folder+it refuses the bot's model. It logs every request to requests.jsonl in its folder."""++import json+import os+import sys+import uuid++MODELS = {"configOptions": [{"id": "model", "category": "model", "type": "select", "currentValue": "fixture",+ "options": [{"value": "fixture", "name": "Fixture"}]}]}++holding = set()+++def send(value):+ print(json.dumps({"jsonrpc": "2.0", **value}), flush=True)+++for line in sys.stdin:+ message = json.loads(line)+ method, rid = message.get("method"), message.get("id")+ if method is None or rid is None:+ continue+ params = message.get("params", {})+ with open("requests.jsonl", "a", encoding="utf-8") as log:+ log.write(json.dumps({"method": method, "params": params}) + "\n")+ if method == "initialize":+ capabilities = {"sessionCapabilities": {"resume": {}, "close": {}}}+ send({"id": rid, "result": {"protocolVersion": 1, "agentCapabilities": capabilities}})+ elif method == "session/new":+ sid = str(uuid.uuid4())+ holding.add(sid)+ send({"id": rid, "result": {"sessionId": sid, **MODELS}})+ elif method == "session/resume":+ if params["sessionId"] in holding:+ send({"id": rid, "error": {"code": -32602, "message": "session is already active"}})+ else:+ holding.add(params["sessionId"])+ send({"id": rid, "result": MODELS})+ elif method == "session/set_config_option" and os.path.exists("model.refused"):+ send({"id": rid, "error": {"code": -32602, "message": "unknown model option"}})+ elif method == "session/set_config_option":+ send({"id": rid, "result": MODELS})+ elif method == "session/close":+ holding.discard(params["sessionId"])+ send({"id": rid, "result": {}})+ elif method == "session/prompt":+ update = {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "ok"}}+ send({"method": "session/update", "params": {"sessionId": params["sessionId"], "update": update}})+ send({"id": rid, "result": {"stopReason": "end_turn"}})+ else:+ send({"id": rid, "error": {"code": -32601, "message": f"Method not found: {method}"}})diff --git a/host/tests/routines_e2e.rs b/host/tests/routines_e2e.rsindex 6c9d7c89..386605d7 100644--- a/host/tests/routines_e2e.rs+++ b/host/tests/routines_e2e.rs@@ -336,8 +336,9 @@ async fn an_agent_started_for_a_run_stops_when_the_run_ends() {host.wait_event("only-runs", "finished", "LATER").await;let events = host.agent_events("only-runs");let count = |event: &str| events.iter().filter(|e| e["event"] == event).count();- // The message started the agent again: the run's agent stopped with the run. Windows never stops an agent (it- // can't tell a dev server from an MCP server, see `lifecycle`), so there the run's session closes instead.+ // The message started the agent again: the run's agent stopped with the run. On Windows this fixture has no MCP+ // server of Codync's, so its job can't be told from a dev server (see `background_work`): the agent counts as+ // busy, and the run's session closes instead.assert_eq!((count("initialize"), count("closed")), if cfg!(windows) { (1, 1) } else { (2, 0) });}diff --git a/host/tests/session_reopen_e2e.rs b/host/tests/session_reopen_e2e.rsnew file mode 100644index 00000000..bfebc8e4--- /dev/null+++ b/host/tests/session_reopen_e2e.rs@@ -0,0 +1,71 @@+//! An agent that can't load a session but can resume one, through a real host and a fixture agent: the conversation+//! carries on after the agent restarts, and the sessions it's done with go back like any other agent's.++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++mod common;++use common::host::Host;+use serde_json::json;+use std::time::Duration;++#[tokio::test]+async fn an_agent_that_only_resumes_keeps_its_conversation_and_gives_sessions_back() {+ if common::python_missing() {+ return;+ }+ let mut host = Host::start().await;+ let bot = host.fixture_bot("Resumes", "resume_agent.py", "").await;++ host.reply(&bot, "one").await;+ let opened = host.requests(&bot, "session/new");+ assert_eq!(opened.len(), 1);++ // The agent starts again with the host: the same session comes back, with its tools.+ host.restart(|_| {}).await;+ host.reply(&bot, "two").await;+ assert_eq!(host.requests(&bot, "session/new").len(), 1, "a new session would lose the conversation");+ assert!(host.requests(&bot, "session/load").is_empty(), "the agent didn't offer session/load");+ let resumed = host.requests(&bot, "session/resume");+ assert_eq!(resumed.len(), 1);+ let main = resumed[0]["params"]["sessionId"].as_str().unwrap();+ assert!(resumed[0]["params"]["mcpServers"].as_array().is_some_and(|s| !s.is_empty()), "{resumed:?}");++ // A routine run's session is spent when the run is; its MCP servers shouldn't stay until the agent stops.+ let routine = json!({"botId": bot, "name": "Check", "instruction": "Report", "triggers": [{"type": "webhook"}]});+ let id = host.call("saveRoutine", routine).await["routine"]["id"].as_str().unwrap().to_owned();+ host.call("runRoutine", json!({"botId": bot, "id": id})).await;+ common::eventually("the run's session is closed", Duration::from_secs(30), async || {+ !host.requests(&bot, "session/close").is_empty()+ })+ .await;+ let closed = host.requests(&bot, "session/close");+ assert_ne!(closed[0]["params"]["sessionId"], main, "the bot's own conversation stays open");+ assert_eq!(host.requests(&bot, "session/new").len(), 2);+}++#[tokio::test]+async fn a_model_refused_after_a_resume_leaves_the_session_to_resume_again() {+ if common::python_missing() {+ return;+ }+ let mut host = Host::start().await;+ let bot = host.fixture_bot("Resumes", "resume_agent.py", "").await;+ host.call("updateBot", json!({"id": bot, "model": "fixture"})).await;+ host.reply(&bot, "one").await;++ let refused = host.home.join("bots").join(&bot).join("workspace").join("model.refused");+ std::fs::write(&refused, "").unwrap();+ host.restart(|_| {}).await;+ host.call("send", json!({"botId": bot, "text": "two", "clientNonce": "n-two"})).await;+ common::eventually("the turn fails on its model", Duration::from_secs(30), async || {+ let history = host.call("history", json!({"botId": bot})).await;+ history["entries"].as_array().unwrap().iter().any(|e| e["data"]["style"] == "error")+ })+ .await;++ std::fs::remove_file(&refused).unwrap();+ host.reply(&bot, "three").await;+ assert_eq!(host.requests(&bot, "session/resume").len(), 2);+ assert_eq!(host.requests(&bot, "session/new").len(), 1, "the agent refused to resume a session it still held");+}diff --git a/web/content/docs/agents.mdx b/web/content/docs/agents.mdxindex 78fbabc0..583e1b6c 100644--- a/web/content/docs/agents.mdx+++ b/web/content/docs/agents.mdx@@ -57,7 +57,7 @@ Signing in to Google Antigravity with `agy` in a terminal doesn't sign in the paWorkBuddy is separate from CodeBuddy Code. Codync runs the CLI bundled in the WorkBuddy app: `WorkBuddy AI.app` (from workbuddy.ai) or `WorkBuddy.app` (from codebuddy.cn) on macOS, or its install folder on Windows (`%LOCALAPPDATA%\Programs\WorkBuddy AI` or `WorkBuddy`). That CLI only ships WorkBuddy's lite build, so Codync starts it the way the app does. It runs on Node.js: if the computer has none, Codync offers to add its own. Codync does not install WorkBuddy, and there is no Linux build, so Codync on Linux doesn't list it. Sign in from Codync: the WorkBuddy app's login stays in the app, so this CLI asks again and opens a browser. A `codebuddy` command on your `PATH` stays CodeBuddy Code.-DeepSeek Harness runs its own `dsh --profile acp` mode. It has no sign-in command: it uses the DeepSeek API key saved in `dsh web`, or `DEEPSEEK_API_KEY` set in `~/.dsh/.env`. It can't reopen an earlier session, so after the host or the agent restarts, a DeepSeek Harness bot starts a new session; the chat in Codync stays.+DeepSeek Harness runs its own `dsh --profile acp` mode. It has no sign-in command: it uses the DeepSeek API key saved in `dsh web`, or `DEEPSEEK_API_KEY` set in `~/.dsh/.env`. After the host or the agent restarts, a DeepSeek Harness bot carries on in the same session.Hermes Agent runs its own `hermes acp` mode, with the provider and model you pick in `hermes acp --setup`. On Windows, Codync also finds it in its install folders (`%LOCALAPPDATA%\hermes\bin`) without a `PATH` change. Hermes and Gemini CLI keep a memory of their own that every bot on them shares; see [Memory](/docs/memory#agents-with-a-memory-of-their-own).