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}
105
106/// Request body for `POST /sessions/{id}/messages` — `session_id` comes
107/// from the path, so only `input` remains.
108#[derive(Deserialize)]
109struct SendMessageBody {
110 input: String,
111}
112
113/// Request body for `PUT /sessions/{id}/goal` — `session_id` comes from the
114/// path, so only `slot`/`text` remain (mirrors `protocol_goals`'s private
115/// `SetGoalParams`).
116#[derive(Deserialize)]
117struct SetGoalBody {
118 slot: usize,
119 text: String,
120}
121
122/// Request body for `DELETE /sessions/{id}/goal` — `session_id` comes from
123/// the path, so only `slot` remains (mirrors `protocol_goals`'s private
124/// `ClearGoalParams`). `DELETE` carrying a JSON body is unusual but valid
125/// HTTP; it keeps this route's shape symmetric with `PUT`'s rather than
126/// introducing a query-string convention nowhere else in this crate uses.
127#[derive(Deserialize)]
128struct ClearGoalBody {
129 slot: usize,
130}
131
132/// Like [`super::respond`] but reports `201 Created` on success instead of
133/// the implicit `200` `Json<Value>` carries — the one route in this module
134/// that creates a brand-new resource rather than acting on an existing one.
135///
136/// Why: every other handler in this crate returns [`RestResult`], whose
137/// `Ok` arm is a bare `Json<Value>` (200 via axum's blanket `IntoResponse`);
138/// `POST /sessions` needs a different status on the SAME success path
139/// without duplicating [`respond`]'s error-mapping logic.
140/// What: delegates to [`respond`], then rewraps a successful `Json<Value>`
141/// as `(StatusCode::CREATED, Json<Value>)`; the error arm is untouched —
142/// `rpc_error_to_status` already returns the correct 4xx/5xx.
143/// Test: `tests::create_session_returns_201_with_running_session`.
144async fn respond_created(
145 router: &Router,
146 method: &str,
147 params: Value,
148) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Response>)> {
149 respond(router, method, params)
150 .await
151 .map(|Json(v)| (StatusCode::CREATED, Json(v)))
152}
153
154/// `POST /sessions` -> `session.create`.
155///
156/// Why: the write half of the resource `GET /sessions` (Slice 2) already
157/// enumerates — the only way a REST-only client can bring a session into
158/// existence at all.
159/// What: `201 Created` with the new `Session` JSON on success; `400` if
160/// `task` is empty or `project` names no real directory (`-32003
161/// invalid_argument`, see `session::protocol::create`'s docs on the AC-16.2
162/// project-path reconciliation).
163/// Test: `tests::create_session_returns_201_with_running_session`,
164/// `tests::create_session_empty_task_returns_400`,
165/// `tests::create_session_malformed_body_returns_400`.
166async fn create_session(
167 State(state): State<SessionsWriteState>,
168 Json(body): Json<CreateBody>,
169) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Response>)> {
170 respond_created(
171 &state.router,
172 "session.create",
173 json!({
174 "task": body.task,
175 "agent": body.agent,
176 "project": body.project,
177 "workstream_id": body.workstream_id,
178 }),
179 )
180 .await
181}
182
183/// `POST /sessions/{id}/messages` -> `session.send`.
184///
185/// Why: the client -> daemon input path as a REST resource — a "message"
186/// added to the session's input stream.
187/// What: `200` with `{"acknowledged": true}` on success; `404` for an
188/// unknown `id` (`-32007 session_not_found`).
189/// Test: `tests::send_message_returns_200_acknowledged`,
190/// `tests::send_message_missing_session_returns_404`,
191/// `tests::send_message_malformed_body_returns_400`.
192async fn send_message(
193 State(state): State<SessionsWriteState>,
194 Path(id): Path<String>,
195 Json(body): Json<SendMessageBody>,
196) -> RestResult {
197 respond(
198 &state.router,
199 "session.send",
200 json!({"session_id": id, "input": body.input}),
201 )
202 .await
203}
204
205/// `POST /sessions/{id}/cancel` -> `session.cancel`.
206///
207/// Why: explicit REST termination signal, mirroring the JSON-RPC method's
208/// cooperative-vs-immediate cancel semantics (see
209/// `session::protocol::cancel`'s docs) — this route never needs a body,
210/// `session_id` from the path is the whole request.
211/// What: `200` with the (possibly still-`running`, cooperative-cancel-
212/// pending) `Session` snapshot on success; `404` for an unknown `id`.
213/// Test: `tests::cancel_session_returns_200_with_session_json`,
214/// `tests::cancel_session_missing_session_returns_404`,
215/// `tests::cancel_session_is_idempotent`.
216async fn cancel_session(
217 State(state): State<SessionsWriteState>,
218 Path(id): Path<String>,
219) -> RestResult {
220 respond(&state.router, "session.cancel", json!({"session_id": id})).await
221}
222
223/// `PUT /sessions/{id}/goal` -> `session.set_goal`.
224///
225/// Why: the operator-facing REST entry point onto a session's 5 fixed goal
226/// slots (see `protocol_goals` module docs) — `PUT` because it is a full
227/// replace-by-slot, idempotent write.
228/// What: `200` with `{}` on success; `404` for an unknown `id`; `400` if
229/// the session has no transcript yet or `slot` is out of range (`-32003
230/// invalid_argument`, see `protocol_goals::set_goal`'s docs).
231/// Test: `tests::set_goal_returns_200_empty_object`,
232/// `tests::set_goal_missing_session_returns_404`,
233/// `tests::set_goal_malformed_body_returns_400`.
234async fn set_goal(
235 State(state): State<SessionsWriteState>,
236 Path(id): Path<String>,
237 Json(body): Json<SetGoalBody>,
238) -> RestResult {
239 respond(
240 &state.router,
241 "session.set_goal",
242 json!({"session_id": id, "slot": body.slot, "text": body.text}),
243 )
244 .await
245}
246
247/// `DELETE /sessions/{id}/goal` -> `session.clear_goal`.
248///
249/// Why: the operator-facing REST counterpart to `PUT` above.
250/// What: `200` with `{}` on success — clearing an already-empty slot is
251/// idempotent success, matching `protocol_goals::clear_goal`'s convention,
252/// so this route never needs its own idempotency special-case; `404` for an
253/// unknown `id`; `400` for an out-of-range `slot` (`-32003
254/// invalid_argument`).
255/// Test: `tests::clear_goal_returns_200_empty_object`,
256/// `tests::clear_goal_missing_session_returns_404`,
257/// `tests::clear_goal_malformed_body_returns_400`.
258async fn clear_goal(
259 State(state): State<SessionsWriteState>,
260 Path(id): Path<String>,
261 Json(body): Json<ClearGoalBody>,
262) -> RestResult {
263 respond(
264 &state.router,
265 "session.clear_goal",
266 json!({"session_id": id, "slot": body.slot}),
267 )
268 .await
269}
270
271#[cfg(test)]
272#[path = "sessions_write_tests.rs"]
273mod tests;