Skip to main content

trusty_code/jsonrpc/
error.rs

1//! Typed JSON-RPC error returned by [`super::router::MethodHandler`] impls.
2//!
3//! Why: handlers need a lightweight, typed way to signal a specific JSON-RPC
4//! error code (invalid params, internal error, …) without the router having
5//! to string-sniff an `anyhow::Error`. Centralising the constructors here
6//! means every handler produces spec-correct codes by construction.
7//! What: `RpcError { code, message, data }` plus constructors for the
8//! standard JSON-RPC 2.0 codes a handler is expected to return itself, and
9//! (#2054) the vision spec's domain error taxonomy (§13.2) — an
10//! *additive* layer of application-specific codes carried in the same
11//! envelope, each tagged with `data.error_type` so clients can match on a
12//! stable string rather than a numeric code alone. `-32601 Method not
13//! found` and `-32600 Invalid Request` are produced by
14//! [`super::router::Router`] before a handler is ever invoked, so they are
15//! intentionally not exposed as constructors here — a handler has no
16//! legitimate reason to fabricate either.
17//! Test: this module's unit tests.
18
19use serde_json::{Value, json};
20use trusty_mcp::error_codes;
21
22/// A JSON-RPC 2.0 error, as returned by a method handler.
23///
24/// Why: mirrors `trusty_mcp::JsonRpcError`'s shape so the router can
25/// convert one into the other with a straight field copy, but stays a
26/// separate type so handler code never has to construct the wire envelope
27/// directly.
28/// What: `code` is a JSON-RPC error code (spec-defined or application
29/// range); `message` is human-readable; `data` is optional structured detail
30/// attached to the wire error.
31/// Test: `rpc_error_invalid_params_sets_code`, `rpc_error_internal_sets_code`.
32#[derive(Debug, Clone)]
33pub struct RpcError {
34    pub code: i32,
35    pub message: String,
36    pub data: Option<Value>,
37}
38
39impl RpcError {
40    /// Construct an `RpcError` with an arbitrary code.
41    ///
42    /// Why: escape hatch for application-defined codes outside the standard
43    /// JSON-RPC range (e.g. a future domain-specific error).
44    /// What: sets `code`/`message`, leaves `data` unset.
45    /// Test: `rpc_error_new_has_no_data_by_default`.
46    pub fn new(code: i32, message: impl Into<String>) -> Self {
47        Self {
48            code,
49            message: message.into(),
50            data: None,
51        }
52    }
53
54    /// Attach structured `data` to an existing error.
55    ///
56    /// Why: some failures carry machine-readable detail (e.g. which field
57    /// failed validation) beyond the human-readable `message`.
58    /// What: builder-style setter; returns `self` for chaining.
59    /// Test: `rpc_error_with_data_attaches_payload`.
60    pub fn with_data(mut self, data: Value) -> Self {
61        self.data = Some(data);
62        self
63    }
64
65    /// Build a `-32602 Invalid params` error.
66    ///
67    /// Why: the standard code a handler returns when it cannot parse or
68    /// validate its `params` argument.
69    /// What: `code = error_codes::INVALID_PARAMS`.
70    /// Test: `rpc_error_invalid_params_sets_code`.
71    pub fn invalid_params(message: impl Into<String>) -> Self {
72        Self::new(error_codes::INVALID_PARAMS, message)
73    }
74
75    /// Build a `-32603 Internal error` error.
76    ///
77    /// Why: the standard code for a handler-side failure that isn't the
78    /// caller's fault (I/O failure, downstream panic-free error, etc.).
79    /// What: `code = error_codes::INTERNAL_ERROR`.
80    /// Test: `rpc_error_internal_sets_code`.
81    pub fn internal(message: impl Into<String>) -> Self {
82        Self::new(error_codes::INTERNAL_ERROR, message)
83    }
84
85    /// Build a domain-taxonomy error (vision spec §13.2): a code from the
86    /// spec's table plus a stable `error_type` string tagged onto `data`.
87    ///
88    /// Why: the spec's domain errors (`session_not_found`, `invalid_argument`,
89    /// `cancelled`, …) live in a numeric range distinct from the standard
90    /// JSON-RPC `-326xx` codes, and every one of them carries
91    /// `data.error_type` so a client can match on the string rather than
92    /// memorising numbers. Centralising the shape here means every domain
93    /// error is built the same way.
94    /// What: sets `code`, `message`, and `data = {"error_type": error_type}`.
95    /// Test: `rpc_error_domain_sets_error_type_in_data`.
96    fn domain(code: i32, error_type: &'static str, message: impl Into<String>) -> Self {
97        Self::new(code, message).with_data(json!({"error_type": error_type}))
98    }
99
100    /// Build a `-32007 session_not_found` error (vision spec §13.2).
101    ///
102    /// Why: the specific, spec-named code for "the session id in `params`
103    /// does not exist in the registry" — used by every `session.*` method
104    /// that takes a `session_id`.
105    /// What: `message` embeds `session_id` for operator-visible logs;
106    /// `data.error_type = "session_not_found"`.
107    /// Test: `rpc_error_session_not_found_sets_code_and_type`.
108    pub fn session_not_found(session_id: &str) -> Self {
109        Self::domain(
110            -32007,
111            "session_not_found",
112            format!("session not found: {session_id}"),
113        )
114    }
115
116    /// Build a `-32002 not_found` error (vision spec §13.2).
117    ///
118    /// Why: the spec's general "the thing you named does not exist" code,
119    /// distinct from the session-specific `-32007 session_not_found` — used by
120    /// methods whose subject is not a session (e.g. `fs.list_dir` on a path
121    /// that isn't there).
122    /// What: `data.error_type = "not_found"`.
123    /// Test: `rpc_error_not_found_sets_code_and_type`.
124    pub fn not_found(message: impl Into<String>) -> Self {
125        Self::domain(-32002, "not_found", message)
126    }
127
128    /// Build a `-32001 permission_denied` error (vision spec §13.2).
129    ///
130    /// Why: the spec's "caller lacks permission" code. tcode adds no permission
131    /// layer of its own — it runs as the user with the user's entitlements — so
132    /// this reports an OS-level refusal (e.g. an unreadable directory) rather
133    /// than a policy decision tcode made.
134    /// What: `data.error_type = "permission_denied"`.
135    /// Test: `rpc_error_permission_denied_sets_code_and_type`.
136    pub fn permission_denied(message: impl Into<String>) -> Self {
137        Self::domain(-32001, "permission_denied", message)
138    }
139
140    /// Build a `-32003 invalid_argument` error (vision spec §13.2).
141    ///
142    /// Why: the spec's domain-level "malformed request" code, distinct from
143    /// the JSON-RPC protocol-level `-32602 Invalid params` — used when a
144    /// method's arguments parse as JSON but fail a semantic check (e.g. an
145    /// empty task description).
146    /// What: `data.error_type = "invalid_argument"`.
147    /// Test: `rpc_error_invalid_argument_sets_code_and_type`.
148    pub fn invalid_argument(message: impl Into<String>) -> Self {
149        Self::domain(-32003, "invalid_argument", message)
150    }
151
152    /// Build a `-32008 active_conflict` error (DOC-48 §5.2/§6.1, issue #3294).
153    ///
154    /// Why: `workstream.activate{id, force: false}` must fail when a
155    /// DIFFERENT workstream is already active, and the caller needs the
156    /// currently-active id to decide whether to retry with `force: true`
157    /// (§6.1: "the error includes the ID of the currently-active
158    /// workstream"). `-32008` is the next free slot after `-32007
159    /// session_not_found` in this crate's domain-error range — DOC-48
160    /// predates no reservation for it in the vision spec's §13.2 table, so
161    /// it is allocated here rather than colliding with the reserved-but-
162    /// unimplemented `-32004`/`-32005`/`-32006` (`timeout`/`cancelled`/
163    /// `provider_failure`).
164    /// What: `data = {"error_type": "active_conflict", "active_id": <uuid
165    /// string>}` — `active_id` rides alongside the standard `error_type` tag
166    /// so a client can read the conflicting id without re-parsing `message`.
167    /// Test: `rpc_error_active_conflict_sets_code_and_active_id`.
168    pub fn active_conflict(active_id: impl std::fmt::Display) -> Self {
169        let active_id = active_id.to_string();
170        Self::new(-32008, format!("another workstream is active: {active_id}"))
171            .with_data(json!({"error_type": "active_conflict", "active_id": active_id}))
172    }
173
174    /// Build a `-32009 already_exists` error (issue #3449).
175    ///
176    /// Why: `agents.create`/`skills.create` must refuse to overwrite an
177    /// existing disk entry, and that conflict needs its OWN code — an early
178    /// cut reused the literal `-32008`, but that slot is
179    /// [`Self::active_conflict`]'s (DOC-48 §5.2, constructor-backed, and
180    /// asserted on numerically by the workstreams tests), so sharing it
181    /// would make the two semantically different conflicts
182    /// indistinguishable to a client matching on code (code-critic PR #3465
183    /// review, LOW). `-32009` is the next free slot after it.
184    /// What: `data.error_type = "already_exists"`. The REST layer maps this
185    /// to `409 Conflict` (`serve::rest::rpc_error_to_status`), same HTTP
186    /// status as `active_conflict` — the distinction lives in the JSON-RPC
187    /// code/`error_type`, where protocol clients look.
188    /// Test: `rpc_error_already_exists_sets_code_and_type`.
189    pub fn already_exists(message: impl Into<String>) -> Self {
190        Self::domain(-32009, "already_exists", message)
191    }
192
193    /// Build a `-32010 cancel_unconfirmed` error (#8207).
194    ///
195    /// Why: `session.cancel` blocks until the signalled run has actually
196    /// stopped, and the run that does not stop in time is NOT an internal
197    /// fault — it is "still cancelling", the one answer a client can act on by
198    /// staying in a cancelling state instead of reporting a daemon bug. The
199    /// `-32603 internal` this replaces made the two indistinguishable. The
200    /// numeric code carries the distinction on its own, and the `error_type`
201    /// tag also reaches socket clients: the `From` conversion onto
202    /// [`trusty_common::uds::server::RpcError`] carries `data` across.
203    /// What: `data.error_type = "cancel_unconfirmed"`. `-32010` is the next
204    /// free slot after [`Self::already_exists`]'s `-32009`.
205    ///
206    /// The three consumers in this repo: `crate::serve::rest::rpc_error_to_status`
207    /// and `trusty_code_gui::bridge::BridgeError::status` map it to HTTP 503 —
208    /// "not yet, retry", distinct from the 500 both used to send — and
209    /// `crate::tui_client::CodeEngine::cancel_session_outcome` returns it as
210    /// `CancelOutcome::StillCancelling`. The TUI's own "still cancelling…" render
211    /// on top of that outcome is `trusty-code-tui`'s, and is not in this crate.
212    /// Test: `rpc_error_cancel_unconfirmed_sets_code_and_type`.
213    pub fn cancel_unconfirmed(message: impl Into<String>) -> Self {
214        Self::domain(-32010, "cancel_unconfirmed", message)
215    }
216}
217
218impl std::fmt::Display for RpcError {
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        write!(f, "JSON-RPC error {}: {}", self.code, self.message)
221    }
222}
223
224impl std::error::Error for RpcError {}
225
226/// Carry this crate's error onto the UDS transport's error type (#6637).
227///
228/// Why: `crate::serve::uds` answers over `trusty_common::uds::server`, whose
229/// frames carry that crate's `RpcError`. Converting here — once, beside the
230/// codes it converts — keeps the socket transport from inventing a second
231/// mapping, and keeps the code the caller reads identical to the one the same
232/// method reports over STDIO or HTTP.
233/// What: widens `code` to `i64` and keeps `message` verbatim. `data` is carried
234/// through with `with_data` when present (#6285).
235/// Test: `rpc_error_converts_onto_the_uds_transport_error`.
236impl From<RpcError> for trusty_common::uds::server::RpcError {
237    fn from(err: RpcError) -> Self {
238        let converted = Self::new(i64::from(err.code), err.message);
239        match err.data {
240            Some(data) => converted.with_data(data),
241            None => converted,
242        }
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use serde_json::json;
250
251    /// `invalid_params` must use the spec's `-32602` code.
252    #[test]
253    fn rpc_error_invalid_params_sets_code() {
254        let e = RpcError::invalid_params("bad shape");
255        assert_eq!(e.code, error_codes::INVALID_PARAMS);
256        assert_eq!(e.message, "bad shape");
257        assert!(e.data.is_none());
258    }
259
260    /// `internal` must use the spec's `-32603` code.
261    #[test]
262    fn rpc_error_internal_sets_code() {
263        let e = RpcError::internal("boom");
264        assert_eq!(e.code, error_codes::INTERNAL_ERROR);
265        assert_eq!(e.message, "boom");
266    }
267
268    /// `new` alone must not attach any `data`.
269    #[test]
270    fn rpc_error_new_has_no_data_by_default() {
271        let e = RpcError::new(-1, "custom");
272        assert_eq!(e.code, -1);
273        assert!(e.data.is_none());
274    }
275
276    /// `with_data` must attach the supplied payload.
277    #[test]
278    fn rpc_error_with_data_attaches_payload() {
279        let e = RpcError::invalid_params("bad field").with_data(json!({"field": "name"}));
280        assert_eq!(e.data, Some(json!({"field": "name"})));
281    }
282
283    /// `Display` must surface both the code and the message for logs.
284    #[test]
285    fn rpc_error_display_contains_code_and_message() {
286        let e = RpcError::internal("db unreachable");
287        let s = e.to_string();
288        assert!(s.contains("-32603"));
289        assert!(s.contains("db unreachable"));
290    }
291
292    /// `session_not_found` must use the spec's `-32007` code, embed the id
293    /// in the message, and tag `error_type` in `data`.
294    #[test]
295    fn rpc_error_session_not_found_sets_code_and_type() {
296        let e = RpcError::session_not_found("s-123");
297        assert_eq!(e.code, -32007);
298        assert!(e.message.contains("s-123"));
299        assert_eq!(e.data, Some(json!({"error_type": "session_not_found"})));
300    }
301
302    /// `not_found` must use the spec's `-32002` code and tag `error_type`.
303    #[test]
304    fn rpc_error_not_found_sets_code_and_type() {
305        let e = RpcError::not_found("path not found: /x");
306        assert_eq!(e.code, -32002);
307        assert_eq!(e.data, Some(json!({"error_type": "not_found"})));
308    }
309
310    /// `permission_denied` must use the spec's `-32001` code and tag
311    /// `error_type`.
312    #[test]
313    fn rpc_error_permission_denied_sets_code_and_type() {
314        let e = RpcError::permission_denied("permission denied: /x");
315        assert_eq!(e.code, -32001);
316        assert_eq!(e.data, Some(json!({"error_type": "permission_denied"})));
317    }
318
319    /// `invalid_argument` must use the spec's `-32003` code and tag
320    /// `error_type` in `data`.
321    #[test]
322    fn rpc_error_invalid_argument_sets_code_and_type() {
323        let e = RpcError::invalid_argument("task must not be empty");
324        assert_eq!(e.code, -32003);
325        assert_eq!(e.data, Some(json!({"error_type": "invalid_argument"})));
326    }
327
328    /// `active_conflict` must use `-32008`, tag `error_type`, and carry the
329    /// conflicting `active_id` in `data` (DOC-48 §6.1).
330    #[test]
331    fn rpc_error_active_conflict_sets_code_and_active_id() {
332        let e = RpcError::active_conflict("a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b");
333        assert_eq!(e.code, -32008);
334        assert!(e.message.contains("a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b"));
335        assert_eq!(
336            e.data,
337            Some(json!({
338                "error_type": "active_conflict",
339                "active_id": "a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b",
340            }))
341        );
342    }
343
344    /// `already_exists` must use `-32009` — its OWN slot, distinct from
345    /// `active_conflict`'s `-32008` (code-critic PR #3465 review, LOW).
346    #[test]
347    fn rpc_error_already_exists_sets_code_and_type() {
348        let e = RpcError::already_exists("agent 'dup' already exists on disk");
349        assert_eq!(e.code, -32009);
350        assert_ne!(e.code, RpcError::active_conflict("x").code);
351        assert_eq!(e.data, Some(json!({"error_type": "already_exists"})));
352    }
353
354    /// `cancel_unconfirmed` must use `-32010` — its OWN slot, distinguishable
355    /// from a genuine `-32603 internal` fault (#8207).
356    #[test]
357    fn rpc_error_cancel_unconfirmed_sets_code_and_type() {
358        let e = RpcError::cancel_unconfirmed("session s-1: still cancelling");
359        assert_eq!(e.code, -32010);
360        assert_ne!(e.code, RpcError::internal("x").code);
361        assert_eq!(e.data, Some(json!({"error_type": "cancel_unconfirmed"})));
362    }
363
364    /// #8207: the `-32010` code survives the UDS conversion, so a socket
365    /// client can match on it without reading `data` (which is also carried).
366    #[test]
367    fn cancel_unconfirmed_stays_distinguishable_across_the_uds_transport() {
368        let converted: trusty_common::uds::server::RpcError =
369            RpcError::cancel_unconfirmed("still cancelling").into();
370        assert_eq!(converted.code, -32010);
371    }
372
373    /// #6637: the socket transport must report the SAME code and message a
374    /// caller would have read over STDIO or HTTP.
375    #[test]
376    fn rpc_error_converts_onto_the_uds_transport_error() {
377        let converted: trusty_common::uds::server::RpcError =
378            RpcError::session_not_found("sess-1").into();
379        assert_eq!(
380            converted.code,
381            i64::from(RpcError::session_not_found("sess-1").code)
382        );
383        assert!(converted.message.contains("sess-1"));
384        assert_eq!(
385            converted.data,
386            RpcError::session_not_found("sess-1").data,
387            "domain `error_type` data must survive the conversion"
388        );
389
390        // #6285: `data` must survive the conversion when present.
391        let with_data: trusty_common::uds::server::RpcError = RpcError::invalid_params("bad")
392            .with_data(json!({"field": "x"}))
393            .into();
394        assert_eq!(with_data.data, Some(json!({"field": "x"})));
395    }
396}