Skip to main content

trusty_code/serve/
mod.rs

1//! `tcode serve` daemon: STDIO + HTTP JSON-RPC transports + proof-of-life,
2//! `session.*`, and `task.*` methods (#2053, #2054, #2056, #2058,
3//! M1 control-plane cut line).
4//!
5//! Why: this module is the foundation the `tcode serve` binary subcommand
6//! delegates to. It owns assembling the [`crate::jsonrpc::Router`] (and,
7//! since #2054, the [`crate::session::SessionRegistry`] every `session.*`/
8//! `task.*` method shares) and entering whichever transport loop was
9//! requested; `main.rs` stays a thin clap-to-handler shim, matching the rest
10//! of the crate's CLI wiring.
11//! What: [`build_router`] registers every currently-known method group
12//! (today: [`methods::register`]'s `ping`/`health` proof-of-life pair,
13//! `crate::session::protocol::register`'s eight `session.*` methods
14//! (including #2058's read-only `session.get_transcript`), and (#2056)
15//! `crate::task::protocol::register`'s `task.run` — later tickets add
16//! `harness.describe` #2066 here, one line each). [`run_stdio`] and
17//! [`run_http`] both build a router + registry via `build_router` and hand
18//! them to their respective transport ([`transport::run_stdio_loop`] /
19//! [`http::run_http`]) — every method behaves identically over either
20//! transport because both dispatch through the same `Router` against the
21//! same `SessionRegistry`. Both also call
22//! `SessionRegistry::shutdown_executions` before returning, so a graceful
23//! stop (SIGTERM/stdin EOF) gives any in-flight `task.run` execution a
24//! bounded chance to unwind — the same connection-safe-restart discipline
25//! (issue #534) this crate's daemons already apply to connections, now
26//! extended to background tasks.
27//!
28//! What's NOT here yet: the transports are independent modes (`--stdio` xor
29//! `--http`), not simultaneous; running both at once would need a shared
30//! `Arc<Router>`/`Arc<SessionRegistry>` across two concurrently-spawned
31//! tasks, which no current ticket requires (the registry is already `Arc`,
32//! so this is a small extension when it's needed).
33//!
34//! Test: `serve::tests::*`.
35
36pub mod http;
37pub mod methods;
38pub mod transport;
39
40use std::path::PathBuf;
41use std::sync::Arc;
42use std::time::Duration;
43
44use anyhow::Result;
45use tracing::info;
46
47use crate::agents::locate_agents_dir;
48use crate::jsonrpc::Router;
49use crate::session::SessionRegistry;
50
51/// How long a graceful stop waits for in-flight `task.run` executions to
52/// observe cancellation and unwind before the process exits anyway.
53///
54/// Why: bounds shutdown latency — an operator restarting the daemon should
55/// not wait indefinitely on a stuck tool call; best-effort, not a hard
56/// guarantee (see `SessionRegistry::shutdown_executions`'s docs).
57const SHUTDOWN_GRACE: Duration = Duration::from_secs(10);
58
59/// Default TCP port for `tcode serve --http` when `--port` is omitted.
60///
61/// Why: the trusty-* family reserves a block of fixed local ports so
62/// operators/tooling can find a daemon without a discovery file
63/// (`trusty-memory` 7070, `trusty-search` 7878, `trusty-analyze` 7879,
64/// `trusty-review` 7880). `7881` is the next free port in that sequence.
65/// Pass `--port 0` to bind an OS-assigned ephemeral port instead (e.g. for
66/// tests or running multiple instances side by side); the real bound port
67/// is always logged to stderr regardless of which is used.
68/// What: `7881`.
69/// Test: `default_http_port_is_documented_value`.
70pub const DEFAULT_HTTP_PORT: u16 = 7881;
71
72/// Assemble the router (+ its session registry) with every method this
73/// build of `tcode` knows about, scoped to `project`.
74///
75/// Why: single place that lists which method groups are wired in, so a new
76/// ticket adding `harness.describe` touches exactly one line here plus its
77/// own `register` function. Both transports (`run_stdio`, `run_http`) call
78/// this so they can never drift into different method surfaces, and both
79/// need the SAME `SessionRegistry` instance — `run_http` hands it separately
80/// to the `GET /sessions/{id}/events` SSE route, which bypasses the `Router`
81/// entirely (see `crate::serve::http` module docs). `task.run` (#2056) is
82/// the first method that needs `project` for more than logging — it resolves
83/// `agents_dir` from it via `crate::agents::locate_agents_dir` (the same
84/// `.claude/agents` / `.open-mpm/agents` convention `tcode run-task` uses)
85/// and passes both down to spawned executions.
86/// What: builds an empty `Router` + a fresh `SessionRegistry`, calls
87/// `methods::register`, `crate::session::protocol::register`, and
88/// `crate::task::protocol::register` on them, and returns both.
89/// Test: `run_stdio_router_recognises_proof_of_life_methods`,
90/// `build_router_wires_session_methods`, `build_router_wires_task_run`.
91pub fn build_router(project: PathBuf) -> (Router, Arc<SessionRegistry>) {
92    let sessions = Arc::new(SessionRegistry::new());
93    let agents_dir = locate_agents_dir(&project);
94    let mut router = Router::new();
95    methods::register(&mut router);
96    crate::session::protocol::register(&mut router, sessions.clone());
97    crate::task::protocol::register(&mut router, sessions.clone(), project, agents_dir);
98    (router, sessions)
99}
100
101/// Run `tcode serve --stdio` to completion.
102///
103/// Why: the top-level entry point `main.rs` calls for the `serve --stdio`
104/// subcommand.
105/// What: builds the router, logs start/stop to stderr, and enters
106/// [`transport::run_stdio_loop`], returning when it returns (stdin EOF or
107/// SIGTERM/SIGINT). On return, calls `SessionRegistry::shutdown_executions`
108/// (bounded by [`SHUTDOWN_GRACE`]) so an in-flight `task.run` gets a chance
109/// to unwind before the process exits.
110/// Test: `run_stdio_router_recognises_proof_of_life_methods` covers the
111/// router assembly; the transport loop itself is covered by
112/// `transport::tests`.
113pub async fn run_stdio(project: PathBuf) -> Result<()> {
114    info!(project = %project.display(), "tcode serve --stdio: starting");
115    let (router, sessions) = build_router(project);
116    transport::run_stdio_loop(router).await?;
117    sessions.shutdown_executions(SHUTDOWN_GRACE).await;
118    info!("tcode serve --stdio: stopped");
119    Ok(())
120}
121
122/// Run `tcode serve --http` to completion.
123///
124/// Why: the top-level entry point `main.rs` calls for the `serve --http`
125/// subcommand.
126/// What: builds the router + session registry, logs start/stop to stderr,
127/// and enters [`http::run_http`] bound to `port` (`0` = OS-assigned
128/// ephemeral port), returning when it returns (SIGTERM/SIGINT). On return,
129/// calls `SessionRegistry::shutdown_executions` (bounded by
130/// [`SHUTDOWN_GRACE`]) — see [`run_stdio`]'s docs for why.
131/// Test: `run_stdio_router_recognises_proof_of_life_methods` covers the
132/// shared router assembly; `http::tests` cover the routing/dispatch logic.
133pub async fn run_http(project: PathBuf, port: u16) -> Result<()> {
134    info!(project = %project.display(), port, "tcode serve --http: starting");
135    let (router, sessions) = build_router(project);
136    http::run_http(router, sessions.clone(), port).await?;
137    sessions.shutdown_executions(SHUTDOWN_GRACE).await;
138    info!("tcode serve --http: stopped");
139    Ok(())
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use serde_json::json;
146    use trusty_common::mcp::Request;
147
148    fn test_ctx() -> crate::jsonrpc::ConnectionContext {
149        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
150        crate::jsonrpc::ConnectionContext::new(tx)
151    }
152
153    /// `build_router` must recognise both proof-of-life methods.
154    #[tokio::test]
155    async fn run_stdio_router_recognises_proof_of_life_methods() {
156        let project = tempfile::tempdir().expect("project tempdir");
157        let (router, _sessions) = build_router(project.path().to_path_buf());
158        for method in ["ping", "health"] {
159            let req = Request {
160                jsonrpc: Some("2.0".to_string()),
161                id: Some(json!(1)),
162                method: method.to_string(),
163                params: None,
164            };
165            let resp = router.dispatch(req, &test_ctx()).await;
166            assert!(
167                resp.error.is_none(),
168                "{method} must be registered, got {:?}",
169                resp.error
170            );
171        }
172    }
173
174    /// `build_router` must also wire every `session.*` method (#2054),
175    /// sharing the registry it returns.
176    #[tokio::test]
177    async fn build_router_wires_session_methods() {
178        let project = tempfile::tempdir().expect("project tempdir");
179        let (router, sessions) = build_router(project.path().to_path_buf());
180        let session = sessions.create("t".to_string(), None, None);
181
182        let req = Request {
183            jsonrpc: Some("2.0".to_string()),
184            id: Some(json!(1)),
185            method: "session.status".to_string(),
186            params: Some(json!({"session_id": session.id})),
187        };
188        let resp = router.dispatch(req, &test_ctx()).await;
189        assert!(
190            resp.error.is_none(),
191            "session.status must be registered, got {:?}",
192            resp.error
193        );
194        assert_eq!(resp.result.unwrap()["id"], session.id);
195    }
196
197    /// `DEFAULT_HTTP_PORT` must stay the documented value (7881) so a
198    /// change is a deliberate edit to both the constant and its doc comment,
199    /// not an accidental drift.
200    #[test]
201    fn default_http_port_is_documented_value() {
202        assert_eq!(DEFAULT_HTTP_PORT, 7881);
203    }
204
205    /// `build_router` must also wire `task.run` (#2056).
206    #[tokio::test]
207    async fn build_router_wires_task_run() {
208        let project = tempfile::tempdir().expect("project tempdir");
209        std::fs::create_dir_all(project.path().join(".claude").join("agents")).expect("mkdir");
210        std::fs::write(
211            project
212                .path()
213                .join(".claude")
214                .join("agents")
215                .join("pm.toml"),
216            "[agent]\nname = \"pm\"\nmodel = \"openai/gpt-4o-mini\"\n[system_prompt]\ncontent = \"PM\"\n",
217        )
218        .expect("write pm.toml");
219        std::fs::write(
220            project
221                .path()
222                .join(".claude")
223                .join("agents")
224                .join("python-engineer.toml"),
225            "[agent]\nname = \"python-engineer\"\nmodel = \"deepseek/deepseek-chat\"\n[system_prompt]\ncontent = \"eng\"\n",
226        )
227        .expect("write python-engineer.toml");
228
229        // SAFETY: test-only env mutation; serialized by the shared crate lock.
230        let _guard = crate::task::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
231        unsafe {
232            std::env::set_var(
233                crate::task::mock_llm::MOCK_LLM_ENV,
234                crate::task::mock_llm::MOCK_LLM_ECHO,
235            );
236        }
237        let (router, sessions) = build_router(project.path().to_path_buf());
238        let req = Request {
239            jsonrpc: Some("2.0".to_string()),
240            id: Some(json!(1)),
241            method: "task.run".to_string(),
242            params: Some(json!({"task_description": "say hi"})),
243        };
244        let resp = router.dispatch(req, &test_ctx()).await;
245        sessions
246            .shutdown_executions(std::time::Duration::from_secs(5))
247            .await;
248        unsafe {
249            std::env::remove_var(crate::task::mock_llm::MOCK_LLM_ENV);
250        }
251
252        assert!(
253            resp.error.is_none(),
254            "task.run must be registered, got {:?}",
255            resp.error
256        );
257        assert_eq!(resp.result.unwrap()["status"], "running");
258    }
259}