pub mod http;
pub mod methods;
pub mod transport;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use tracing::info;
use crate::agents::locate_agents_dir;
use crate::jsonrpc::Router;
use crate::session::SessionRegistry;
const SHUTDOWN_GRACE: Duration = Duration::from_secs(10);
pub const DEFAULT_HTTP_PORT: u16 = 7881;
pub fn build_router(project: PathBuf) -> (Router, Arc<SessionRegistry>) {
let sessions = Arc::new(SessionRegistry::new());
let agents_dir = locate_agents_dir(&project);
let mut router = Router::new();
methods::register(&mut router);
crate::session::protocol::register(&mut router, sessions.clone());
crate::task::protocol::register(&mut router, sessions.clone(), project, agents_dir);
(router, sessions)
}
pub async fn run_stdio(project: PathBuf) -> Result<()> {
info!(project = %project.display(), "tcode serve --stdio: starting");
let (router, sessions) = build_router(project);
transport::run_stdio_loop(router).await?;
sessions.shutdown_executions(SHUTDOWN_GRACE).await;
info!("tcode serve --stdio: stopped");
Ok(())
}
pub async fn run_http(project: PathBuf, port: u16) -> Result<()> {
info!(project = %project.display(), port, "tcode serve --http: starting");
let (router, sessions) = build_router(project);
http::run_http(router, sessions.clone(), port).await?;
sessions.shutdown_executions(SHUTDOWN_GRACE).await;
info!("tcode serve --http: stopped");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use trusty_common::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 (router, _sessions) = build_router(project.path().to_path_buf());
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 (router, sessions) = build_router(project.path().to_path_buf());
let session = sessions.create("t".to_string(), None, 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);
}
#[test]
fn default_http_port_is_documented_value() {
assert_eq!(DEFAULT_HTTP_PORT, 7881);
}
#[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.toml"),
"[agent]\nname = \"pm\"\nmodel = \"openai/gpt-4o-mini\"\n[system_prompt]\ncontent = \"PM\"\n",
)
.expect("write pm.toml");
std::fs::write(
project
.path()
.join(".claude")
.join("agents")
.join("python-engineer.toml"),
"[agent]\nname = \"python-engineer\"\nmodel = \"deepseek/deepseek-chat\"\n[system_prompt]\ncontent = \"eng\"\n",
)
.expect("write python-engineer.toml");
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 (router, sessions) = build_router(project.path().to_path_buf());
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");
}
}