CLI: async runtime + proper RPC fallback plumbing

- main.rs: use #[tokio::main] so CLI has a runtime available
- memory.rs: make run_with_local_store async (no more runtime creation)
- mcp_server.rs: cache socket connection in OnceLock, use block_in_place
  for async fallback when socket unavailable

Fixes "cannot start a runtime from within a runtime" panic when CLI
falls back to local store.

Co-Authored-By: Kent Overstreet <kent.overstreet@linux.dev>
This commit is contained in:
Kent Overstreet 2026-04-13 11:23:52 -04:00
parent 7476e9d0db
commit dc1049f62d
3 changed files with 96 additions and 55 deletions

View file

@ -58,22 +58,14 @@ async fn cached_store() -> Result<Arc<crate::Mutex<Store>>> {
}
/// Run a tool with a temporarily-opened store (for rpc_local fallback).
pub fn run_with_local_store(tool_name: &str, args: serde_json::Value) -> Result<String> {
let store = Store::load().map_err(|e| anyhow::anyhow!("{}", e))?;
let arc = Arc::new(crate::Mutex::new(store));
pub async fn run_with_local_store(tool_name: &str, args: serde_json::Value) -> Result<String> {
let store = Store::cached().await.map_err(|e| anyhow::anyhow!("{}", e))?;
LOCAL_STORE.with(|s| *s.borrow_mut() = Some(arc));
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let name = tool_name.to_string();
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(dispatch(&name, &None, args))
}));
LOCAL_STORE.with(|s| *s.borrow_mut() = Some(store));
let result = dispatch(tool_name, &None, args).await;
LOCAL_STORE.with(|s| *s.borrow_mut() = None);
result.map_err(|_| anyhow::anyhow!("tool panicked"))?
result
}
/// Get provenance from agent, or from args._provenance, or "manual".

View file

@ -476,7 +476,8 @@ impl Run for AdminCmd {
}
}
fn main() {
#[tokio::main]
async fn main() {
std::panic::set_backtrace_style(std::panic::BacktraceStyle::Short);
// Handle --help ourselves for expanded subcommand display

View file

@ -9,7 +9,7 @@ use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::{Arc, Mutex, OnceLock};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, BufWriter};
use tokio::net::{UnixListener, UnixStream};
@ -21,17 +21,22 @@ pub fn socket_path() -> PathBuf {
.join(".consciousness/mcp.sock")
}
/// Forward a tool call to the daemon socket, or execute locally if daemon is down.
/// Used by external processes that don't have direct store access.
pub fn memory_rpc(tool_name: &str, args: serde_json::Value) -> Result<String> {
// Cached socket connection
static SOCKET_CONN: OnceLock<Mutex<Option<SocketConn>>> = OnceLock::new();
struct SocketConn {
reader: std::io::BufReader<std::os::unix::net::UnixStream>,
writer: std::io::BufWriter<std::os::unix::net::UnixStream>,
next_id: u64,
}
impl SocketConn {
fn connect() -> Result<Self> {
use std::os::unix::net::UnixStream;
use std::io::{BufRead, BufReader, BufWriter, Write};
let path = socket_path();
let stream = match UnixStream::connect(&path) {
Ok(s) => s,
Err(_) => return rpc_local(tool_name, &args),
};
let stream = UnixStream::connect(&path)?;
let mut reader = BufReader::new(stream.try_clone()?);
let mut writer = BufWriter::new(stream);
@ -44,13 +49,20 @@ pub fn memory_rpc(tool_name: &str, args: serde_json::Value) -> Result<String> {
let mut buf = String::new();
reader.read_line(&mut buf)?;
// Call tool
let call = json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call",
Ok(Self { reader, writer, next_id: 1 })
}
fn call(&mut self, tool_name: &str, args: &serde_json::Value) -> Result<String> {
use std::io::{BufRead, Write};
self.next_id += 1;
let call = json!({"jsonrpc": "2.0", "id": self.next_id, "method": "tools/call",
"params": {"name": tool_name, "arguments": args}});
writeln!(writer, "{}", call)?;
writer.flush()?;
buf.clear();
reader.read_line(&mut buf)?;
writeln!(self.writer, "{}", call)?;
self.writer.flush()?;
let mut buf = String::new();
self.reader.read_line(&mut buf)?;
let resp: serde_json::Value = serde_json::from_str(&buf)?;
if let Some(err) = resp.get("error") {
@ -65,10 +77,46 @@ pub fn memory_rpc(tool_name: &str, args: serde_json::Value) -> Result<String> {
.unwrap_or("");
Ok(text.to_string())
}
}
/// Forward a tool call to the daemon socket, or execute locally if daemon is down.
/// Used by external processes that don't have direct store access.
pub fn memory_rpc(tool_name: &str, args: serde_json::Value) -> Result<String> {
let conn_lock = SOCKET_CONN.get_or_init(|| Mutex::new(None));
let mut guard = conn_lock.lock().unwrap();
// Try cached connection first
if let Some(conn) = guard.as_mut() {
match conn.call(tool_name, &args) {
Ok(result) => return Ok(result),
Err(_) => {
// Connection broken, clear cache and retry
*guard = None;
}
}
}
// Try to establish new connection
match SocketConn::connect() {
Ok(mut conn) => {
let result = conn.call(tool_name, &args);
*guard = Some(conn);
result
}
Err(_) => {
// Socket unavailable - fall back to local store
drop(guard); // Release lock before blocking
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(rpc_local(tool_name, &args))
})
}
}
}
/// Execute a tool locally when daemon isn't running.
fn rpc_local(tool_name: &str, args: &serde_json::Value) -> Result<String> {
crate::agent::tools::memory::run_with_local_store(tool_name, args.clone())
async fn rpc_local(tool_name: &str, args: &serde_json::Value) -> Result<String> {
crate::agent::tools::memory::run_with_local_store(tool_name, args.clone()).await
}
#[derive(Debug, Deserialize)]