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): keep Claude signed in and report its real sign-in state

leepokaidf319517b893
diff --git a/docs/guides/development.md b/docs/guides/development.md
index a2dcf321..6f468401 100644
--- a/docs/guides/development.md
+++ b/docs/guides/development.md
@@ -35,10 +35,12 @@ successful restart; stop that host in its terminal and retry. Hosts attached usi
`CODYNC_PORT` are managed manually.
On SIGTERM the host stops its bots without waiting for open SSE or WebSocket
-connections. ACP adapters run in separate process groups; stopping an adapter
-also kills tools and MCP servers that remain in its group. Processes that detach
-into their own sessions and unrelated hosts using other data directories are
-outside this cleanup.
+connections. ACP adapters run in separate process groups. Stopping an adapter
+closes its stdin and gives its group 10 seconds to exit by itself, so a Claude
+Code CLI can finish saving a refreshed login. Tools and MCP servers still left
+in the group after that are killed, and the host waits for this before it exits.
+Processes that detach into their own sessions and unrelated hosts using other
+data directories are outside this cleanup.
After rebuilding the host, restart the service (macOS launch agent shown; Linux
uses the environment-specific systemd user unit). Stop only test hosts you started; do not kill another environment's host. For Dev:
diff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rs
index 7d095ab6..f7303ac1 100644
--- a/host/src/agent/acp.rs
+++ b/host/src/agent/acp.rs
@@ -9,12 +9,19 @@ use std::collections::{HashMap, VecDeque};
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicI64, Ordering};
+use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, Command};
use tokio::sync::{mpsc, oneshot};
+use tokio::time::Instant;
/// stderr lines kept to explain a crash.
const STDERR_TAIL_LINES: usize = 12;
+/// How long a stopped agent gets to exit by itself before what's left of it is killed.
+const EXIT_GRACE: Duration = Duration::from_secs(10);
+
+/// Agents [`Acp::kill`] is still stopping, for the host to wait for before it exits.
+static STOPPING: std::sync::Mutex<Vec<tokio::task::JoinHandle<()>>> = std::sync::Mutex::new(Vec::new());
pub enum Incoming {
Notification { method: String, params: Value },
@@ -108,10 +115,12 @@ impl Answer {
}
pub struct Acp {
- stdin: tokio::sync::Mutex<ChildStdin>,
+ /// `None` once stopped: the closed pipe tells the agent to exit.
+ stdin: tokio::sync::Mutex<Option<ChildStdin>>,
next_id: AtomicI64,
pending: Pending,
- child: tokio::sync::Mutex<Child>,
+ /// `None` once stopped (handed to [`reap`]).
+ child: tokio::sync::Mutex<Option<Child>>,
/// The process (and, on Unix, process group) leader.
pid: Option<u32>,
}
@@ -200,10 +209,10 @@ impl Acp {
let pid = child.id();
let acp = Arc::new(Self {
- stdin: tokio::sync::Mutex::new(stdin),
+ stdin: tokio::sync::Mutex::new(Some(stdin)),
next_id: AtomicI64::new(1),
pending,
- child: tokio::sync::Mutex::new(child),
+ child: tokio::sync::Mutex::new(Some(child)),
pid,
});
Ok((acp, rx))
@@ -217,6 +226,7 @@ impl Acp {
let mut line = serde_json::to_vec(&msg)?;
line.push(b'\n');
let mut stdin = self.stdin.lock().await;
+ let stdin = stdin.as_mut().ok_or_else(|| Failure::error(FailureKind::Exited, "agent stopped"))?;
stdin.write_all(&line).await?;
stdin.flush().await?;
Ok(())
@@ -248,31 +258,71 @@ impl Acp {
self.write(json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})).await
}
+ /// Stops the agent and everything it started, without waiting for it. Closing its stdin
+ /// lets it exit by itself first: Claude Code killed during an OAuth refresh loses the new
+ /// refresh token, and the user's login with it.
pub async fn kill(&self) {
- let mut child = self.child.lock().await;
- // ACP adapters spawn MCP servers and tools. Stop the adapter's whole
- // process group (Windows: process tree) before reaping its leader.
- if let Some(pid) = child.id() {
- let mut tree = if cfg!(windows) {
- let mut c = Command::new("taskkill");
- c.args(["/T", "/F", "/PID", &pid.to_string()]);
- c
- } else {
- let mut c = Command::new("/bin/kill");
- c.args(["-KILL", "--", &format!("-{pid}")]);
- c
- };
- let _ = tree.stdout(Stdio::null()).stderr(Stdio::null()).status().await;
- }
- // Already exited is fine; anything else is worth a log line.
- if let Err(error) = child.kill().await
- && error.kind() != std::io::ErrorKind::InvalidInput
- {
- tracing::debug!(%error, "couldn't kill agent process");
+ self.stdin.lock().await.take();
+ if let Some(child) = self.child.lock().await.take() {
+ let mut stopping = STOPPING.locked();
+ stopping.retain(|task| !task.is_finished());
+ stopping.push(tokio::spawn(reap(child)));
}
}
}
+/// Waits until every agent being stopped has exited or been killed (at most [`EXIT_GRACE`]).
+pub async fn stopped() {
+ let tasks = std::mem::take(&mut *STOPPING.locked());
+ futures::future::join_all(tasks).await;
+}
+
+/// Gives the agent [`EXIT_GRACE`] to exit with everything it started (ACP adapters spawn
+/// CLIs, MCP servers and tools), then kills its process group (Windows: process tree).
+async fn reap(mut child: Child) {
+ let Some(pid) = child.id() else { return };
+ let deadline = Instant::now() + EXIT_GRACE;
+ let exited = tokio::time::timeout_at(deadline, child.wait()).await.is_ok();
+ if !exited || outlived(pid, deadline).await {
+ let mut tree = if cfg!(windows) {
+ let mut c = Command::new("taskkill");
+ c.args(["/T", "/F", "/PID", &pid.to_string()]);
+ c
+ } else {
+ let mut c = Command::new("/bin/kill");
+ c.args(["-KILL", "--", &format!("-{pid}")]);
+ c
+ };
+ let _ = tree.stdout(Stdio::null()).stderr(Stdio::null()).status().await;
+ }
+ // Already exited is fine; anything else is worth a log line.
+ if let Err(error) = child.kill().await
+ && error.kind() != std::io::ErrorKind::InvalidInput
+ {
+ tracing::debug!(%error, "couldn't kill agent process");
+ }
+}
+
+/// Whether part of the exited agent's process group is still running at `deadline`.
+#[cfg(unix)]
+async fn outlived(pid: u32, deadline: Instant) -> bool {
+ let Ok(group) = libc::pid_t::try_from(pid) else { return true };
+ // SAFETY: signal 0 sends nothing; it only checks that the group still has a process.
+ let running = || unsafe { libc::killpg(group, 0) } == 0;
+ while running() && Instant::now() < deadline {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ running()
+}
+
+/// Windows has no process groups: what the agent started got the same closed pipes, and its
+/// tree can't be found once it's gone.
+#[cfg(windows)]
+#[allow(clippy::unused_async)] // the Unix check's signature
+async fn outlived(_pid: u32, _deadline: Instant) -> bool {
+ false
+}
+
/// Plain-text rendering of an ACP content block list / tool-call content list.
pub fn content_text(v: &Value) -> String {
match v {
@@ -325,14 +375,30 @@ mod tests {
&[],
)
.unwrap();
- let ready = tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv()).await.unwrap();
+ let ready = tokio::time::timeout(Duration::from_secs(3), rx.recv()).await.unwrap();
assert!(matches!(ready, Some(Incoming::Notification { .. })));
acp.kill().await;
// Killing only the shell leaves sleep holding stdout for 60 seconds.
- let closed = tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv()).await.unwrap();
+ let closed = tokio::time::timeout(EXIT_GRACE + Duration::from_secs(3), rx.recv()).await.unwrap();
assert!(matches!(closed, Some(Incoming::Closed { .. })));
}
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_stopped_agent_finishes_by_itself_first() {
+ // The adapter exits on its closed stdin; the CLI it started saves its login a second later.
+ let (acp, mut rx) = Acp::spawn(
+ r#"sh -c 'read line; (sleep 1; echo "{\"jsonrpc\":\"2.0\",\"method\":\"saved\"}") &'"#,
+ "/tmp",
+ &[],
+ )
+ .unwrap();
+ acp.kill().await;
+ let saved = tokio::time::timeout(EXIT_GRACE, rx.recv()).await.unwrap();
+ assert!(matches!(saved, Some(Incoming::Notification { method, .. }) if method == "saved"));
+ assert!(acp.notify("x", json!({})).await.is_err(), "a stopped agent takes no more messages");
+ }
+
#[cfg(unix)]
#[tokio::test]
async fn request_response_roundtrip() {
diff --git a/host/src/agent/auth.rs b/host/src/agent/auth.rs
index db6e306c..49516043 100644
--- a/host/src/agent/auth.rs
+++ b/host/src/agent/auth.rs
@@ -1,8 +1,9 @@
//! Signing agents in the ACP way, so every agent that speaks ACP can be set up
//! from Codync, not just the ones we know by name.
//!
-//! A check starts the agent, reads the `authMethods` it advertises and tries
-//! `session/new`: `-32000` means it needs signing in. Methods come in three kinds:
+//! A check starts the agent, reads the `authMethods` it advertises and takes the
+//! login it reports (`_auth/status_update`), or else tries `session/new`: `-32000`
+//! means it needs signing in. Methods come in three kinds:
//! - terminal: a command (the agent's `_meta.terminal-auth`, or its own binary
//! with `args`), run in a setup terminal (`term`);
//! - agent: the agent signs itself in on `authenticate` (usually a browser on
@@ -219,8 +220,16 @@ fn model_options(options: &Value, model: &str) -> Vec<Value> {
}
async fn probe(store: &Store, backend: &str) -> Result<Status> {
- let (acp, _inbox, init, cmd) = start(store, backend).await?;
+ let (acp, mut inbox, init, cmd) = start(store, backend).await?;
let methods = methods(backend, &init, &cmd);
+ // An agent that reports its login is believed over a session: Claude's adapter opens one
+ // without checking the login, which then fails at the first prompt.
+ if init["agentCapabilities"]["_meta"]["authStatus"].is_object()
+ && let Some(signed_in) = reported_login(&mut inbox).await
+ {
+ acp.kill().await;
+ return Ok(Status { signed_in: Some(signed_in), detail: None, methods });
+ }
let dir = probe_dir();
tokio::fs::create_dir_all(&dir).await?;
let res = tokio::time::timeout(
@@ -240,6 +249,24 @@ async fn probe(store: &Store, backend: &str) -> Result<Status> {
Ok(Status { signed_in, detail, methods })
}
+/// The agent's first `_auth/status_update` (ACP `authStatus` extension): `kind: "none"` is signed
+/// out, any other kind signed in. `None`: it can't tell (it stays silent then).
+async fn reported_login(inbox: &mut mpsc::UnboundedReceiver<Incoming>) -> Option<bool> {
+ // Claude's adapter gives its `claude auth status` 5 s.
+ let report = async {
+ while let Some(incoming) = inbox.recv().await {
+ if let Incoming::Notification { method, params } = incoming
+ && method == "_auth/status_update"
+ && let Some(kind) = params["authStatus"]["kind"].as_str()
+ {
+ return Some(kind != "none");
+ }
+ }
+ None
+ };
+ tokio::time::timeout(Duration::from_secs(8), report).await.ok().flatten()
+}
+
/// Starts `backend` and completes `initialize`, trying each way to launch it.
/// The agent's inbox must stay open: the reader stops when nobody listens.
type Started = (Arc<Acp>, mpsc::UnboundedReceiver<Incoming>, Value, Cmd);
@@ -520,6 +547,22 @@ mod tests {
assert!(serde_json::to_value(&m[0]).unwrap().get("command").is_none());
}
+ #[tokio::test]
+ async fn takes_the_first_login_the_agent_reports() {
+ let report = |kind: &str| Incoming::Notification {
+ method: "_auth/status_update".into(),
+ params: json!({"authStatus": {"kind": kind, "label": "x"}}),
+ };
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ tx.send(Incoming::Notification { method: "session/update".into(), params: json!({}) }).unwrap();
+ tx.send(report("none")).unwrap();
+ tx.send(report("account")).unwrap();
+ assert_eq!(reported_login(&mut rx).await, Some(false));
+ assert_eq!(reported_login(&mut rx).await, Some(true));
+ drop(tx);
+ assert_eq!(reported_login(&mut rx).await, None, "an agent that goes quiet can't tell");
+ }
+
#[test]
fn skips_terminal_commands_of_another_harness() {
let init = json!({"authMethods": [{"id": "k", "name": "Kilo", "_meta": {"terminal-auth": {"command": "opencode", "args": ["auth", "login"]}}}]});
diff --git a/host/src/main.rs b/host/src/main.rs
index c0ad5b23..6e553a0f 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -545,6 +545,7 @@ async fn serve(bind: &str, port: u16) -> Result<()> {
() = shutdown_signal() => {},
}
hub.shutdown().await;
+ agent::acp::stopped().await;
analytics::flush_before_exit(&hub).await;
tracing::info!("codync-host stopped");
Ok(())