pub mod methods;
pub mod transport;
pub mod uds;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
use tokio::sync::Mutex;
use tracing::info;
use crate::binding::ProjectBinding;
use crate::jsonrpc::Router;
use crate::session::SessionRegistry;
use crate::workstreams::{SharedWorkstreamStore, WorkstreamStore};
const SHUTDOWN_GRACE: Duration = Duration::from_secs(10);
pub async fn build_router(
binding: ProjectBinding,
) -> Result<(Router, Arc<SessionRegistry>, SharedWorkstreamStore)> {
crate::log_drain::spawn(
binding.root().map(std::path::Path::to_path_buf),
crate::logging::file_log_dir(),
crate::paths::private_state::private_state_dir().join("log-drain"),
);
build_router_at(binding, &crate::workstreams::default_data_dir()).await
}
async fn build_router_at(
binding: ProjectBinding,
data_dir: &std::path::Path,
) -> Result<(Router, Arc<SessionRegistry>, SharedWorkstreamStore)> {
let sessions = Arc::new(SessionRegistry::new());
crate::agents::deploy::deploy_and_log(binding.root());
let agents_dir = binding.agents_dir();
let mut workstream_store = WorkstreamStore::load_for_binding(data_dir, &binding)
.await
.context("loading workstream store")?;
let live_session_ids: std::collections::HashSet<String> =
sessions.list().into_iter().map(|s| s.id).collect();
workstream_store
.reconcile_on_boot(&live_session_ids)
.await
.context("reconciling workstream store on boot")?;
let workstreams = Arc::new(Mutex::new(workstream_store));
let mut router = Router::new();
methods::register(&mut router, binding.clone());
crate::session::protocol::register(&mut router, sessions.clone(), workstreams.clone());
crate::fs_browse::protocol::register(&mut router);
crate::agents::protocol::register(
&mut router,
crate::agents::protocol::AgentsCatalogState::new(agents_dir.clone(), binding.is_bound()),
);
crate::skills::protocol::register(
&mut router,
crate::skills::protocol::SkillsCatalogState::new(binding.root()),
);
let permissions = Arc::new(crate::permissions::PermissionBroker::new());
crate::permissions::protocol::register(&mut router, Arc::clone(&permissions));
crate::task::protocol::register_with_permissions(
&mut router,
sessions.clone(),
binding,
agents_dir,
workstreams.clone(),
Some(permissions),
);
crate::workstreams::protocol::register(&mut router, workstreams.clone());
Ok((router, sessions, workstreams))
}
pub async fn run_stdio(binding: ProjectBinding) -> Result<()> {
info!(
binding = binding.state(),
project = binding.label().unwrap_or_else(|| "<projectless>".into()),
"tcode serve --stdio: starting"
);
let (router, sessions, _workstreams) = build_router(binding).await?;
transport::run_stdio_loop(router).await?;
sessions.shutdown_executions(SHUTDOWN_GRACE).await;
info!("tcode serve --stdio: stopped");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
use trusty_mcp::Request;
fn test_ctx() -> crate::jsonrpc::ConnectionContext {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
crate::jsonrpc::ConnectionContext::new(tx)
}
#[tokio::test]
async fn run_stdio_router_recognises_proof_of_life_methods() {
let project = tempfile::tempdir().expect("project tempdir");
let data_dir = tempfile::tempdir().expect("data tempdir");
let (router, _sessions, _workstreams) = build_router_at(
ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
data_dir.path(),
)
.await
.expect("build_router_at");
for method in ["ping", "health"] {
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: method.to_string(),
params: None,
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"{method} must be registered, got {:?}",
resp.error
);
}
}
#[tokio::test]
async fn build_router_wires_session_methods() {
let project = tempfile::tempdir().expect("project tempdir");
let data_dir = tempfile::tempdir().expect("data tempdir");
let (router, sessions, _workstreams) = build_router_at(
ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
data_dir.path(),
)
.await
.expect("build_router_at");
let session = sessions.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: "session.status".to_string(),
params: Some(json!({"session_id": session.id})),
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"session.status must be registered, got {:?}",
resp.error
);
assert_eq!(resp.result.unwrap()["id"], session.id);
}
#[tokio::test]
async fn build_router_wires_fs_list_dir() {
let project = tempfile::tempdir().expect("project tempdir");
let data_dir = tempfile::tempdir().expect("data tempdir");
let (router, _sessions, _workstreams) = build_router_at(
ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
data_dir.path(),
)
.await
.expect("build_router_at");
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: "fs.list_dir".to_string(),
params: Some(json!({"path": project.path().display().to_string()})),
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"fs.list_dir must be registered, got {:?}",
resp.error
);
assert!(resp.result.expect("result")["entries"].is_array());
}
#[tokio::test]
async fn build_router_wires_agents_and_skills_catalog_methods() {
let project = tempfile::tempdir().expect("project tempdir");
let data_dir = tempfile::tempdir().expect("data tempdir");
let (router, _sessions, _workstreams) = build_router_at(
ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
data_dir.path(),
)
.await
.expect("build_router_at");
for method in ["agents.list", "skills.list"] {
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: method.to_string(),
params: None,
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"{method} must be registered, got {:?}",
resp.error
);
}
}
#[tokio::test]
async fn build_router_is_projectless_without_a_project() {
let data_dir = tempfile::tempdir().expect("data tempdir");
let (router, _sessions, _workstreams) =
build_router_at(ProjectBinding::None, data_dir.path())
.await
.expect("build_router_at");
for method in ["task.run", "session.create", "session.list"] {
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: method.to_string(),
params: Some(json!({})),
};
let resp = router.dispatch(req, &test_ctx()).await;
if let Some(err) = resp.error {
assert_ne!(
err.code, -32601,
"{method} must be wired on a projectless daemon, got method-not-found"
);
}
}
}
#[tokio::test]
async fn build_router_wires_task_run() {
let project = tempfile::tempdir().expect("project tempdir");
std::fs::create_dir_all(project.path().join(".claude").join("agents")).expect("mkdir");
std::fs::write(
project.path().join(".claude").join("agents").join("pm.md"),
"---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nPM\n",
)
.expect("write pm.md");
std::fs::write(
project
.path()
.join(".claude")
.join("agents")
.join("python-engineer.md"),
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\neng\n",
)
.expect("write python-engineer.md");
let _guard = crate::task::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
unsafe {
std::env::set_var(
crate::task::mock_llm::MOCK_LLM_ENV,
crate::task::mock_llm::MOCK_LLM_ECHO,
);
}
let data_dir = tempfile::tempdir().expect("data tempdir");
let (router, sessions, _workstreams) = build_router_at(
ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
data_dir.path(),
)
.await
.expect("build_router_at");
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: "task.run".to_string(),
params: Some(json!({"task_description": "say hi"})),
};
let resp = router.dispatch(req, &test_ctx()).await;
sessions
.shutdown_executions(std::time::Duration::from_secs(5))
.await;
unsafe {
std::env::remove_var(crate::task::mock_llm::MOCK_LLM_ENV);
}
assert!(
resp.error.is_none(),
"task.run must be registered, got {:?}",
resp.error
);
assert_eq!(resp.result.unwrap()["status"], "running");
}
#[tokio::test]
async fn build_router_wires_workstream_methods() {
let project = tempfile::tempdir().expect("project tempdir");
let data_dir = tempfile::tempdir().expect("data tempdir");
let binding =
ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind");
let (router, _sessions, _workstreams) = build_router_at(binding.clone(), data_dir.path())
.await
.expect("build_router_at");
let create_req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: "workstream.activate".to_string(),
params: Some(json!({"id": crate::workstreams::WorkstreamId::new().to_string()})),
};
let resp = router.dispatch(create_req, &test_ctx()).await;
let err = resp
.error
.expect("activating an unknown id must fail, not silently succeed");
assert_eq!(err.code, -32002, "workstream.activate must be registered");
let deactivate_req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(2)),
method: "workstream.deactivate".to_string(),
params: Some(json!({"id": crate::workstreams::WorkstreamId::new().to_string()})),
};
let resp = router.dispatch(deactivate_req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"workstream.deactivate must be registered, got {:?}",
resp.error
);
let (_router2, _sessions2, _workstreams2) = build_router_at(binding, data_dir.path())
.await
.expect("a second build_router_at over the same data_dir must succeed");
}
#[tokio::test]
async fn build_router_reconciles_dangling_active_pointer_on_boot() {
let project = tempfile::tempdir().expect("project tempdir");
let data_dir = tempfile::tempdir().expect("data tempdir");
let binding =
ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind");
let store_path = crate::workstreams::store_path(data_dir.path(), &binding);
let dangling_id = crate::workstreams::WorkstreamId::new();
let raw = json!({
"version": "1.0",
"active_workstream_id": dangling_id,
"workstreams": [],
});
tokio::fs::create_dir_all(data_dir.path())
.await
.expect("mkdir data_dir");
tokio::fs::write(&store_path, serde_json::to_string_pretty(&raw).unwrap())
.await
.expect("seed raw store file with a dangling active_workstream_id");
let (router, _sessions, _workstreams) = build_router_at(binding, data_dir.path())
.await
.expect("build_router_at must reconcile the dangling pointer, not fail");
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: "workstream.list".to_string(),
params: Some(json!({})),
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"workstream.list must succeed, got {:?}",
resp.error
);
assert_eq!(
resp.result.unwrap()["active_workstream_id"],
Value::Null,
"boot reconciliation through build_router_at must clear a dangling \
active_workstream_id before the router answers requests"
);
}
}