Skip to main content

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