trusty_code/session/protocol.rs
1//! `session.*` JSON-RPC method handlers (#2054, vision spec Axiom 4 / §4.3).
2//!
3//! Why: this is the API surface Axiom 4 requires — every session operation
4//! goes through JSON-RPC, reachable identically over STDIO and HTTP, so the
5//! CLI (and later TUI/TELGUI/REST) never touch `SessionRegistry` directly.
6//! What: [`register`] wires `session.create`, `session.list`,
7//! `session.status`, `session.send`, `session.attach`, `session.detach`,
8//! `session.cancel`, and (#2058) `session.get_transcript` onto a [`Router`],
9//! all closed over the SAME `Arc<SessionRegistry>` so every method sees a
10//! consistent view. Each handler parses its typed `params`, forwards to the
11//! matching `SessionRegistry` method, and maps the result onto the JSON-RPC
12//! result shape the vision spec's §4.3 examples describe.
13//! Test: `protocol::tests::*` (parameter validation, error mapping); the
14//! full attach/detach streaming behaviour is covered by
15//! `session::registry_tests` (registry-level) and
16//! `tests/session_e2e.rs`/`tests/task_e2e.rs` (API-driven, real daemon).
17
18use std::sync::Arc;
19
20use serde::Deserialize;
21use serde::de::DeserializeOwned;
22use serde_json::{Value, json};
23
24use crate::jsonrpc::{ConnectionContext, Router, RpcError};
25
26use super::registry::SessionRegistry;
27
28/// Register every `session.*` method onto `router`, all sharing `registry`.
29///
30/// Why: the one place that lists the full `session.*` surface — mirrors
31/// `crate::serve::methods::register`'s role for the proof-of-life methods.
32/// What: clones `registry` once per method (cheap — `Arc`) into a small
33/// adapter closure that forwards to the corresponding free function below.
34/// Test: `protocol::tests::register_wires_every_session_method`.
35pub fn register(router: &mut Router, registry: Arc<SessionRegistry>) {
36 let r = registry.clone();
37 router.register(
38 "session.create",
39 move |params: Value, ctx: ConnectionContext| {
40 let r = r.clone();
41 async move { create(&r, params, ctx).await }
42 },
43 );
44
45 let r = registry.clone();
46 router.register(
47 "session.list",
48 move |params: Value, ctx: ConnectionContext| {
49 let r = r.clone();
50 async move { list(&r, params, ctx).await }
51 },
52 );
53
54 let r = registry.clone();
55 router.register(
56 "session.status",
57 move |params: Value, ctx: ConnectionContext| {
58 let r = r.clone();
59 async move { status(&r, params, ctx).await }
60 },
61 );
62
63 let r = registry.clone();
64 router.register(
65 "session.send",
66 move |params: Value, ctx: ConnectionContext| {
67 let r = r.clone();
68 async move { send(&r, params, ctx).await }
69 },
70 );
71
72 let r = registry.clone();
73 router.register(
74 "session.attach",
75 move |params: Value, ctx: ConnectionContext| {
76 let r = r.clone();
77 async move { attach(&r, params, ctx).await }
78 },
79 );
80
81 let r = registry.clone();
82 router.register(
83 "session.detach",
84 move |params: Value, ctx: ConnectionContext| {
85 let r = r.clone();
86 async move { detach(&r, params, ctx).await }
87 },
88 );
89
90 let r = registry.clone();
91 router.register(
92 "session.cancel",
93 move |params: Value, ctx: ConnectionContext| {
94 let r = r.clone();
95 async move { cancel(&r, params, ctx).await }
96 },
97 );
98
99 let r = registry.clone();
100 router.register(
101 "session.get_transcript",
102 move |params: Value, ctx: ConnectionContext| {
103 let r = r.clone();
104 async move { get_transcript(&r, params, ctx).await }
105 },
106 );
107}
108
109/// `params` shape shared by every method that only needs a session id
110/// (`status`, `attach`, `detach`, `cancel`).
111#[derive(Deserialize)]
112struct SessionIdParams {
113 session_id: String,
114}
115
116/// `params` shape for `session.create`.
117#[derive(Deserialize)]
118struct CreateParams {
119 task: String,
120 #[serde(default)]
121 agent: Option<String>,
122 #[serde(default)]
123 project: Option<String>,
124}
125
126/// `params` shape for `session.send`.
127#[derive(Deserialize)]
128struct SendParams {
129 session_id: String,
130 input: String,
131}
132
133/// Deserialise `params` into `T`, mapping a failure onto
134/// `-32602 Invalid params` with the method name for context.
135fn parse<T: DeserializeOwned>(params: Value, method: &str) -> Result<T, RpcError> {
136 serde_json::from_value(params).map_err(|e| RpcError::invalid_params(format!("{method}: {e}")))
137}
138
139/// `session.create(task, agent?, project?) -> Session` (vision spec Axiom 4).
140///
141/// Why: mints a brand-new daemon-owned session.
142/// What: validates `task` is non-empty (`-32003 invalid_argument`
143/// otherwise), then delegates to `SessionRegistry::create`. The returned
144/// `Session` already has `status: "running"` — see `session::model`'s docs
145/// on why M1 has no queued/created-but-not-running state.
146/// Test: `protocol::tests::create_rejects_empty_task`,
147/// `protocol::tests::create_returns_running_session`.
148async fn create(
149 registry: &SessionRegistry,
150 params: Value,
151 _ctx: ConnectionContext,
152) -> Result<Value, RpcError> {
153 let p: CreateParams = parse(params, "session.create")?;
154 if p.task.trim().is_empty() {
155 return Err(RpcError::invalid_argument("task must not be empty"));
156 }
157 let session = registry.create(p.task, p.agent, p.project);
158 Ok(json!(session))
159}
160
161/// `session.list() -> [Session]` (vision spec Axiom 4).
162///
163/// Why: enumerates every session currently owned by the daemon.
164/// What: wraps `SessionRegistry::list` as `{"sessions": [...]}`.
165/// Test: `protocol::tests::list_returns_sessions_key`.
166async fn list(
167 registry: &SessionRegistry,
168 _params: Value,
169 _ctx: ConnectionContext,
170) -> Result<Value, RpcError> {
171 Ok(json!({ "sessions": registry.list() }))
172}
173
174/// `session.status(session_id) -> Session` (vision spec Axiom 4).
175///
176/// Why: point lookup for one session's current state.
177/// What: `-32007 session_not_found` if unknown; otherwise the `Session`.
178/// Test: `protocol::tests::status_unknown_session_maps_to_session_not_found`.
179async fn status(
180 registry: &SessionRegistry,
181 params: Value,
182 _ctx: ConnectionContext,
183) -> Result<Value, RpcError> {
184 let p: SessionIdParams = parse(params, "session.status")?;
185 Ok(json!(registry.status(&p.session_id)?))
186}
187
188/// `session.send(session_id, input) -> { acknowledged }` (vision spec
189/// Axiom 4).
190///
191/// Why: the client -> daemon input path.
192/// What: `-32007 session_not_found` if unknown; otherwise
193/// `{"acknowledged": true}` after `SessionRegistry::send` publishes the
194/// observable `Event::SessionInput`.
195/// Test: `protocol::tests::send_unknown_session_maps_to_session_not_found`.
196async fn send(
197 registry: &SessionRegistry,
198 params: Value,
199 _ctx: ConnectionContext,
200) -> Result<Value, RpcError> {
201 let p: SendParams = parse(params, "session.send")?;
202 registry.send(&p.session_id, &p.input)?;
203 Ok(json!({ "acknowledged": true }))
204}
205
206/// `session.attach(session_id) -> { session_id, events, stream_url }`
207/// (vision spec Axiom 4 / §4.4 session-attach protocol).
208///
209/// Why: the streaming half of the protocol. `events` is the ring-buffer
210/// replay (§12, 11.2) so a freshly-attached client sees recent history
211/// immediately; live events follow as server-initiated notifications.
212/// What: over STDIO, `ctx.notify` is the long-lived per-process channel —
213/// live events are pushed on the SAME connection as
214/// `{"jsonrpc":"2.0","method":"session.event","params":{...}}` lines,
215/// interleaved with ordinary responses. Over HTTP, `ctx.notify` is a
216/// throwaway per-request channel (the forwarder self-terminates once the
217/// response is written); the real HTTP live-streaming path is the
218/// dedicated `GET /sessions/{id}/events` SSE route
219/// (`crate::serve::http::session_events_sse`), which is why `stream_url` is
220/// always included — HTTP clients need it, STDIO clients simply ignore it.
221/// `-32007 session_not_found` if `session_id` is unknown.
222/// Test: `protocol::tests::attach_unknown_session_maps_to_session_not_found`;
223/// the streaming behaviour itself is covered by
224/// `session::registry_tests::attach_forwards_live_events_until_detach` and
225/// the API-driven `tests/session_e2e.rs`.
226async fn attach(
227 registry: &SessionRegistry,
228 params: Value,
229 ctx: ConnectionContext,
230) -> Result<Value, RpcError> {
231 let p: SessionIdParams = parse(params, "session.attach")?;
232 let events = registry.attach(&p.session_id, ctx.connection_id, ctx.notify.clone())?;
233 Ok(json!({
234 "session_id": p.session_id,
235 "events": events,
236 "stream_url": format!("/sessions/{}/events", p.session_id),
237 }))
238}
239
240/// `session.detach(session_id) -> {}` (vision spec Axiom 4).
241///
242/// Why: stops this connection's live-event forwarding for the session.
243/// What: idempotent — detaching without a prior attach is a success no-op
244/// (see `SessionRegistry::detach`). `-32007 session_not_found` if
245/// `session_id` itself is unknown.
246/// Test: `protocol::tests::detach_unknown_session_maps_to_session_not_found`.
247async fn detach(
248 registry: &SessionRegistry,
249 params: Value,
250 ctx: ConnectionContext,
251) -> Result<Value, RpcError> {
252 let p: SessionIdParams = parse(params, "session.detach")?;
253 registry.detach(&p.session_id, ctx.connection_id)?;
254 Ok(json!({}))
255}
256
257/// `session.cancel(session_id) -> Session` (vision spec §12, 11.6
258/// Cancellation Semantics).
259///
260/// Why: explicit termination signal. #2056 splits this into two paths: a
261/// session with a background `task.run` execution in flight must be
262/// signalled COOPERATIVELY (the executing `AgentLoop`(s) observe the flag at
263/// their next turn boundary and unwind themselves — see
264/// `agent_loop::AgentLoopError::Cancelled` — before `crate::task::executor`
265/// lands the terminal transition via `SessionRegistry::finish`); a session
266/// with nothing executing keeps the original #2054 immediate-transition
267/// behaviour.
268/// What: idempotent either way. `-32007 session_not_found` if `session_id`
269/// is unknown. When `SessionRegistry::is_executing` is true, calls
270/// `request_cancel` (sets the flag) and returns the CURRENT snapshot — still
271/// `status: "running"` until the executor actually observes cancellation and
272/// transitions it. Otherwise falls back to `SessionRegistry::cancel` (the
273/// #2054 immediate `status: "cancelled"` path).
274/// Test: `protocol::tests::cancel_unknown_session_maps_to_session_not_found`,
275/// `protocol::tests::cancel_executing_session_requests_cooperative_cancel`.
276async fn cancel(
277 registry: &SessionRegistry,
278 params: Value,
279 _ctx: ConnectionContext,
280) -> Result<Value, RpcError> {
281 let p: SessionIdParams = parse(params, "session.cancel")?;
282 if registry.is_executing(&p.session_id) {
283 registry.request_cancel(&p.session_id)?;
284 Ok(json!(registry.status(&p.session_id)?))
285 } else {
286 Ok(json!(registry.cancel(&p.session_id)?))
287 }
288}
289
290/// `session.get_transcript(session_id) -> TranscriptRecord` (#2058, vision
291/// spec §11.1 Transcript Persistence / §4.3 API Surface).
292///
293/// Why: completes the M1 cut-line's "inspect transcript" verb — read-only
294/// access to the run record `task.run` (#2056) persists via
295/// `SessionRegistry::set_run_outcome`.
296/// What: `-32007 session_not_found` if `session_id` is unknown; otherwise
297/// `SessionRegistry::get_transcript`'s `TranscriptRecord` verbatim — turns,
298/// aggregate usage, and stored cost, never recomputed here. A session that
299/// has never run a task returns a `TranscriptRecord` with an empty `turns`
300/// array rather than an error (see `SessionRegistry::get_transcript`'s docs).
301/// Test: `protocol::tests::get_transcript_unknown_session_maps_to_session_not_found`,
302/// `protocol::tests::get_transcript_on_never_run_session_is_empty`.
303async fn get_transcript(
304 registry: &SessionRegistry,
305 params: Value,
306 _ctx: ConnectionContext,
307) -> Result<Value, RpcError> {
308 let p: SessionIdParams = parse(params, "session.get_transcript")?;
309 Ok(json!(registry.get_transcript(&p.session_id)?))
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315 use tokio::sync::mpsc;
316 use trusty_common::mcp::Request;
317
318 fn test_ctx() -> ConnectionContext {
319 let (tx, _rx) = mpsc::unbounded_channel();
320 ConnectionContext::new(tx)
321 }
322
323 /// Every `session.*` method must be reachable through a `Router` built
324 /// by `register` (proves the wiring, not just the free functions).
325 #[tokio::test]
326 async fn register_wires_every_session_method() {
327 let registry = Arc::new(SessionRegistry::new());
328 let mut router = Router::new();
329 register(&mut router, registry.clone());
330
331 let session = registry.create("t".to_string(), None, None);
332
333 let cases: &[(&str, Value)] = &[
334 ("session.list", json!({})),
335 ("session.status", json!({"session_id": session.id})),
336 (
337 "session.send",
338 json!({"session_id": session.id, "input": "hi"}),
339 ),
340 ("session.attach", json!({"session_id": session.id})),
341 ("session.detach", json!({"session_id": session.id})),
342 ("session.get_transcript", json!({"session_id": session.id})),
343 ];
344 for (method, params) in cases {
345 let req = Request {
346 jsonrpc: Some("2.0".to_string()),
347 id: Some(json!(1)),
348 method: method.to_string(),
349 params: Some(params.clone()),
350 };
351 let resp = router.dispatch(req, &test_ctx()).await;
352 assert!(
353 resp.error.is_none(),
354 "{method} should succeed, got {:?}",
355 resp.error
356 );
357 }
358
359 // `session.cancel` last since it terminates the session.
360 let req = Request {
361 jsonrpc: Some("2.0".to_string()),
362 id: Some(json!(1)),
363 method: "session.cancel".to_string(),
364 params: Some(json!({"session_id": session.id})),
365 };
366 let resp = router.dispatch(req, &test_ctx()).await;
367 assert!(
368 resp.error.is_none(),
369 "session.cancel should succeed, got {:?}",
370 resp.error
371 );
372 }
373
374 /// An empty `task` must map to `-32003 invalid_argument`, not silently
375 /// create a blank session.
376 #[tokio::test]
377 async fn create_rejects_empty_task() {
378 let registry = SessionRegistry::new();
379 let err = create(®istry, json!({"task": " "}), test_ctx())
380 .await
381 .unwrap_err();
382 assert_eq!(err.code, -32003);
383 }
384
385 /// A well-formed `session.create` call must return a running session.
386 #[tokio::test]
387 async fn create_returns_running_session() {
388 let registry = SessionRegistry::new();
389 let result = create(®istry, json!({"task": "do it"}), test_ctx())
390 .await
391 .unwrap();
392 assert_eq!(result["status"], "running");
393 assert_eq!(result["task"], "do it");
394 }
395
396 /// `session.list` must wrap its result under a `"sessions"` key.
397 #[tokio::test]
398 async fn list_returns_sessions_key() {
399 let registry = SessionRegistry::new();
400 registry.create("a".to_string(), None, None);
401 let result = list(®istry, Value::Null, test_ctx()).await.unwrap();
402 assert_eq!(result["sessions"].as_array().unwrap().len(), 1);
403 }
404
405 /// `session.status` on an unknown id must map to `session_not_found`.
406 #[tokio::test]
407 async fn status_unknown_session_maps_to_session_not_found() {
408 let registry = SessionRegistry::new();
409 let err = status(®istry, json!({"session_id": "nope"}), test_ctx())
410 .await
411 .unwrap_err();
412 assert_eq!(err.code, -32007);
413 }
414
415 /// `session.get_transcript` on an unknown id must map to
416 /// `session_not_found` (#2058).
417 #[tokio::test]
418 async fn get_transcript_unknown_session_maps_to_session_not_found() {
419 let registry = SessionRegistry::new();
420 let err = get_transcript(®istry, json!({"session_id": "nope"}), test_ctx())
421 .await
422 .unwrap_err();
423 assert_eq!(err.code, -32007);
424 }
425
426 /// `session.get_transcript` on a session that has never run a task
427 /// returns an empty transcript, not an error (#2058).
428 #[tokio::test]
429 async fn get_transcript_on_never_run_session_is_empty() {
430 let registry = SessionRegistry::new();
431 let session = registry.create("t".to_string(), None, None);
432 let result = get_transcript(®istry, json!({"session_id": session.id}), test_ctx())
433 .await
434 .unwrap();
435 assert_eq!(result["session_id"], session.id);
436 assert_eq!(result["turns"].as_array().unwrap().len(), 0);
437 assert_eq!(result["cost_usd"], Value::Null);
438 }
439
440 /// `session.send` on an unknown id must map to `session_not_found`.
441 #[tokio::test]
442 async fn send_unknown_session_maps_to_session_not_found() {
443 let registry = SessionRegistry::new();
444 let err = send(
445 ®istry,
446 json!({"session_id": "nope", "input": "hi"}),
447 test_ctx(),
448 )
449 .await
450 .unwrap_err();
451 assert_eq!(err.code, -32007);
452 }
453
454 /// `session.attach` on an unknown id must map to `session_not_found`.
455 #[tokio::test]
456 async fn attach_unknown_session_maps_to_session_not_found() {
457 let registry = SessionRegistry::new();
458 let err = attach(®istry, json!({"session_id": "nope"}), test_ctx())
459 .await
460 .unwrap_err();
461 assert_eq!(err.code, -32007);
462 }
463
464 /// `session.detach` on an unknown id must map to `session_not_found`.
465 #[tokio::test]
466 async fn detach_unknown_session_maps_to_session_not_found() {
467 let registry = SessionRegistry::new();
468 let err = detach(®istry, json!({"session_id": "nope"}), test_ctx())
469 .await
470 .unwrap_err();
471 assert_eq!(err.code, -32007);
472 }
473
474 /// `session.cancel` on an unknown id must map to `session_not_found`.
475 #[tokio::test]
476 async fn cancel_unknown_session_maps_to_session_not_found() {
477 let registry = SessionRegistry::new();
478 let err = cancel(®istry, json!({"session_id": "nope"}), test_ctx())
479 .await
480 .unwrap_err();
481 assert_eq!(err.code, -32007);
482 }
483
484 /// `session.cancel` on a session with an in-flight execution must request
485 /// cooperative cancellation (set the flag) rather than immediately
486 /// transitioning to `cancelled` — the executor lands that transition once
487 /// it actually observes the flag.
488 #[tokio::test]
489 async fn cancel_executing_session_requests_cooperative_cancel() {
490 let registry = SessionRegistry::new();
491 let session = registry.create("t".to_string(), None, None);
492 let flag = registry.begin_execution(&session.id).unwrap();
493
494 let result = cancel(®istry, json!({"session_id": &session.id}), test_ctx())
495 .await
496 .unwrap();
497
498 assert_eq!(
499 result["status"], "running",
500 "status must NOT be transitioned immediately for an executing session"
501 );
502 assert!(
503 flag.load(std::sync::atomic::Ordering::Relaxed),
504 "the shared cancel flag must have been set"
505 );
506 }
507}