trusty_code/cli_client/stdio.rs
1//! [`StdioRpcClient`]: a JSON-RPC 2.0 client speaking NDJSON over a spawned
2//! `tcode serve --stdio` child's stdio pipes (#2060).
3//!
4//! Why: the CLI needs to drive the daemon's `session.*`/`task.*` methods
5//! without reimplementing any of their logic. Spawning an ephemeral child
6//! per invocation (rather than discovering/reusing a long-lived daemon) is
7//! the simplest robust M1 approach the ticket calls for — no discovery file,
8//! no port, no lifecycle management beyond this one process's lifetime.
9//! What: [`StdioRpcClient::spawn`] launches the child; [`StdioRpcClient::call`]
10//! sends a request and blocks (bounded by [`DEFAULT_CALL_TIMEOUT`]) for its
11//! matching response, buffering any interleaved `session.event` notification
12//! lines rather than dropping them; [`StdioRpcClient::next_notification`]
13//! drains that buffer (or reads fresh lines, bounded by a caller-supplied
14//! wait) for the streaming subcommands (`attach`, `run-task`).
15//! [`classify_notification`]/[`build_request`] are pure helpers, unit tested
16//! here without spawning a real process; the full spawn+wire round trip is
17//! covered by `tests/cli_e2e.rs` against the real `tcode` binary.
18//! Test: `cli_client::stdio::tests::*`.
19
20use std::collections::VecDeque;
21use std::path::Path;
22use std::process::Stdio;
23use std::time::Duration;
24
25use serde_json::Value;
26use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
27use tokio::process::{Child, ChildStdin, ChildStdout};
28use tokio::time::timeout;
29use trusty_mcp::Request;
30
31use crate::events::SessionEventEnvelope;
32
33/// How long [`StdioRpcClient::call`] waits for a matching response before
34/// giving up.
35///
36/// Why: every method this client calls (`session.*`, `task.run`) is a fast,
37/// synchronous handler by design — `task.run` in particular reserves its
38/// execution slot and returns immediately rather than blocking on the LLM
39/// run (see `task::protocol::task_run`'s docs) — so a real hang here means a
40/// genuine daemon-side regression, not a slow-but-legitimate call. Generous
41/// enough for a debug build under load, tight enough to fail fast.
42pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(15);
43
44/// Errors a CLI subcommand handler surfaces to the user (mapped onto a
45/// nonzero exit code by the caller — this type carries no exit-code opinion
46/// itself).
47#[derive(Debug, thiserror::Error)]
48pub enum RpcClientError {
49 /// The child process could not be spawned at all (binary missing, not
50 /// executable, etc.).
51 #[error("failed to spawn `{0}`: {1}")]
52 Spawn(String, #[source] std::io::Error),
53 /// The child's stdout closed (process exited) before a full response
54 /// arrived.
55 #[error("daemon connection closed unexpectedly")]
56 ConnectionClosed,
57 /// A read/write against the child's stdio pipes failed.
58 #[error("failed to read from daemon: {0}")]
59 Io(#[source] std::io::Error),
60 /// A line on the wire was not valid JSON, or lacked fields a response
61 /// must have.
62 #[error("malformed response from daemon: {0}")]
63 MalformedResponse(String),
64 /// The daemon's JSON-RPC error envelope for this call (verbatim: code +
65 /// message + optional `data`).
66 #[error("daemon returned an error ({code}): {message}")]
67 Rpc {
68 code: i32,
69 message: String,
70 data: Option<Value>,
71 },
72 /// No matching response arrived within [`DEFAULT_CALL_TIMEOUT`].
73 #[error("timed out waiting for the daemon to respond")]
74 Timeout,
75}
76
77/// Build the outgoing JSON-RPC 2.0 request envelope for one call.
78///
79/// Why: split out so `next_id` bookkeeping and wire-envelope construction
80/// are each independently, purely testable — no process I/O involved.
81/// What: `jsonrpc: "2.0"`, `id` as a JSON number, `method`/`params` verbatim.
82/// Test: `tests::build_request_uses_2_0_and_given_id`.
83fn build_request(id: i64, method: &str, params: Value) -> Request {
84 Request {
85 jsonrpc: Some("2.0".to_string()),
86 id: Some(serde_json::json!(id)),
87 method: method.to_string(),
88 params: Some(params),
89 }
90}
91
92/// Classify one already-JSON-parsed wire line as a `session.event`
93/// notification, if it is one.
94///
95/// Why: the daemon interleaves request/response traffic with
96/// server-initiated `session.event` notifications on the SAME connection
97/// (see `session::registry`'s attach-forwarding docs); every line this
98/// client reads must be checked against both shapes.
99/// What: `Some(envelope)` when `value.method == "session.event"` and
100/// `value.params` deserialises as a [`SessionEventEnvelope`]; `None`
101/// otherwise (including a shape that claims to be a notification but fails
102/// to parse — degrade silently rather than error, matching `Event`'s own
103/// "unknown variants are ignored" forward-compatibility stance).
104/// Test: `tests::classify_notification_recognises_session_event`,
105/// `tests::classify_notification_ignores_other_shapes`.
106fn classify_notification(value: &Value) -> Option<SessionEventEnvelope> {
107 if value.get("method").and_then(|m| m.as_str()) != Some("session.event") {
108 return None;
109 }
110 serde_json::from_value(value.get("params")?.clone()).ok()
111}
112
113/// A JSON-RPC 2.0 client over a spawned `tcode serve --stdio` child.
114///
115/// Why: see module docs.
116/// What: owns the child + its stdin/stdout handles and a monotonic request
117/// id counter; buffers notification lines encountered while a `call` is
118/// awaiting its own response so nothing observed on the wire is ever
119/// silently dropped.
120/// Test: `tests::*` for the pure helpers; `tests/cli_e2e.rs` for the real
121/// spawn + wire round trip.
122pub struct StdioRpcClient {
123 child: Child,
124 stdin: ChildStdin,
125 lines: Lines<BufReader<ChildStdout>>,
126 next_id: i64,
127 pending_notifications: VecDeque<SessionEventEnvelope>,
128}
129
130impl StdioRpcClient {
131 /// Spawn `<tcode_exe> serve --project <project> --stdio` and return a
132 /// client wired to its stdio pipes.
133 ///
134 /// Why: `tcode_exe` is normally `std::env::current_exe()` — the CLI
135 /// re-spawns ITSELF in daemon mode, per the ticket's "in-process spawn"
136 /// requirement; passing it explicitly (rather than hardcoding
137 /// `current_exe()` inside this function) keeps this module testable
138 /// with an arbitrary binary path and avoids a hidden `std::env` read
139 /// inside library code.
140 /// What: `kill_on_drop(true)` so a CLI process that exits early (panic,
141 /// early return) never leaks the child; the child's stderr is
142 /// inherited so daemon-side log lines are visible to the operator
143 /// without corrupting the stdout NDJSON framing this client reads.
144 /// Test: `tests/cli_e2e.rs` (spawns the real binary).
145 pub fn spawn(tcode_exe: &Path, project: &Path) -> Result<Self, RpcClientError> {
146 let mut child = tokio::process::Command::new(tcode_exe)
147 .arg("serve")
148 .arg("--project")
149 .arg(project)
150 .arg("--stdio")
151 .stdin(Stdio::piped())
152 .stdout(Stdio::piped())
153 .stderr(Stdio::inherit())
154 .kill_on_drop(true)
155 .spawn()
156 .map_err(|e| RpcClientError::Spawn(tcode_exe.display().to_string(), e))?;
157 let stdin = child.stdin.take().ok_or(RpcClientError::ConnectionClosed)?;
158 let stdout = child
159 .stdout
160 .take()
161 .ok_or(RpcClientError::ConnectionClosed)?;
162 Ok(Self {
163 child,
164 stdin,
165 lines: BufReader::new(stdout).lines(),
166 next_id: 1,
167 pending_notifications: VecDeque::new(),
168 })
169 }
170
171 /// Call `method` with `params`, waiting for its matching response.
172 ///
173 /// Why: the request/response half of the protocol every non-streaming
174 /// subcommand (`session.list`/`status`/`cancel`/`get_transcript`,
175 /// `task.run`'s initial call) uses.
176 /// What: writes one NDJSON request line, then reads lines until one
177 /// carries the SAME `id` — any `session.event` notification observed
178 /// along the way is buffered (not dropped) for a later
179 /// [`Self::next_notification`] call. A JSON-RPC error envelope becomes
180 /// `Err(RpcClientError::Rpc)`; the whole call is bounded by
181 /// [`DEFAULT_CALL_TIMEOUT`].
182 /// Test: covered end-to-end by `tests/cli_e2e.rs`.
183 pub async fn call(&mut self, method: &str, params: Value) -> Result<Value, RpcClientError> {
184 timeout(DEFAULT_CALL_TIMEOUT, self.call_inner(method, params))
185 .await
186 .map_err(|_| RpcClientError::Timeout)?
187 }
188
189 async fn call_inner(&mut self, method: &str, params: Value) -> Result<Value, RpcClientError> {
190 let id = self.next_id;
191 self.next_id += 1;
192 let req = build_request(id, method, params);
193 let mut line = serde_json::to_string(&req)
194 .map_err(|e| RpcClientError::MalformedResponse(e.to_string()))?;
195 line.push('\n');
196 self.stdin
197 .write_all(line.as_bytes())
198 .await
199 .map_err(RpcClientError::Io)?;
200 self.stdin.flush().await.map_err(RpcClientError::Io)?;
201
202 loop {
203 let raw = self.read_raw_line().await?;
204 let value: Value = serde_json::from_str(&raw)
205 .map_err(|e| RpcClientError::MalformedResponse(format!("{e}: {raw}")))?;
206
207 if value.get("id").and_then(Value::as_i64) == Some(id) {
208 if let Some(err) = value.get("error").filter(|e| !e.is_null()) {
209 return Err(RpcClientError::Rpc {
210 code: err.get("code").and_then(Value::as_i64).unwrap_or(0) as i32,
211 message: err
212 .get("message")
213 .and_then(|m| m.as_str())
214 .unwrap_or_default()
215 .to_string(),
216 data: err.get("data").cloned(),
217 });
218 }
219 return Ok(value.get("result").cloned().unwrap_or(Value::Null));
220 }
221
222 if let Some(envelope) = classify_notification(&value) {
223 self.pending_notifications.push_back(envelope);
224 }
225 // Any other stray line (e.g. a response to an id we no longer
226 // care about) is silently ignored — this client only ever has
227 // one call in flight at a time.
228 }
229 }
230
231 /// Return the next observed `session.event` notification, waiting up to
232 /// `wait` for a fresh one if none is already buffered.
233 ///
234 /// Why: the streaming subcommands (`attach`, `run-task`) poll this in a
235 /// loop, printing each envelope as it arrives, until a terminal event or
236 /// the user interrupts.
237 /// What: drains [`Self::pending_notifications`] first (events observed
238 /// while a previous `call` was still awaiting its own response); only
239 /// reads fresh lines from the child when the buffer is empty.
240 /// `Ok(None)` means "nothing arrived within `wait`" — NOT connection
241 /// loss (that is `Err(ConnectionClosed)`) — callers should keep polling.
242 /// Test: covered end-to-end by `tests/cli_e2e.rs`.
243 pub async fn next_notification(
244 &mut self,
245 wait: Duration,
246 ) -> Result<Option<SessionEventEnvelope>, RpcClientError> {
247 if let Some(envelope) = self.pending_notifications.pop_front() {
248 return Ok(Some(envelope));
249 }
250 match timeout(wait, self.read_raw_line()).await {
251 Ok(Ok(raw)) => {
252 let value: Value = serde_json::from_str(&raw)
253 .map_err(|e| RpcClientError::MalformedResponse(format!("{e}: {raw}")))?;
254 Ok(classify_notification(&value))
255 }
256 Ok(Err(e)) => Err(e),
257 Err(_) => Ok(None),
258 }
259 }
260
261 async fn read_raw_line(&mut self) -> Result<String, RpcClientError> {
262 self.lines
263 .next_line()
264 .await
265 .map_err(RpcClientError::Io)?
266 .ok_or(RpcClientError::ConnectionClosed)
267 }
268
269 /// Close stdin (EOF) and wait, bounded by `grace`, for the child to
270 /// exit cleanly; force-kills it if it doesn't.
271 ///
272 /// Why: mirrors the daemon's own connection-safe-shutdown convention
273 /// (issue #534) from the client side — the CLI should give its spawned
274 /// child a real chance to drain before the process ends.
275 /// What: dropping `stdin` signals EOF (the same trigger
276 /// `serve::run_stdio` reacts to); force-kill is best-effort, matching
277 /// every other bounded-shutdown path in this crate.
278 /// Test: covered end-to-end by `tests/cli_e2e.rs`.
279 pub async fn shutdown(mut self, grace: Duration) -> Result<(), RpcClientError> {
280 drop(self.stdin);
281 match timeout(grace, self.child.wait()).await {
282 Ok(Ok(_status)) => Ok(()),
283 Ok(Err(e)) => Err(RpcClientError::Io(e)),
284 Err(_) => {
285 let _ = self.child.start_kill();
286 Ok(())
287 }
288 }
289 }
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295 use serde_json::json;
296
297 /// `build_request` must stamp `jsonrpc: "2.0"` and the exact given id.
298 #[test]
299 fn build_request_uses_2_0_and_given_id() {
300 let req = build_request(7, "session.list", json!({}));
301 assert_eq!(req.jsonrpc.as_deref(), Some("2.0"));
302 assert_eq!(req.id, Some(json!(7)));
303 assert_eq!(req.method, "session.list");
304 }
305
306 /// A well-formed `session.event` notification must parse into its
307 /// envelope.
308 #[test]
309 fn classify_notification_recognises_session_event() {
310 let line = json!({
311 "method": "session.event",
312 "params": {
313 "session_id": "s-1",
314 "seq": 1,
315 "at": "2024-01-01T00:00:00Z",
316 "kind": "session_started",
317 "event": {"type": "session_started", "session_id": "s-1", "project": "p"},
318 }
319 });
320 let envelope = classify_notification(&line).expect("must classify as a notification");
321 assert_eq!(envelope.session_id, "s-1");
322 assert_eq!(envelope.kind, "session_started");
323 }
324
325 /// A JSON-RPC response (has an `id`, no `method`) must NOT be classified
326 /// as a notification.
327 #[test]
328 fn classify_notification_ignores_other_shapes() {
329 let response = json!({"jsonrpc": "2.0", "id": 1, "result": {}});
330 assert!(classify_notification(&response).is_none());
331
332 let other_method = json!({"method": "ping", "params": {}});
333 assert!(classify_notification(&other_method).is_none());
334
335 let malformed_params = json!({"method": "session.event", "params": {"not": "an envelope"}});
336 assert!(classify_notification(&malformed_params).is_none());
337 }
338}