Skip to main content

trusty_code/serve/rest/
mod.rs

1//! REST resource gateway over the JSON-RPC method registry (#2983, #587,
2//! Slice 1 bridge + Slice 2 `session.*` read routes).
3//!
4//! Why: the vision spec (#587) wants `tcode serve --http` to expose a
5//! conventional REST resource vocabulary (`GET /projects`, `POST
6//! /sessions`, …) alongside the existing JSON-RPC `POST /rpc` endpoint, but
7//! every one of those resources is already backed by a registered JSON-RPC
8//! method (`session.create`, `task.run`, …). Re-implementing the same
9//! business logic a second time as bespoke axum handlers would fork the two
10//! surfaces the moment either one changed — exactly the drift `trusty-code`'s
11//! `Router` was built to prevent between the STDIO and HTTP JSON-RPC
12//! transports (see `crate::jsonrpc` module docs). This module is
13//! `trusty-memory`'s "Pattern C" (`crates/trusty-memory/src/web/rpc.rs`:
14//! one shared dispatch seam, many transports) applied one layer further:
15//! a REST route handler will call [`call`] instead of building its own
16//! `Request`, so a REST resource and its JSON-RPC method twin always run
17//! the exact same handler.
18//!
19//! What: [`call`] synthesizes a JSON-RPC [`Request`] from a `method` +
20//! `params` pair and drives it through [`Router::dispatch`], unwrapping the
21//! `Response` envelope back into a plain `Result<Value, RpcError>` — the
22//! shape a REST handler wants (`?` onto an HTTP error), rather than the
23//! always-200 envelope `POST /rpc` returns. [`rpc_error_to_status`] maps an
24//! `RpcError` onto the real HTTP status a REST response should carry,
25//! deliberately diverging from `POST /rpc`'s "always 200, error in the
26//! envelope" convention — matching how `GET /sessions/{id}/events`
27//! (`crate::serve::http::session_events_sse`) already returns a real `404`
28//! for `session_not_found` rather than a 200-wrapped error. [`respond`] is
29//! the one place that glues those two together into the `Result<Json<Value>,
30//! (StatusCode, Json<Response>)>` shape every axum REST handler returns, so
31//! a route handler is never more than "extract params, call `respond`".
32//! [`throwaway_ctx`] builds the per-request [`ConnectionContext`] every REST
33//! handler needs to call [`call`] with — identical in spirit to
34//! `crate::serve::http::rpc_handler`'s own throwaway context, since a REST
35//! call is exactly as one-shot as a `POST /rpc` call.
36//!
37//! Slice 1 wired no axum routes — only this bridge. Slice 2
38//! ([`sessions`]) adds the first concrete resource group: `GET /sessions`,
39//! `GET /sessions/{id}`, `GET /sessions/{id}/transcript`,
40//! `GET /sessions/{id}/readiness`, `GET /sessions/{id}/goals`, each a thin
41//! handler calling [`respond`] against its `session.*` JSON-RPC twin.
42//! Slice 3 ([`sessions_write`]) adds the `session.*` WRITE routes:
43//! `POST /sessions`, `POST /sessions/{id}/messages`,
44//! `POST /sessions/{id}/cancel`, `PUT /sessions/{id}/goal`,
45//! `DELETE /sessions/{id}/goal`. Slice 4 ([`tasks`]) adds
46//! `POST /tasks` -> `task.run`. Slice 5 ([`fs`]) adds
47//! `GET /fs` -> `fs.list_dir`. Slice 6 ([`agents`]) adds
48//! `GET /sessions/{id}/agents` -> `session.get_agents`. Slice 7
49//! ([`search_audit`]) adds `GET /sessions/{id}/search-audit` ->
50//! `session.get_search_audit` (issue #3072). [`workstreams`] adds the full
51//! `workstream.*` surface: `POST /workstreams`, `GET /workstreams/{id}`,
52//! `GET /workstreams`, `POST /workstreams/{id}/close` (issue #3295, epic
53//! #3292) and `POST /workstreams/{id}/activate`,
54//! `POST /workstreams/{id}/deactivate` (DOC-48 §5.2/§6, issue #3294) — see
55//! its module docs for why the paths are unprefixed rather than DOC-48
56//! §5.2's literal `/api/v1/workstreams`. [`projects`] adds `GET /projects`
57//! -> `fs.list_projects` (issue #3365 — the GUI's workstream-first
58//! project-picker modal's roster data source). [`agent_catalog`]/
59//! [`skill_catalog`] (issue #3449) add the Foundry GUI's Agents/Skills
60//! management tabs' full surface — `GET`/`POST /agents`,
61//! `DELETE /agents/{name}` and the `skills` twin — over
62//! `crate::agents::protocol`/`crate::skills::protocol`; distinct from this
63//! module's own [`agents`] group (`GET /sessions/{id}/agents`, the
64//! per-session LIVE roster, unrelated to the disk/embedded catalog these two
65//! new groups manage). Every slice reuses [`respond`]/[`throwaway_ctx`]
66//! rather than reimplementing the glue.
67//!
68//! Test: `tests::*` — a success round-trip, an error round-trip, and one
69//! assertion per `rpc_error_to_status` mapping. See `sessions::tests` for
70//! the Slice 2 route-level coverage.
71
72pub mod agent_catalog;
73pub mod agents;
74pub mod fs;
75pub mod projects;
76pub mod search_audit;
77pub mod sessions;
78pub mod sessions_write;
79pub mod skill_catalog;
80pub mod tasks;
81pub mod workstreams;
82
83use axum::Json;
84use axum::http::StatusCode;
85use serde_json::Value;
86use trusty_mcp::{Request, Response, error_codes};
87
88use crate::jsonrpc::{ConnectionContext, Router, RpcError};
89
90/// Call a registered JSON-RPC method from a REST handler, in-process.
91///
92/// Why: the single seam every future REST resource handler goes through, so
93/// a REST route and its JSON-RPC method twin are provably the same code
94/// path — never two handwritten implementations of the same business logic
95/// (see module docs).
96/// What: synthesizes a `Request { jsonrpc: "2.0", id: Some(0), method,
97/// params }` — the `id` is a fixed synthetic value because a REST caller
98/// never observes it; `dispatch` never suppresses a response as long as
99/// `id` is `Some(_)` (see `Router::dispatch`'s notification rule) — calls
100/// `router.dispatch(req, ctx)`, and unwraps the `Response` envelope: `Ok`
101/// when `result` is set, `Err` reconstructing the `RpcError` from
102/// `Response::error` otherwise. If `dispatch` ever returned a `Response`
103/// with neither `result` nor `error` set — a `Router::dispatch` bug, not a
104/// caller-triggerable condition, and provably unreachable through this
105/// bridge since `call` always sets a non-`None` `id`, so `dispatch` never
106/// returns `Response::suppressed()` — this falls back to `Ok(Value::Null)`
107/// rather than panicking (no `unwrap`/`expect` in library code). That would
108/// surface as a silently-wrong 200 response, not a panic.
109/// Test: `call_success_returns_handler_result`, `call_error_returns_rpc_error`.
110pub async fn call(
111    router: &Router,
112    method: &str,
113    params: Value,
114    ctx: &ConnectionContext,
115) -> Result<Value, RpcError> {
116    let req = Request {
117        jsonrpc: Some("2.0".to_string()),
118        id: Some(Value::from(0)),
119        method: method.to_string(),
120        params: Some(params),
121    };
122    let resp = router.dispatch(req, ctx).await;
123    if let Some(err) = resp.error {
124        let mut rpc_err = RpcError::new(err.code, err.message);
125        rpc_err.data = err.data;
126        return Err(rpc_err);
127    }
128    Ok(resp.result.unwrap_or(Value::Null))
129}
130
131/// Map an [`RpcError`] onto the HTTP status a REST response should carry.
132///
133/// Why: `POST /rpc` always returns HTTP 200 with the JSON-RPC error carried
134/// in the envelope — appropriate for a JSON-RPC transport, but REST callers
135/// (and REST tooling: curl, browsers, API gateways) expect the status line
136/// itself to say "not found" / "forbidden" / etc. This mirrors the mapping
137/// `crate::serve::http::session_events_sse` already applies by hand for
138/// `session_not_found` -> 404, generalised to every domain error code
139/// `crate::jsonrpc::error::RpcError` currently defines (vision spec §13.2).
140/// What: matches on the numeric JSON-RPC error code: `-32002 not_found` ->
141/// 404, `-32001 permission_denied` -> 403, `-32003 invalid_argument` and
142/// `-32602 Invalid params` -> 400, `-32007 session_not_found` -> 404,
143/// `-32008 active_conflict` (DOC-48 §5.2, issue #3294) and `-32009
144/// already_exists` (issue #3449) -> 409, `-32603
145/// Internal error` -> 500. Any other/future code (including
146/// `-32601`/`-32600`, which a REST handler should never see because it
147/// calls `call` with a hardcoded, known-good method name) falls back to 500
148/// — an unmapped domain error is a bug to fix by adding a mapping, not a
149/// client-facing 4xx.
150/// Test: `status_mapping_*` — one case per mapped code, plus the unknown ->
151/// 500 fallback.
152pub fn rpc_error_to_status(err: &RpcError) -> axum::http::StatusCode {
153    use axum::http::StatusCode;
154
155    match err.code {
156        -32002 => StatusCode::NOT_FOUND,   // not_found
157        -32007 => StatusCode::NOT_FOUND,   // session_not_found
158        -32001 => StatusCode::FORBIDDEN,   // permission_denied
159        -32003 => StatusCode::BAD_REQUEST, // invalid_argument
160        -32008 => StatusCode::CONFLICT,    // active_conflict (DOC-48 §5.2)
161        -32009 => StatusCode::CONFLICT,    // already_exists (issue #3449)
162        c if c == error_codes::INVALID_PARAMS => StatusCode::BAD_REQUEST,
163        c if c == error_codes::INTERNAL_ERROR => StatusCode::INTERNAL_SERVER_ERROR,
164        _ => StatusCode::INTERNAL_SERVER_ERROR,
165    }
166}
167
168/// Build a throwaway [`ConnectionContext`] for a single REST call.
169///
170/// Why: every REST handler calls [`call`], which requires a
171/// `&ConnectionContext`, but a REST request is exactly as one-shot as an
172/// HTTP `POST /rpc` call — there is no live connection for a handler like
173/// `session.attach` to push notifications back to (that path is the
174/// dedicated SSE route, `crate::serve::http::session_events_sse`). Mirrors
175/// `crate::serve::http::rpc_handler`'s identical throwaway-channel
176/// construction so the two transports build a `ConnectionContext` the same
177/// way.
178/// What: a fresh `mpsc::unbounded_channel()`, receiver immediately dropped —
179/// any handler that queues a notification onto `notify` simply stops on its
180/// next send once this function returns.
181/// Test: exercised indirectly by every `sessions::tests::*` route test (a
182/// route only responds at all if its `ConnectionContext` is constructible).
183pub(crate) fn throwaway_ctx() -> ConnectionContext {
184    let (notify_tx, _notify_rx) = tokio::sync::mpsc::unbounded_channel();
185    ConnectionContext::new(notify_tx)
186}
187
188/// A REST handler's return type: the JSON-RPC result as a `Json` body on
189/// success, or a real HTTP status plus a JSON-RPC error envelope on failure.
190///
191/// Why: `(StatusCode, Json<Response>)` already implements axum's
192/// `IntoResponse` for the error arm, so every route handler can just return
193/// this type from [`respond`] without a bespoke error type.
194pub(crate) type RestResult = Result<Json<Value>, (StatusCode, Json<Response>)>;
195
196/// Call `method` through [`call`] and convert the result into a
197/// [`RestResult`] — the single glue point every Slice 2+ REST handler goes
198/// through.
199///
200/// Why: keeps route handlers themselves down to "extract path/query params,
201/// build `params`, call `respond`" with zero business logic and zero
202/// repeated error-mapping boilerplate (see module docs).
203/// What: `Ok(value)` becomes `Ok(Json(value))`; `Err(rpc_err)` becomes
204/// `Err((rpc_error_to_status(&rpc_err), Json(Response::err(None,
205/// rpc_err.code, rpc_err.message))))` — `data` is intentionally dropped from
206/// the REST envelope, matching `crate::serve::http::session_events_sse`'s
207/// existing `session_not_found` -> 404 mapping (the `id` is always `None`
208/// because a REST error response has no JSON-RPC request id to echo).
209/// Test: `sessions::tests::get_session_found_returns_200_with_session_json`,
210/// `sessions::tests::get_session_missing_returns_404_session_not_found`.
211pub(crate) async fn respond(router: &Router, method: &str, params: Value) -> RestResult {
212    call(router, method, params, &throwaway_ctx())
213        .await
214        .map(Json)
215        .map_err(|err| {
216            let status = rpc_error_to_status(&err);
217            (status, Json(Response::err(None, err.code, err.message)))
218        })
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use serde_json::json;
225    use tokio::sync::mpsc;
226
227    fn test_ctx() -> ConnectionContext {
228        let (tx, _rx) = mpsc::unbounded_channel();
229        ConnectionContext::new(tx)
230    }
231
232    fn echo_router() -> Router {
233        let mut router = Router::new();
234        router.register(
235            "echo",
236            |params: Value, _ctx: ConnectionContext| async move { Ok(params) },
237        );
238        router.register(
239            "boom.not_found",
240            |_params: Value, _ctx: ConnectionContext| async move {
241                Err(RpcError::not_found("thing not found: x"))
242            },
243        );
244        router
245    }
246
247    /// `call` on a registered method must return `Ok` with the handler's
248    /// result, unwrapped from the `Response` envelope.
249    #[tokio::test]
250    async fn call_success_returns_handler_result() {
251        let router = echo_router();
252        let result = call(&router, "echo", json!({"a": 1}), &test_ctx())
253            .await
254            .expect("echo must succeed");
255        assert_eq!(result, json!({"a": 1}));
256    }
257
258    /// `call` on a handler that returns an `RpcError` must surface that
259    /// exact error (code + message + data) as `Err`, not swallow it into
260    /// the `Ok` branch.
261    #[tokio::test]
262    async fn call_error_returns_rpc_error() {
263        let router = echo_router();
264        let err = call(&router, "boom.not_found", Value::Null, &test_ctx())
265            .await
266            .expect_err("boom.not_found must fail");
267        assert_eq!(err.code, -32002);
268        assert!(err.message.contains("thing not found"));
269        assert_eq!(err.data, Some(json!({"error_type": "not_found"})));
270    }
271
272    /// `call` on an unknown method must surface `-32601 Method not found`
273    /// like any other `Router::dispatch` caller — `call` does not swallow
274    /// or re-map dispatcher-level errors, only handler-level ones.
275    #[tokio::test]
276    async fn call_unknown_method_returns_method_not_found() {
277        let router = echo_router();
278        let err = call(&router, "does.not.exist", Value::Null, &test_ctx())
279            .await
280            .expect_err("unknown method must fail");
281        assert_eq!(err.code, error_codes::METHOD_NOT_FOUND);
282    }
283
284    /// Every currently-mapped `RpcError` code must resolve to its documented
285    /// HTTP status.
286    #[test]
287    fn status_mapping_not_found_is_404() {
288        assert_eq!(
289            rpc_error_to_status(&RpcError::not_found("x")),
290            axum::http::StatusCode::NOT_FOUND
291        );
292    }
293
294    #[test]
295    fn status_mapping_session_not_found_is_404() {
296        assert_eq!(
297            rpc_error_to_status(&RpcError::session_not_found("s-1")),
298            axum::http::StatusCode::NOT_FOUND
299        );
300    }
301
302    #[test]
303    fn status_mapping_permission_denied_is_403() {
304        assert_eq!(
305            rpc_error_to_status(&RpcError::permission_denied("x")),
306            axum::http::StatusCode::FORBIDDEN
307        );
308    }
309
310    #[test]
311    fn status_mapping_invalid_argument_is_400() {
312        assert_eq!(
313            rpc_error_to_status(&RpcError::invalid_argument("x")),
314            axum::http::StatusCode::BAD_REQUEST
315        );
316    }
317
318    #[test]
319    fn status_mapping_invalid_params_is_400() {
320        assert_eq!(
321            rpc_error_to_status(&RpcError::invalid_params("x")),
322            axum::http::StatusCode::BAD_REQUEST
323        );
324    }
325
326    #[test]
327    fn status_mapping_internal_error_is_500() {
328        assert_eq!(
329            rpc_error_to_status(&RpcError::internal("x")),
330            axum::http::StatusCode::INTERNAL_SERVER_ERROR
331        );
332    }
333
334    #[test]
335    fn status_mapping_active_conflict_is_409() {
336        assert_eq!(
337            rpc_error_to_status(&RpcError::active_conflict("ws-1")),
338            axum::http::StatusCode::CONFLICT
339        );
340    }
341
342    #[test]
343    fn status_mapping_already_exists_is_409() {
344        assert_eq!(
345            rpc_error_to_status(&RpcError::already_exists("dup")),
346            axum::http::StatusCode::CONFLICT
347        );
348    }
349
350    #[test]
351    fn status_mapping_unknown_code_falls_back_to_500() {
352        assert_eq!(
353            rpc_error_to_status(&RpcError::new(-1, "custom")),
354            axum::http::StatusCode::INTERNAL_SERVER_ERROR
355        );
356    }
357}