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, `-32010 cancel_unconfirmed`
145/// (issue #8207) -> 503, `-32603
146/// Internal error` -> 500. Any other/future code (including
147/// `-32601`/`-32600`, which a REST handler should never see because it
148/// calls `call` with a hardcoded, known-good method name) falls back to 500
149/// — an unmapped domain error is a bug to fix by adding a mapping, not a
150/// client-facing 4xx.
151///
152/// (#8207) `-32010` is the one arm that is neither the caller's fault nor a
153/// daemon fault: the cancel was accepted and the run has not stopped YET. 503 is
154/// the status whose whole meaning is "not now, try again", which is what a
155/// `POST /sessions/{id}/cancel` caller must do — 500 told it the daemon was
156/// broken and 4xx told it its request was, and both are wrong.
157/// Test: `status_mapping_*` — one case per mapped code, plus the unknown ->
158/// 500 fallback.
159pub fn rpc_error_to_status(err: &RpcError) -> axum::http::StatusCode {
160 use axum::http::StatusCode;
161
162 match err.code {
163 -32002 => StatusCode::NOT_FOUND, // not_found
164 -32007 => StatusCode::NOT_FOUND, // session_not_found
165 -32001 => StatusCode::FORBIDDEN, // permission_denied
166 -32003 => StatusCode::BAD_REQUEST, // invalid_argument
167 -32008 => StatusCode::CONFLICT, // active_conflict (DOC-48 §5.2)
168 -32009 => StatusCode::CONFLICT, // already_exists (issue #3449)
169 // #8207: still cancelling — retryable, not a fault on either side.
170 -32010 => StatusCode::SERVICE_UNAVAILABLE,
171 c if c == error_codes::INVALID_PARAMS => StatusCode::BAD_REQUEST,
172 c if c == error_codes::INTERNAL_ERROR => StatusCode::INTERNAL_SERVER_ERROR,
173 _ => StatusCode::INTERNAL_SERVER_ERROR,
174 }
175}
176
177/// Build a throwaway [`ConnectionContext`] for a single REST call.
178///
179/// Why: every REST handler calls [`call`], which requires a
180/// `&ConnectionContext`, but a REST request is exactly as one-shot as an
181/// HTTP `POST /rpc` call — there is no live connection for a handler like
182/// `session.attach` to push notifications back to (that path is the
183/// dedicated SSE route, `crate::serve::http::session_events_sse`). Mirrors
184/// `crate::serve::http::rpc_handler`'s identical throwaway-channel
185/// construction so the two transports build a `ConnectionContext` the same
186/// way.
187/// What: a fresh `mpsc::unbounded_channel()`, receiver immediately dropped —
188/// any handler that queues a notification onto `notify` simply stops on its
189/// next send once this function returns.
190/// Test: exercised indirectly by every `sessions::tests::*` route test (a
191/// route only responds at all if its `ConnectionContext` is constructible).
192pub(crate) fn throwaway_ctx() -> ConnectionContext {
193 let (notify_tx, _notify_rx) = tokio::sync::mpsc::unbounded_channel();
194 ConnectionContext::new(notify_tx)
195}
196
197/// A REST handler's return type: the JSON-RPC result as a `Json` body on
198/// success, or a real HTTP status plus a JSON-RPC error envelope on failure.
199///
200/// Why: `(StatusCode, Json<Response>)` already implements axum's
201/// `IntoResponse` for the error arm, so every route handler can just return
202/// this type from [`respond`] without a bespoke error type.
203pub(crate) type RestResult = Result<Json<Value>, (StatusCode, Json<Response>)>;
204
205/// Call `method` through [`call`] and convert the result into a
206/// [`RestResult`] — the single glue point every Slice 2+ REST handler goes
207/// through.
208///
209/// Why: keeps route handlers themselves down to "extract path/query params,
210/// build `params`, call `respond`" with zero business logic and zero
211/// repeated error-mapping boilerplate (see module docs).
212/// What: `Ok(value)` becomes `Ok(Json(value))`; `Err(rpc_err)` becomes
213/// `Err((rpc_error_to_status(&rpc_err), Json(Response::err(None,
214/// rpc_err.code, rpc_err.message))))` — `data` is intentionally dropped from
215/// the REST envelope, matching `crate::serve::http::session_events_sse`'s
216/// existing `session_not_found` -> 404 mapping (the `id` is always `None`
217/// because a REST error response has no JSON-RPC request id to echo).
218/// Test: `sessions::tests::get_session_found_returns_200_with_session_json`,
219/// `sessions::tests::get_session_missing_returns_404_session_not_found`.
220pub(crate) async fn respond(router: &Router, method: &str, params: Value) -> RestResult {
221 call(router, method, params, &throwaway_ctx())
222 .await
223 .map(Json)
224 .map_err(|err| {
225 let status = rpc_error_to_status(&err);
226 (status, Json(Response::err(None, err.code, err.message)))
227 })
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233 use serde_json::json;
234 use tokio::sync::mpsc;
235
236 fn test_ctx() -> ConnectionContext {
237 let (tx, _rx) = mpsc::unbounded_channel();
238 ConnectionContext::new(tx)
239 }
240
241 fn echo_router() -> Router {
242 let mut router = Router::new();
243 router.register(
244 "echo",
245 |params: Value, _ctx: ConnectionContext| async move { Ok(params) },
246 );
247 router.register(
248 "boom.not_found",
249 |_params: Value, _ctx: ConnectionContext| async move {
250 Err(RpcError::not_found("thing not found: x"))
251 },
252 );
253 router
254 }
255
256 /// `call` on a registered method must return `Ok` with the handler's
257 /// result, unwrapped from the `Response` envelope.
258 #[tokio::test]
259 async fn call_success_returns_handler_result() {
260 let router = echo_router();
261 let result = call(&router, "echo", json!({"a": 1}), &test_ctx())
262 .await
263 .expect("echo must succeed");
264 assert_eq!(result, json!({"a": 1}));
265 }
266
267 /// `call` on a handler that returns an `RpcError` must surface that
268 /// exact error (code + message + data) as `Err`, not swallow it into
269 /// the `Ok` branch.
270 #[tokio::test]
271 async fn call_error_returns_rpc_error() {
272 let router = echo_router();
273 let err = call(&router, "boom.not_found", Value::Null, &test_ctx())
274 .await
275 .expect_err("boom.not_found must fail");
276 assert_eq!(err.code, -32002);
277 assert!(err.message.contains("thing not found"));
278 assert_eq!(err.data, Some(json!({"error_type": "not_found"})));
279 }
280
281 /// `call` on an unknown method must surface `-32601 Method not found`
282 /// like any other `Router::dispatch` caller — `call` does not swallow
283 /// or re-map dispatcher-level errors, only handler-level ones.
284 #[tokio::test]
285 async fn call_unknown_method_returns_method_not_found() {
286 let router = echo_router();
287 let err = call(&router, "does.not.exist", Value::Null, &test_ctx())
288 .await
289 .expect_err("unknown method must fail");
290 assert_eq!(err.code, error_codes::METHOD_NOT_FOUND);
291 }
292
293 /// Every currently-mapped `RpcError` code must resolve to its documented
294 /// HTTP status.
295 #[test]
296 fn status_mapping_not_found_is_404() {
297 assert_eq!(
298 rpc_error_to_status(&RpcError::not_found("x")),
299 axum::http::StatusCode::NOT_FOUND
300 );
301 }
302
303 #[test]
304 fn status_mapping_session_not_found_is_404() {
305 assert_eq!(
306 rpc_error_to_status(&RpcError::session_not_found("s-1")),
307 axum::http::StatusCode::NOT_FOUND
308 );
309 }
310
311 #[test]
312 fn status_mapping_permission_denied_is_403() {
313 assert_eq!(
314 rpc_error_to_status(&RpcError::permission_denied("x")),
315 axum::http::StatusCode::FORBIDDEN
316 );
317 }
318
319 #[test]
320 fn status_mapping_invalid_argument_is_400() {
321 assert_eq!(
322 rpc_error_to_status(&RpcError::invalid_argument("x")),
323 axum::http::StatusCode::BAD_REQUEST
324 );
325 }
326
327 #[test]
328 fn status_mapping_invalid_params_is_400() {
329 assert_eq!(
330 rpc_error_to_status(&RpcError::invalid_params("x")),
331 axum::http::StatusCode::BAD_REQUEST
332 );
333 }
334
335 #[test]
336 fn status_mapping_internal_error_is_500() {
337 assert_eq!(
338 rpc_error_to_status(&RpcError::internal("x")),
339 axum::http::StatusCode::INTERNAL_SERVER_ERROR
340 );
341 }
342
343 #[test]
344 fn status_mapping_active_conflict_is_409() {
345 assert_eq!(
346 rpc_error_to_status(&RpcError::active_conflict("ws-1")),
347 axum::http::StatusCode::CONFLICT
348 );
349 }
350
351 #[test]
352 fn status_mapping_already_exists_is_409() {
353 assert_eq!(
354 rpc_error_to_status(&RpcError::already_exists("dup")),
355 axum::http::StatusCode::CONFLICT
356 );
357 }
358
359 /// A cancel that has not confirmed yet must not read as a fault (#8207).
360 ///
361 /// Why: the code exists so a client can show "still cancelling…" instead of
362 /// an error, and the REST mapping is where that distinction either survives
363 /// or is flattened. It fell through to 500 — indistinguishable from
364 /// `-32603`, which is exactly what the domain code was minted to avoid.
365 /// Test: this test.
366 #[test]
367 fn status_mapping_cancel_unconfirmed_is_503_not_500() {
368 assert_eq!(
369 rpc_error_to_status(&RpcError::cancel_unconfirmed("s-1: still cancelling")),
370 axum::http::StatusCode::SERVICE_UNAVAILABLE
371 );
372 }
373
374 #[test]
375 fn status_mapping_unknown_code_falls_back_to_500() {
376 assert_eq!(
377 rpc_error_to_status(&RpcError::new(-1, "custom")),
378 axum::http::StatusCode::INTERNAL_SERVER_ERROR
379 );
380 }
381}