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`, (#2350)
9//! `session.set_goal`/`session.clear_goal`/`session.get_goals`,
10//! (DOC-39 §5.6 Slice D) `session.get_readiness`, (DOC-39 §5.4)
11//! `session.get_agents`, (issue #3015) `session.get_context_budget`, and
12//! (issue #3072) `session.get_search_audit` onto a [`Router`], all
13//! closed over the SAME `Arc<SessionRegistry>` so every method sees a
14//! consistent view. Each handler parses its typed `params`, forwards to the
15//! matching `SessionRegistry` method, and maps the result onto the JSON-RPC
16//! result shape the vision spec's §4.3 examples describe.
17//! The three goal methods' handler bodies live in the sibling
18//! `protocol_goals` module, `session.get_readiness`'s in the sibling
19//! `protocol_readiness` module, `session.get_agents`'s in the sibling
20//! `protocol_agents` module, and `session.get_context_budget`'s in the
21//! sibling `protocol_budget` module (all kept out of this file purely for
22//! the 500-SLOC cap — see each module's docs), but are registered here
23//! alongside every other `session.*` method so this remains the one place
24//! listing the full surface.
25//! Test: `protocol::tests::*` (parameter validation, error mapping);
26//! `protocol_goals::tests::*` (the three goal methods);
27//! `protocol_readiness::tests::*` (`session.get_readiness`);
28//! `protocol_agents::tests::*` (`session.get_agents`);
29//! `protocol_budget::tests::*` (`session.get_context_budget`); the full
30//! attach/detach streaming behaviour is covered by `session::registry_tests`
31//! (registry-level) and `tests/session_e2e.rs`/`tests/task_e2e.rs`
32//! (API-driven, real daemon).
33
34use std::path::PathBuf;
35use std::sync::Arc;
36
37use serde::Deserialize;
38use serde::de::DeserializeOwned;
39use serde_json::{Value, json};
40
41use crate::binding::ProjectBinding;
42use crate::jsonrpc::{ConnectionContext, Router, RpcError};
43use crate::workstreams::SharedWorkstreamStore;
44
45use super::registry::SessionRegistry;
46
47/// Register every `session.*` method onto `router`, all sharing `registry`.
48///
49/// Why: the one place that lists the full `session.*` surface — mirrors
50/// `crate::serve::methods::register`'s role for the proof-of-life methods.
51/// What: clones `registry` once per method (cheap — `Arc`) into a small
52/// adapter closure that forwards to the corresponding free function below.
53/// Test: `protocol::tests::register_wires_every_session_method`.
54///
55/// (Issue #3298) `workstreams` is the daemon's shared workstream store —
56/// `session.create` resolves and persists the session's binding (explicit
57/// `workstream_id` param, or DOC-48 §4.2's ambient active-workstream
58/// default) through it before returning.
59pub fn register(
60    router: &mut Router,
61    registry: Arc<SessionRegistry>,
62    workstreams: SharedWorkstreamStore,
63) {
64    let r = registry.clone();
65    let ws = workstreams.clone();
66    router.register(
67        "session.create",
68        move |params: Value, ctx: ConnectionContext| {
69            let r = r.clone();
70            let ws = ws.clone();
71            async move { create(&r, &ws, params, ctx).await }
72        },
73    );
74
75    let r = registry.clone();
76    router.register(
77        "session.list",
78        move |params: Value, ctx: ConnectionContext| {
79            let r = r.clone();
80            async move { list(&r, params, ctx).await }
81        },
82    );
83
84    let r = registry.clone();
85    router.register(
86        "session.status",
87        move |params: Value, ctx: ConnectionContext| {
88            let r = r.clone();
89            async move { status(&r, params, ctx).await }
90        },
91    );
92
93    let r = registry.clone();
94    router.register(
95        "session.send",
96        move |params: Value, ctx: ConnectionContext| {
97            let r = r.clone();
98            async move { send(&r, params, ctx).await }
99        },
100    );
101
102    let r = registry.clone();
103    router.register(
104        "session.attach",
105        move |params: Value, ctx: ConnectionContext| {
106            let r = r.clone();
107            async move { attach(&r, params, ctx).await }
108        },
109    );
110
111    let r = registry.clone();
112    router.register(
113        "session.detach",
114        move |params: Value, ctx: ConnectionContext| {
115            let r = r.clone();
116            async move { detach(&r, params, ctx).await }
117        },
118    );
119
120    let r = registry.clone();
121    router.register(
122        "session.cancel",
123        move |params: Value, ctx: ConnectionContext| {
124            let r = r.clone();
125            async move { cancel(&r, params, ctx).await }
126        },
127    );
128
129    let r = registry.clone();
130    router.register(
131        "session.get_transcript",
132        move |params: Value, ctx: ConnectionContext| {
133            let r = r.clone();
134            async move { get_transcript(&r, params, ctx).await }
135        },
136    );
137
138    let r = registry.clone();
139    router.register(
140        "session.set_goal",
141        move |params: Value, ctx: ConnectionContext| {
142            let r = r.clone();
143            async move { protocol_goals::set_goal(&r, params, ctx).await }
144        },
145    );
146
147    let r = registry.clone();
148    router.register(
149        "session.clear_goal",
150        move |params: Value, ctx: ConnectionContext| {
151            let r = r.clone();
152            async move { protocol_goals::clear_goal(&r, params, ctx).await }
153        },
154    );
155
156    let r = registry.clone();
157    router.register(
158        "session.get_goals",
159        move |params: Value, ctx: ConnectionContext| {
160            let r = r.clone();
161            async move { protocol_goals::get_goals(&r, params, ctx).await }
162        },
163    );
164
165    let r = registry.clone();
166    router.register(
167        "session.get_readiness",
168        move |params: Value, ctx: ConnectionContext| {
169            let r = r.clone();
170            async move { protocol_readiness::get_readiness(&r, params, ctx).await }
171        },
172    );
173
174    let r = registry.clone();
175    router.register(
176        "session.get_agents",
177        move |params: Value, ctx: ConnectionContext| {
178            let r = r.clone();
179            async move { protocol_agents::get_agents(&r, params, ctx).await }
180        },
181    );
182
183    let r = registry.clone();
184    router.register(
185        "session.get_context_budget",
186        move |params: Value, ctx: ConnectionContext| {
187            let r = r.clone();
188            async move { protocol_budget::get_context_budget(&r, params, ctx).await }
189        },
190    );
191
192    let r = registry.clone();
193    router.register(
194        "session.get_search_audit",
195        move |params: Value, ctx: ConnectionContext| {
196            let r = r.clone();
197            async move { protocol_search_audit::get_search_audit(&r, params, ctx).await }
198        },
199    );
200}
201
202/// `params` shape shared by every method that only needs a session id
203/// (`status`, `attach`, `detach`, `cancel`).
204#[derive(Deserialize)]
205struct SessionIdParams {
206    session_id: String,
207}
208
209/// `params` shape for `session.create`.
210///
211/// `project` is now a project PATH, not the free-form label it used to be — see
212/// [`create`]'s docs for the reconciliation and its compatibility implications.
213#[derive(Deserialize)]
214struct CreateParams {
215    task: String,
216    #[serde(default)]
217    agent: Option<String>,
218    #[serde(default)]
219    project: Option<PathBuf>,
220    /// (Issue #3298, DOC-48 §4.1) Explicit workstream to bind this NEW
221    /// session to. `None` falls back to §4.2's ambient active-workstream
222    /// default (or stays projectless if nothing is active) — see
223    /// [`create`]'s docs.
224    #[serde(default)]
225    workstream_id: Option<String>,
226}
227
228/// `params` shape for `session.send`.
229#[derive(Deserialize)]
230struct SendParams {
231    session_id: String,
232    input: String,
233}
234
235/// Deserialise `params` into `T`, mapping a failure onto
236/// `-32602 Invalid params` with the method name for context.
237fn parse<T: DeserializeOwned>(params: Value, method: &str) -> Result<T, RpcError> {
238    serde_json::from_value(params).map_err(|e| RpcError::invalid_params(format!("{method}: {e}")))
239}
240
241/// `session.create(task, agent?, project?) -> Session` (vision spec Axiom 4).
242///
243/// Why: mints a brand-new daemon-owned session.
244/// What: validates `task` is non-empty (`-32003 invalid_argument`
245/// otherwise), resolves `project` into a typed [`ProjectBinding`], then
246/// delegates to `SessionRegistry::create`. The returned `Session` already has
247/// `status: "running"` — see `session::model`'s docs on why M1 has no
248/// queued/created-but-not-running state.
249///
250/// **The `project` reconciliation (spec DOC-39 §5.5, AC-16.2).** This param was
251/// an untyped, free-form `Option<String>` LABEL: never validated, never bound,
252/// not enumerable, and disconnected from the `PathBuf` `task.run` demanded. One
253/// concept lived on two surfaces that could not agree. It is now the same
254/// `ProjectBinding` `task.run` uses, resolved from a project PATH.
255///
256/// This is a deliberate BREAKING change to this method's contract: a caller that
257/// previously passed a decorative label (`"my-app"`) now receives
258/// `-32003 invalid_argument` unless that string names a real directory. Erroring
259/// is the point — silently accepting a label that binds nothing and indexes
260/// nothing is exactly the failure this reconciliation exists to end, and a
261/// caller who learns their "project" was never real is strictly better off than
262/// one who never finds out. Omitting `project` entirely remains valid and means
263/// PROJECTLESS — a supported state, never an error (AC-2.1).
264/// Test: `protocol::tests::create_rejects_empty_task`,
265/// `protocol::tests::create_returns_running_session`,
266/// `protocol::tests::create_without_project_is_projectless`,
267/// `protocol::tests::create_binds_a_real_directory`,
268/// `protocol::tests::create_rejects_a_label_that_is_not_a_directory`.
269///
270/// **(Issue #3298, DOC-48 §4.1/§4.2) Workstream binding.** Resolves and
271/// VALIDATES the EFFECTIVE workstream target via
272/// `crate::workstreams::protocol::resolve_validate_bind` — an explicit
273/// `workstream_id` param wins; otherwise the daemon's active workstream is
274/// the ambient default (§4.2); if neither applies the session stays
275/// projectless (valid). **Validation happens BEFORE the session is minted**
276/// (PR #3354 code-critic HIGH 1): `SessionRegistry` has no delete/rollback,
277/// so a malformed/unknown/closed `workstream_id` must reject the call while
278/// nothing has been created yet — otherwise every rejected bind would
279/// strand an orphaned, caller-invisible session in the registry for the
280/// daemon lifetime. The mint runs as a closure inside that helper, under
281/// the SAME store lock as validation and the subsequent bind, keeping the
282/// whole sequence TOCTOU-free (see the helper's docs).
283/// Test: `workstream_binding_tests::create_binds_ambient_active_workstream`,
284/// `workstream_binding_tests::create_binds_explicit_workstream_overriding_ambient`,
285/// `workstream_binding_tests::create_stays_projectless_without_explicit_or_active`,
286/// `workstream_binding_tests::create_rejects_closed_explicit_workstream`,
287/// `workstream_binding_tests::create_rejected_bind_leaves_no_phantom_session`.
288async fn create(
289    registry: &SessionRegistry,
290    workstreams: &SharedWorkstreamStore,
291    params: Value,
292    _ctx: ConnectionContext,
293) -> Result<Value, RpcError> {
294    let p: CreateParams = parse(params, "session.create")?;
295    if p.task.trim().is_empty() {
296        return Err(RpcError::invalid_argument("task must not be empty"));
297    }
298    let binding = ProjectBinding::resolve(p.project)
299        .map_err(|e| RpcError::invalid_argument(format!("session.create: {e}")))?;
300    protocol_workstream::mint_bound_session(
301        registry,
302        workstreams,
303        p.workstream_id.as_deref(),
304        "session.create",
305        || registry.create(p.task, p.agent, binding).id,
306    )
307    .await
308}
309
310/// `session.list() -> [Session]` (vision spec Axiom 4).
311///
312/// Why: enumerates every session currently owned by the daemon.
313/// What: wraps `SessionRegistry::list` as `{"sessions": [...]}`.
314/// Test: `protocol::tests::list_returns_sessions_key`.
315async fn list(
316    registry: &SessionRegistry,
317    _params: Value,
318    _ctx: ConnectionContext,
319) -> Result<Value, RpcError> {
320    Ok(json!({ "sessions": registry.list() }))
321}
322
323/// `session.status(session_id) -> Session` (vision spec Axiom 4).
324///
325/// Why: point lookup for one session's current state.
326/// What: `-32007 session_not_found` if unknown; otherwise the `Session`.
327/// Test: `protocol::tests::status_unknown_session_maps_to_session_not_found`.
328async fn status(
329    registry: &SessionRegistry,
330    params: Value,
331    _ctx: ConnectionContext,
332) -> Result<Value, RpcError> {
333    let p: SessionIdParams = parse(params, "session.status")?;
334    Ok(json!(registry.status(&p.session_id)?))
335}
336
337/// `session.send(session_id, input) -> { acknowledged }` (vision spec
338/// Axiom 4).
339///
340/// Why: the client -> daemon input path.
341/// What: `-32007 session_not_found` if unknown; otherwise
342/// `{"acknowledged": true}` after `SessionRegistry::send` publishes the
343/// observable `Event::SessionInput`.
344/// Test: `protocol::tests::send_unknown_session_maps_to_session_not_found`.
345async fn send(
346    registry: &SessionRegistry,
347    params: Value,
348    _ctx: ConnectionContext,
349) -> Result<Value, RpcError> {
350    let p: SendParams = parse(params, "session.send")?;
351    registry.send(&p.session_id, &p.input)?;
352    Ok(json!({ "acknowledged": true }))
353}
354
355/// `session.attach(session_id) -> { session_id, events, stream_url }`
356/// (vision spec Axiom 4 / §4.4 session-attach protocol).
357///
358/// Why: the streaming half of the protocol. `events` is the ring-buffer
359/// replay (§12, 11.2) so a freshly-attached client sees recent history
360/// immediately; live events follow as server-initiated notifications.
361/// What: over STDIO, `ctx.notify` is the long-lived per-process channel —
362/// live events are pushed on the SAME connection as
363/// `{"jsonrpc":"2.0","method":"session.event","params":{...}}` lines,
364/// interleaved with ordinary responses. Over HTTP, `ctx.notify` is a
365/// throwaway per-request channel (the forwarder self-terminates once the
366/// response is written); the real HTTP live-streaming path is the
367/// dedicated `GET /sessions/{id}/events` SSE route
368/// (`crate::serve::http::session_events_sse`), which is why `stream_url` is
369/// always included — HTTP clients need it, STDIO clients simply ignore it.
370/// `-32007 session_not_found` if `session_id` is unknown.
371/// Test: `protocol::tests::attach_unknown_session_maps_to_session_not_found`;
372/// the streaming behaviour itself is covered by
373/// `session::registry_tests::attach_forwards_live_events_until_detach` and
374/// the API-driven `tests/session_e2e.rs`.
375async fn attach(
376    registry: &SessionRegistry,
377    params: Value,
378    ctx: ConnectionContext,
379) -> Result<Value, RpcError> {
380    let p: SessionIdParams = parse(params, "session.attach")?;
381    let events = registry.attach(&p.session_id, ctx.connection_id, ctx.notify.clone())?;
382    Ok(json!({
383        "session_id": p.session_id,
384        "events": events,
385        "stream_url": format!("/sessions/{}/events", p.session_id),
386    }))
387}
388
389/// `session.detach(session_id) -> {}` (vision spec Axiom 4).
390///
391/// Why: stops this connection's live-event forwarding for the session.
392/// What: idempotent — detaching without a prior attach is a success no-op
393/// (see `SessionRegistry::detach`). `-32007 session_not_found` if
394/// `session_id` itself is unknown.
395/// Test: `protocol::tests::detach_unknown_session_maps_to_session_not_found`.
396async fn detach(
397    registry: &SessionRegistry,
398    params: Value,
399    ctx: ConnectionContext,
400) -> Result<Value, RpcError> {
401    let p: SessionIdParams = parse(params, "session.detach")?;
402    registry.detach(&p.session_id, ctx.connection_id)?;
403    Ok(json!({}))
404}
405
406/// `session.cancel(session_id) -> Session` (vision spec §12, 11.6
407/// Cancellation Semantics).
408///
409/// Why: explicit termination signal. #2056 splits this into two paths: a
410/// session with a background `task.run` execution in flight must be
411/// signalled COOPERATIVELY (the executing `AgentLoop`(s) observe the flag at
412/// their next turn boundary and unwind themselves — see
413/// `agent_loop::AgentLoopError::Cancelled` — before `crate::task::executor`
414/// lands the terminal transition via `SessionRegistry::finish`); a session
415/// with nothing executing keeps the original #2054 immediate-transition
416/// behaviour.
417/// What: idempotent either way. `-32007 session_not_found` if `session_id`
418/// is unknown. When `SessionRegistry::is_executing` is true, calls
419/// `request_cancel` (sets the flag) and returns the CURRENT snapshot — still
420/// `status: "running"` until the executor actually observes cancellation and
421/// transitions it. Otherwise falls back to `SessionRegistry::cancel` (the
422/// #2054 immediate `status: "cancelled"` path).
423/// Test: `protocol::tests::cancel_unknown_session_maps_to_session_not_found`,
424/// `protocol::tests::cancel_executing_session_requests_cooperative_cancel`.
425async fn cancel(
426    registry: &SessionRegistry,
427    params: Value,
428    _ctx: ConnectionContext,
429) -> Result<Value, RpcError> {
430    let p: SessionIdParams = parse(params, "session.cancel")?;
431    if registry.is_executing(&p.session_id) {
432        registry.request_cancel(&p.session_id)?;
433        Ok(json!(registry.status(&p.session_id)?))
434    } else {
435        Ok(json!(registry.cancel(&p.session_id)?))
436    }
437}
438
439/// `session.get_transcript(session_id) -> TranscriptRecord` (#2058, vision
440/// spec §11.1 Transcript Persistence / §4.3 API Surface).
441///
442/// Why: completes the M1 cut-line's "inspect transcript" verb — read-only
443/// access to the run record `task.run` (#2056) persists via
444/// `SessionRegistry::set_run_outcome`.
445/// What: `-32007 session_not_found` if `session_id` is unknown; otherwise
446/// `SessionRegistry::get_transcript`'s `TranscriptRecord` verbatim — turns,
447/// aggregate usage, and stored cost, never recomputed here. A session that
448/// has never run a task returns a `TranscriptRecord` with an empty `turns`
449/// array rather than an error (see `SessionRegistry::get_transcript`'s docs).
450/// Test: `protocol::tests::get_transcript_unknown_session_maps_to_session_not_found`,
451/// `protocol::tests::get_transcript_on_never_run_session_is_empty`.
452async fn get_transcript(
453    registry: &SessionRegistry,
454    params: Value,
455    _ctx: ConnectionContext,
456) -> Result<Value, RpcError> {
457    let p: SessionIdParams = parse(params, "session.get_transcript")?;
458    Ok(json!(registry.get_transcript(&p.session_id)?))
459}
460
461/// `session.set_goal`/`session.clear_goal`/`session.get_goals` (#2350),
462/// split into their own file purely to keep this production file under the
463/// crate's 500-SLOC cap — a child module of `protocol` (declared via
464/// `#[path = ...] mod protocol_goals;`), so it shares full access to this
465/// module's private `SessionIdParams`/`parse` helpers exactly as if these
466/// handlers were still defined here.
467#[path = "protocol_goals.rs"]
468mod protocol_goals;
469
470/// `session.create`'s workstream-binding step (DOC-48 §4.1/§4.2, issue
471/// #3298), split out for the same 500-SLOC-cap reason as `protocol_goals`
472/// above.
473#[path = "protocol_workstream.rs"]
474mod protocol_workstream;
475
476/// `session.get_readiness` (DOC-39 §5.6 Slice D), split into its own file for
477/// the same 500-SLOC-cap reason as `protocol_goals` above.
478#[path = "protocol_readiness.rs"]
479mod protocol_readiness;
480
481/// `session.get_agents` (DOC-39 §5.4), split into its own file for the same
482/// 500-SLOC-cap reason as `protocol_goals` above.
483#[path = "protocol_agents.rs"]
484mod protocol_agents;
485
486/// `session.get_context_budget` (issue #3015), split into its own file for
487/// the same 500-SLOC-cap reason as `protocol_goals` above.
488#[path = "protocol_budget.rs"]
489mod protocol_budget;
490
491/// `session.get_search_audit` (issue #3072), split into its own file for the
492/// same 500-SLOC-cap reason as `protocol_goals` above.
493#[path = "protocol_search_audit.rs"]
494mod protocol_search_audit;
495
496/// `protocol::tests` (parameter validation, error mapping), split into its
497/// own file for the same reason `sessions_write_tests.rs`/`registry_tests.rs`
498/// are split — a `_tests.rs`-suffixed sibling file falls under the crate's
499/// 1500-SLOC test cap rather than counting against this production file's
500/// 500-SLOC budget.
501#[cfg(test)]
502#[path = "protocol_tests.rs"]
503mod tests;
504
505/// `protocol::binding_tests` (project-binding validation, AC-2.1/AC-16.2),
506/// split out for the same reason as `tests` above.
507#[cfg(test)]
508#[path = "protocol_binding_tests.rs"]
509mod binding_tests;
510
511/// `session.create`'s workstream-binding tests (issue #3298), split into its
512/// own file for the same reason `sessions_write_tests.rs`/`registry_tests.rs`
513/// are split — a `_tests.rs`-suffixed sibling file falls under the crate's
514/// 1500-SLOC test cap rather than counting against this production file's
515/// 500-SLOC budget.
516#[cfg(test)]
517#[path = "protocol_workstream_binding_tests.rs"]
518mod workstream_binding_tests;