trusty_code/serve/rest/sessions_write.rs
1//! `POST`/`PUT`/`DELETE /sessions*` REST routes over the `session.*`
2//! JSON-RPC methods (#2983 Slice 3 — write routes).
3//!
4//! Why: Slice 2 (`super::sessions`) covered the five read-only `GET`
5//! routes; a REST client also needs to mint sessions, drive them, and
6//! manage their goal slots without dropping to raw JSON-RPC. Every handler
7//! below stays as thin as Slice 2's — extract path/body, build the
8//! JSON-RPC `params`, call `super::respond` (or [`respond_created`] for the
9//! one route that needs a non-200 success status) — because the actual
10//! behaviour (session lookup, validation, `-32007 session_not_found`
11//! mapping, …) already lives in `crate::session::protocol`'s handlers;
12//! duplicating it here as bespoke axum logic would fork the two surfaces
13//! (see `super` module docs).
14//! What: [`routes`] builds a standalone `axum::Router<()>` (its own
15//! `SessionsWriteState` carrying just the `Arc<Router>`, `with_state`-erased
16//! before return, mirroring `super::sessions::SessionsState`) mapping:
17//! - `POST /sessions` -> `session.create` (`201 Created` — this route
18//! mints a brand-new resource, so it follows the standard REST
19//! creation convention rather than Slice 1-2's uniform `200`/mapped-4xx;
20//! every other route below acts on an EXISTING resource, so it keeps
21//! `200` on success like every Slice 2 route)
22//! - `POST /sessions/{id}/messages` -> `session.send`
23//! - `POST /sessions/{id}/cancel` -> `session.cancel`
24//! - `PUT /sessions/{id}/goal` -> `session.set_goal`
25//! - `DELETE /sessions/{id}/goal` -> `session.clear_goal`
26//!
27//! Request bodies deserialize into private structs shaped identically to
28//! the RPC layer's own `params` structs (`crate::session::protocol`'s
29//! `CreateParams`/`SendParams`, `protocol_goals`'s
30//! `SetGoalParams`/`ClearGoalParams`) minus whatever the URL path already
31//! supplies (`session_id`) — a malformed body never reaches a handler at
32//! all; axum's `Json<T>` extractor rejects it before the handler runs
33//! (`400`/`422`, see module docs on [`super`]), so no handler here
34//! hand-rolls body validation.
35//! `crate::serve::http::build_axum_router` merges this into the daemon's
36//! main router alongside `POST /rpc`, `GET /health`,
37//! `GET /sessions/{id}/events`, and `super::sessions`'s read routes — none
38//! of those paths collide with the ones here (`PUT`/`DELETE
39//! /sessions/{id}/goal` share a path with different methods, which axum
40//! routes independently).
41//! Test: `tests::*` (`sessions_write_tests.rs`, split out purely for the
42//! 500-SLOC cap — see `crate::session::registry`'s identical
43//! `#[path = "registry_tests.rs"]` split for the established convention).
44
45use std::sync::Arc;
46
47use axum::Json;
48use axum::Router as AxumRouter;
49use axum::extract::{Path, State};
50use axum::http::StatusCode;
51use axum::routing::{post, put};
52use serde::Deserialize;
53use serde_json::{Value, json};
54use trusty_mcp::Response;
55
56use crate::jsonrpc::Router;
57
58use super::{RestResult, respond};
59
60/// Shared axum state for every route in this module: just the JSON-RPC
61/// router, mirroring `super::sessions::SessionsState` — every handler here
62/// goes through [`super::respond`]/[`respond_created`] rather than touching
63/// `SessionRegistry` directly.
64#[derive(Clone)]
65struct SessionsWriteState {
66 router: Arc<Router>,
67}
68
69/// Build the `POST`/`PUT`/`DELETE /sessions*` write route group.
70///
71/// Why: kept separate from `crate::serve::http::build_axum_router` so this
72/// resource group is unit-testable via `tower::util::ServiceExt::oneshot`
73/// on its own, exactly like `super::sessions::routes`.
74/// What: five write routes (see module docs), all sharing one
75/// `SessionsWriteState { router }`, `with_state`-erased to
76/// `axum::Router<()>` so the caller can `.merge()` it alongside
77/// `super::sessions::routes` into the daemon's main router.
78/// Test: `tests::create_session_returns_201_with_running_session`.
79pub fn routes(router: Arc<Router>) -> AxumRouter {
80 AxumRouter::new()
81 .route("/sessions", post(create_session))
82 .route("/sessions/{id}/messages", post(send_message))
83 .route("/sessions/{id}/cancel", post(cancel_session))
84 .route("/sessions/{id}/goal", put(set_goal).delete(clear_goal))
85 .with_state(SessionsWriteState { router })
86}
87
88/// Request body for `POST /sessions`, shaped like `session::protocol`'s
89/// private `CreateParams` (`project` stays a `String` here — it is
90/// forwarded verbatim into the RPC `params` `Value`, and `session.create`'s
91/// own `PathBuf` deserialization applies identically either way).
92#[derive(Deserialize)]
93struct CreateBody {
94 task: String,
95 #[serde(default)]
96 agent: Option<String>,
97 #[serde(default)]
98 project: Option<String>,
99 /// (Issue #3298) Forwarded verbatim to `session.create`'s own
100 /// `workstream_id` param — see `session::protocol::create`'s docs for
101 /// the explicit-vs-ambient resolution rules.
102 #[serde(default)]
103 workstream_id: Option<String>,
104 /// (#8184) Forwarded to `session.create`'s own `delegate` param. `None`
105 /// forwards `false` — the solo default — rather than `null`, which that
106 /// param's plain `bool` would reject.
107 #[serde(default)]
108 delegate: Option<bool>,
109}
110
111/// Request body for `POST /sessions/{id}/messages` — `session_id` comes
112/// from the path, so only `input` remains.
113#[derive(Deserialize)]
114struct SendMessageBody {
115 input: String,
116}
117
118/// Request body for `PUT /sessions/{id}/goal` — `session_id` comes from the
119/// path, so only `slot`/`text` remain (mirrors `protocol_goals`'s private
120/// `SetGoalParams`).
121#[derive(Deserialize)]
122struct SetGoalBody {
123 slot: usize,
124 text: String,
125}
126
127/// Request body for `DELETE /sessions/{id}/goal` — `session_id` comes from
128/// the path, so only `slot` remains (mirrors `protocol_goals`'s private
129/// `ClearGoalParams`). `DELETE` carrying a JSON body is unusual but valid
130/// HTTP; it keeps this route's shape symmetric with `PUT`'s rather than
131/// introducing a query-string convention nowhere else in this crate uses.
132#[derive(Deserialize)]
133struct ClearGoalBody {
134 slot: usize,
135}
136
137/// Like [`super::respond`] but reports `201 Created` on success instead of
138/// the implicit `200` `Json<Value>` carries — the one route in this module
139/// that creates a brand-new resource rather than acting on an existing one.
140///
141/// Why: every other handler in this crate returns [`RestResult`], whose
142/// `Ok` arm is a bare `Json<Value>` (200 via axum's blanket `IntoResponse`);
143/// `POST /sessions` needs a different status on the SAME success path
144/// without duplicating [`respond`]'s error-mapping logic.
145/// What: delegates to [`respond`], then rewraps a successful `Json<Value>`
146/// as `(StatusCode::CREATED, Json<Value>)`; the error arm is untouched —
147/// `rpc_error_to_status` already returns the correct 4xx/5xx.
148/// Test: `tests::create_session_returns_201_with_running_session`.
149async fn respond_created(
150 router: &Router,
151 method: &str,
152 params: Value,
153) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Response>)> {
154 respond(router, method, params)
155 .await
156 .map(|Json(v)| (StatusCode::CREATED, Json(v)))
157}
158
159/// `POST /sessions` -> `session.create`.
160///
161/// Why: the write half of the resource `GET /sessions` (Slice 2) already
162/// enumerates — the only way a REST-only client can bring a session into
163/// existence at all.
164/// What: `201 Created` with the new `Session` JSON on success; `400` if
165/// `task` is empty or `project` names no real directory (`-32003
166/// invalid_argument`, see `session::protocol::create`'s docs on the AC-16.2
167/// project-path reconciliation).
168/// Test: `tests::create_session_returns_201_with_running_session`,
169/// `tests::create_session_empty_task_returns_400`,
170/// `tests::create_session_malformed_body_returns_400`.
171async fn create_session(
172 State(state): State<SessionsWriteState>,
173 Json(body): Json<CreateBody>,
174) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Response>)> {
175 respond_created(
176 &state.router,
177 "session.create",
178 json!({
179 "task": body.task,
180 "agent": body.agent,
181 "project": body.project,
182 "workstream_id": body.workstream_id,
183 // #8184: a REST client that says nothing gets the solo default.
184 "delegate": body.delegate.unwrap_or(false),
185 }),
186 )
187 .await
188}
189
190/// `POST /sessions/{id}/messages` -> `session.send`.
191///
192/// Why: the client -> daemon input path as a REST resource — a "message"
193/// added to the session's input stream.
194/// What: `200` with `{"acknowledged": true}` on success; `404` for an
195/// unknown `id` (`-32007 session_not_found`).
196/// Test: `tests::send_message_returns_200_acknowledged`,
197/// `tests::send_message_missing_session_returns_404`,
198/// `tests::send_message_malformed_body_returns_400`.
199async fn send_message(
200 State(state): State<SessionsWriteState>,
201 Path(id): Path<String>,
202 Json(body): Json<SendMessageBody>,
203) -> RestResult {
204 respond(
205 &state.router,
206 "session.send",
207 json!({"session_id": id, "input": body.input}),
208 )
209 .await
210}
211
212/// `POST /sessions/{id}/cancel` -> `session.cancel`.
213///
214/// Why: explicit REST termination signal, mirroring the JSON-RPC method's
215/// cooperative-vs-immediate cancel semantics (see
216/// `session::protocol::cancel`'s docs) — this route never needs a body,
217/// `session_id` from the path is the whole request.
218/// What: `200` with the (possibly still-`running`, cooperative-cancel-
219/// pending) `Session` snapshot on success; `404` for an unknown `id`.
220/// Test: `tests::cancel_session_returns_200_with_session_json`,
221/// `tests::cancel_session_missing_session_returns_404`,
222/// `tests::cancel_session_is_idempotent`.
223async fn cancel_session(
224 State(state): State<SessionsWriteState>,
225 Path(id): Path<String>,
226) -> RestResult {
227 respond(&state.router, "session.cancel", json!({"session_id": id})).await
228}
229
230/// `PUT /sessions/{id}/goal` -> `session.set_goal`.
231///
232/// Why: the operator-facing REST entry point onto a session's 5 fixed goal
233/// slots (see `protocol_goals` module docs) — `PUT` because it is a full
234/// replace-by-slot, idempotent write.
235/// What: `200` with `{}` on success; `404` for an unknown `id`; `400` if
236/// the session has no transcript yet or `slot` is out of range (`-32003
237/// invalid_argument`, see `protocol_goals::set_goal`'s docs).
238/// Test: `tests::set_goal_returns_200_empty_object`,
239/// `tests::set_goal_missing_session_returns_404`,
240/// `tests::set_goal_malformed_body_returns_400`.
241async fn set_goal(
242 State(state): State<SessionsWriteState>,
243 Path(id): Path<String>,
244 Json(body): Json<SetGoalBody>,
245) -> RestResult {
246 respond(
247 &state.router,
248 "session.set_goal",
249 json!({"session_id": id, "slot": body.slot, "text": body.text}),
250 )
251 .await
252}
253
254/// `DELETE /sessions/{id}/goal` -> `session.clear_goal`.
255///
256/// Why: the operator-facing REST counterpart to `PUT` above.
257/// What: `200` with `{}` on success — clearing an already-empty slot is
258/// idempotent success, matching `protocol_goals::clear_goal`'s convention,
259/// so this route never needs its own idempotency special-case; `404` for an
260/// unknown `id`; `400` for an out-of-range `slot` (`-32003
261/// invalid_argument`).
262/// Test: `tests::clear_goal_returns_200_empty_object`,
263/// `tests::clear_goal_missing_session_returns_404`,
264/// `tests::clear_goal_malformed_body_returns_400`.
265async fn clear_goal(
266 State(state): State<SessionsWriteState>,
267 Path(id): Path<String>,
268 Json(body): Json<ClearGoalBody>,
269) -> RestResult {
270 respond(
271 &state.router,
272 "session.clear_goal",
273 json!({"session_id": id, "slot": body.slot}),
274 )
275 .await
276}
277
278#[cfg(test)]
279#[path = "sessions_write_tests.rs"]
280mod tests;