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;
36use std::time::Duration;
37
38use serde::Deserialize;
39use serde::de::DeserializeOwned;
40use serde_json::{Value, json};
41
42use crate::binding::ProjectBinding;
43use crate::jsonrpc::{ConnectionContext, Router, RpcError};
44use crate::workstreams::SharedWorkstreamStore;
45
46use super::registry::SessionRegistry;
47
48/// How long [`cancel`] waits for a signalled run to actually stop before
49/// answering with an error instead of a cancelled snapshot (#8207).
50///
51/// Why: cancellation is observed at TURN boundaries, so the wait has to cover
52/// finishing whatever tool call is in flight — a `bash` step, a delegated
53/// sub-agent's turn — not just the flag check. The upper bound is not a taste
54/// question: this grace and EVERY in-repo client's per-call budget — the TUI's
55/// [`crate::tui_client::uds_rpc::DEFAULT_CALL_TIMEOUT`] and the CLI's
56/// [`crate::cli_client::stdio::DEFAULT_CALL_TIMEOUT`] — are ONE contract,
57/// because the client's budget covers the daemon's whole wait. The first cut
58/// was thirty seconds against a fifteen-second client budget, so every cancel
59/// taking 15-30s reached the user as a transport timeout and the fail-closed
60/// `cancel_unconfirmed` reply was unreachable from the TUI. Ten seconds leaves
61/// the answer five seconds to be written and read.
62///
63/// It also bounds a second stall: `crate::serve::transport` awaits each
64/// dispatch inline, so a connection serving STDIO is blocked for exactly this
65/// long while a cancel is confirming. Shortening the grace is the whole of the
66/// mitigation here — restructuring that transport is not in #8207's scope.
67/// Test: `protocol::tests::cancel_that_cannot_confirm_the_stop_is_an_error`
68/// pins the fail-closed arm this bound exists to reach;
69/// `protocol::tests::the_cancel_grace_fits_inside_the_clients_call_budget`
70/// pins the contract with the client constant.
71const CANCEL_CONFIRM_GRACE: Duration = Duration::from_secs(10);
72
73/// #8207: a build-time stop on the two halves of the cancel contract being
74/// changed out of order — the daemon's wait must leave the client's call
75/// budget room to carry the answer back.
76const _: () = assert!(
77 CANCEL_CONFIRM_GRACE.as_secs() + CANCEL_ANSWER_HEADROOM.as_secs()
78 <= crate::tui_client::uds_rpc::DEFAULT_CALL_TIMEOUT.as_secs(),
79 "CANCEL_CONFIRM_GRACE must fit inside tui_client's DEFAULT_CALL_TIMEOUT \
80 with headroom for the reply — see #8207"
81);
82
83/// #8207: the SAME stop for the second client over the same call. `tcode`'s CLI
84/// subcommands reach `session.cancel` through
85/// [`crate::cli_client::stdio::StdioRpcClient`], which carries its own 15s
86/// budget — pinning only the TUI's left that one free to drop below the grace
87/// and turn every slow cancel into a transport timeout there instead.
88const _: () = assert!(
89 CANCEL_CONFIRM_GRACE.as_secs() + CANCEL_ANSWER_HEADROOM.as_secs()
90 <= crate::cli_client::stdio::DEFAULT_CALL_TIMEOUT.as_secs(),
91 "CANCEL_CONFIRM_GRACE must fit inside cli_client's DEFAULT_CALL_TIMEOUT \
92 with headroom for the reply — see #8207"
93);
94
95/// How much of the client's call budget is reserved for everything that is not
96/// the wait itself: dialling the socket, framing, and writing the reply.
97const CANCEL_ANSWER_HEADROOM: Duration = Duration::from_secs(5);
98
99/// Register every `session.*` method onto `router`, all sharing `registry`.
100///
101/// Why: the one place that lists the full `session.*` surface — mirrors
102/// `crate::serve::methods::register`'s role for the proof-of-life methods.
103/// What: clones `registry` once per method (cheap — `Arc`) into a small
104/// adapter closure that forwards to the corresponding free function below.
105/// Test: `protocol::tests::register_wires_every_session_method`.
106///
107/// (Issue #3298) `workstreams` is the daemon's shared workstream store —
108/// `session.create` resolves and persists the session's binding (explicit
109/// `workstream_id` param, or DOC-48 §4.2's ambient active-workstream
110/// default) through it before returning.
111pub fn register(
112 router: &mut Router,
113 registry: Arc<SessionRegistry>,
114 workstreams: SharedWorkstreamStore,
115) {
116 let r = registry.clone();
117 let ws = workstreams.clone();
118 router.register(
119 "session.create",
120 move |params: Value, ctx: ConnectionContext| {
121 let r = r.clone();
122 let ws = ws.clone();
123 async move { create(&r, &ws, params, ctx).await }
124 },
125 );
126
127 let r = registry.clone();
128 router.register(
129 "session.list",
130 move |params: Value, ctx: ConnectionContext| {
131 let r = r.clone();
132 async move { list(&r, params, ctx).await }
133 },
134 );
135
136 let r = registry.clone();
137 router.register(
138 "session.status",
139 move |params: Value, ctx: ConnectionContext| {
140 let r = r.clone();
141 async move { status(&r, params, ctx).await }
142 },
143 );
144
145 let r = registry.clone();
146 router.register(
147 "session.send",
148 move |params: Value, ctx: ConnectionContext| {
149 let r = r.clone();
150 async move { send(&r, params, ctx).await }
151 },
152 );
153
154 let r = registry.clone();
155 router.register(
156 "session.attach",
157 move |params: Value, ctx: ConnectionContext| {
158 let r = r.clone();
159 async move { attach(&r, params, ctx).await }
160 },
161 );
162
163 let r = registry.clone();
164 router.register(
165 "session.detach",
166 move |params: Value, ctx: ConnectionContext| {
167 let r = r.clone();
168 async move { detach(&r, params, ctx).await }
169 },
170 );
171
172 let r = registry.clone();
173 router.register(
174 "session.cancel",
175 move |params: Value, ctx: ConnectionContext| {
176 let r = r.clone();
177 async move { cancel(&r, params, ctx).await }
178 },
179 );
180
181 let r = registry.clone();
182 router.register(
183 "session.get_transcript",
184 move |params: Value, ctx: ConnectionContext| {
185 let r = r.clone();
186 async move { get_transcript(&r, params, ctx).await }
187 },
188 );
189
190 let r = registry.clone();
191 router.register(
192 "session.set_goal",
193 move |params: Value, ctx: ConnectionContext| {
194 let r = r.clone();
195 async move { protocol_goals::set_goal(&r, params, ctx).await }
196 },
197 );
198
199 let r = registry.clone();
200 router.register(
201 "session.clear_goal",
202 move |params: Value, ctx: ConnectionContext| {
203 let r = r.clone();
204 async move { protocol_goals::clear_goal(&r, params, ctx).await }
205 },
206 );
207
208 let r = registry.clone();
209 router.register(
210 "session.get_goals",
211 move |params: Value, ctx: ConnectionContext| {
212 let r = r.clone();
213 async move { protocol_goals::get_goals(&r, params, ctx).await }
214 },
215 );
216
217 let r = registry.clone();
218 router.register(
219 "session.get_readiness",
220 move |params: Value, ctx: ConnectionContext| {
221 let r = r.clone();
222 async move { protocol_readiness::get_readiness(&r, params, ctx).await }
223 },
224 );
225
226 let r = registry.clone();
227 router.register(
228 "session.get_agents",
229 move |params: Value, ctx: ConnectionContext| {
230 let r = r.clone();
231 async move { protocol_agents::get_agents(&r, params, ctx).await }
232 },
233 );
234
235 let r = registry.clone();
236 router.register(
237 "session.get_context_budget",
238 move |params: Value, ctx: ConnectionContext| {
239 let r = r.clone();
240 async move { protocol_budget::get_context_budget(&r, params, ctx).await }
241 },
242 );
243
244 let r = registry.clone();
245 router.register(
246 "session.get_search_audit",
247 move |params: Value, ctx: ConnectionContext| {
248 let r = r.clone();
249 async move { protocol_search_audit::get_search_audit(&r, params, ctx).await }
250 },
251 );
252}
253
254/// `params` shape shared by every method that only needs a session id
255/// (`status`, `attach`, `detach`, `cancel`).
256#[derive(Deserialize)]
257struct SessionIdParams {
258 session_id: String,
259}
260
261/// `params` shape for `session.create`.
262///
263/// `project` is now a project PATH, not the free-form label it used to be — see
264/// [`create`]'s docs for the reconciliation and its compatibility implications.
265#[derive(Deserialize)]
266struct CreateParams {
267 task: String,
268 #[serde(default)]
269 agent: Option<String>,
270 #[serde(default)]
271 project: Option<PathBuf>,
272 /// (Issue #3298, DOC-48 §4.1) Explicit workstream to bind this NEW
273 /// session to. `None` falls back to §4.2's ambient active-workstream
274 /// default (or stays projectless if nothing is active) — see
275 /// [`create`]'s docs.
276 #[serde(default)]
277 workstream_id: Option<String>,
278 /// (#8184) Opt this session INTO the delegating PM — the pre-#8184 shape,
279 /// where the top-level agent gets `delegate_to_agent` and no filesystem
280 /// tools of its own.
281 ///
282 /// Why: an interactive session's default is now the #8031 solo agent (see
283 /// [`create`]'s docs), so PM/delegation mode needs a way to be asked for.
284 /// What: `#[serde(default)]` — an omitted field is `false`, i.e. SOLO.
285 /// Inverted into [`crate::session::Session::no_delegate`] at the mint.
286 /// Test: `tests::create_with_delegate_true_keeps_the_delegating_pm`.
287 #[serde(default)]
288 delegate: bool,
289}
290
291/// `params` shape for `session.send`.
292#[derive(Deserialize)]
293struct SendParams {
294 session_id: String,
295 input: String,
296}
297
298/// Deserialise `params` into `T`, mapping a failure onto
299/// `-32602 Invalid params` with the method name for context.
300fn parse<T: DeserializeOwned>(params: Value, method: &str) -> Result<T, RpcError> {
301 serde_json::from_value(params).map_err(|e| RpcError::invalid_params(format!("{method}: {e}")))
302}
303
304/// `session.create(task, agent?, project?) -> Session` (vision spec Axiom 4).
305///
306/// Why: mints a brand-new daemon-owned session.
307/// What: validates `task` is non-empty (`-32003 invalid_argument`
308/// otherwise), resolves `project` into a typed [`ProjectBinding`], then
309/// delegates to `SessionRegistry::create`. The returned `Session` already has
310/// `status: "running"` — see `session::model`'s docs on why M1 has no
311/// queued/created-but-not-running state.
312///
313/// **The `project` reconciliation (spec DOC-39 §5.5, AC-16.2).** This param was
314/// an untyped, free-form `Option<String>` LABEL: never validated, never bound,
315/// not enumerable, and disconnected from the `PathBuf` `task.run` demanded. One
316/// concept lived on two surfaces that could not agree. It is now the same
317/// `ProjectBinding` `task.run` uses, resolved from a project PATH.
318///
319/// This is a deliberate BREAKING change to this method's contract: a caller that
320/// previously passed a decorative label (`"my-app"`) now receives
321/// `-32003 invalid_argument` unless that string names a real directory. Erroring
322/// is the point — silently accepting a label that binds nothing and indexes
323/// nothing is exactly the failure this reconciliation exists to end, and a
324/// caller who learns their "project" was never real is strictly better off than
325/// one who never finds out. Omitting `project` entirely remains valid and means
326/// PROJECTLESS — a supported state, never an error (AC-2.1).
327/// Test: `protocol::tests::create_rejects_empty_task`,
328/// `protocol::tests::create_returns_running_session`,
329/// `protocol::tests::create_without_project_is_projectless`,
330/// `protocol::tests::create_binds_a_real_directory`,
331/// `protocol::tests::create_rejects_a_label_that_is_not_a_directory`.
332///
333/// **(Issue #3298, DOC-48 §4.1/§4.2) Workstream binding.** Resolves and
334/// VALIDATES the EFFECTIVE workstream target via
335/// `crate::workstreams::protocol::resolve_validate_bind` — an explicit
336/// `workstream_id` param wins; otherwise the daemon's active workstream is
337/// the ambient default (§4.2); if neither applies the session stays
338/// projectless (valid). **Validation happens BEFORE the session is minted**
339/// (PR #3354 code-critic HIGH 1): `SessionRegistry` has no delete/rollback,
340/// so a malformed/unknown/closed `workstream_id` must reject the call while
341/// nothing has been created yet — otherwise every rejected bind would
342/// strand an orphaned, caller-invisible session in the registry for the
343/// daemon lifetime. The mint runs as a closure inside that helper, under
344/// the SAME store lock as validation and the subsequent bind, keeping the
345/// whole sequence TOCTOU-free (see the helper's docs).
346/// Test: `workstream_binding_tests::create_binds_ambient_active_workstream`,
347/// `workstream_binding_tests::create_binds_explicit_workstream_overriding_ambient`,
348/// `workstream_binding_tests::create_stays_projectless_without_explicit_or_active`,
349/// `workstream_binding_tests::create_rejects_closed_explicit_workstream`,
350/// `workstream_binding_tests::create_rejected_bind_leaves_no_phantom_session`.
351///
352/// **(#8184) The session's agent shape defaults to SOLO.** A session minted
353/// here runs #8031's single-agent path: the named agent carries its own tcode
354/// tools (read/edit/write/bash) and `delegate_to_agent` is never registered.
355/// This is a deliberate default change — `tcode tui`'s interactive session is
356/// minted through this method and could not do a basic read-edit loop while
357/// the delegating PM registry (which has no filesystem tools at all) was the
358/// only shape available. `delegate: true` asks for the pre-#8184 PM instead;
359/// `task.run`'s own mint path is untouched and stays delegating by default.
360/// The chosen shape is persisted on `Session.no_delegate`, so
361/// `session.status`/`session.list` state which agent a session runs.
362/// Test: `tests::create_defaults_to_the_solo_agent`,
363/// `tests::create_with_delegate_true_keeps_the_delegating_pm`,
364/// `tests::create_without_project_defaults_to_the_solo_agent`.
365async fn create(
366 registry: &SessionRegistry,
367 workstreams: &SharedWorkstreamStore,
368 params: Value,
369 _ctx: ConnectionContext,
370) -> Result<Value, RpcError> {
371 let p: CreateParams = parse(params, "session.create")?;
372 if p.task.trim().is_empty() {
373 return Err(RpcError::invalid_argument("task must not be empty"));
374 }
375 let binding = ProjectBinding::resolve(p.project)
376 .map_err(|e| RpcError::invalid_argument(format!("session.create: {e}")))?;
377 protocol_workstream::mint_bound_session(
378 registry,
379 workstreams,
380 p.workstream_id.as_deref(),
381 "session.create",
382 // #8184: solo unless the caller explicitly asks for the PM.
383 || {
384 registry
385 .create_with_delegation(p.task, p.agent, binding, !p.delegate)
386 .id
387 },
388 )
389 .await
390}
391
392/// `session.list() -> [Session]` (vision spec Axiom 4).
393///
394/// Why: enumerates every session currently owned by the daemon.
395/// What: wraps `SessionRegistry::list` as `{"sessions": [...]}`.
396/// Test: `protocol::tests::list_returns_sessions_key`.
397async fn list(
398 registry: &SessionRegistry,
399 _params: Value,
400 _ctx: ConnectionContext,
401) -> Result<Value, RpcError> {
402 Ok(json!({ "sessions": registry.list() }))
403}
404
405/// `session.status(session_id) -> Session` (vision spec Axiom 4).
406///
407/// Why: point lookup for one session's current state.
408/// What: `-32007 session_not_found` if unknown; otherwise the `Session`.
409/// Test: `protocol::tests::status_unknown_session_maps_to_session_not_found`.
410async fn status(
411 registry: &SessionRegistry,
412 params: Value,
413 _ctx: ConnectionContext,
414) -> Result<Value, RpcError> {
415 let p: SessionIdParams = parse(params, "session.status")?;
416 Ok(json!(registry.status(&p.session_id)?))
417}
418
419/// `session.send(session_id, input) -> { acknowledged }` (vision spec
420/// Axiom 4).
421///
422/// Why: the client -> daemon input path.
423/// What: `-32007 session_not_found` if unknown; otherwise
424/// `{"acknowledged": true}` after `SessionRegistry::send` publishes the
425/// observable `Event::SessionInput`.
426/// Test: `protocol::tests::send_unknown_session_maps_to_session_not_found`.
427async fn send(
428 registry: &SessionRegistry,
429 params: Value,
430 _ctx: ConnectionContext,
431) -> Result<Value, RpcError> {
432 let p: SendParams = parse(params, "session.send")?;
433 registry.send(&p.session_id, &p.input)?;
434 Ok(json!({ "acknowledged": true }))
435}
436
437/// `session.attach(session_id) -> { session_id, events, stream_url }`
438/// (vision spec Axiom 4 / §4.4 session-attach protocol).
439///
440/// Why: the streaming half of the protocol. `events` is the ring-buffer
441/// replay (§12, 11.2) so a freshly-attached client sees recent history
442/// immediately; live events follow as server-initiated notifications.
443/// What: over STDIO, `ctx.notify` is the long-lived per-process channel —
444/// live events are pushed on the SAME connection as
445/// `{"jsonrpc":"2.0","method":"session.event","params":{...}}` lines,
446/// interleaved with ordinary responses. Over HTTP, `ctx.notify` is a
447/// throwaway per-request channel (the forwarder self-terminates once the
448/// response is written); the real HTTP live-streaming path is the
449/// dedicated `GET /sessions/{id}/events` SSE route
450/// (`crate::serve::http::session_events_sse`), which is why `stream_url` is
451/// always included — HTTP clients need it, STDIO clients simply ignore it.
452/// `-32007 session_not_found` if `session_id` is unknown.
453/// Test: `protocol::tests::attach_unknown_session_maps_to_session_not_found`;
454/// the streaming behaviour itself is covered by
455/// `session::registry_tests::attach_forwards_live_events_until_detach` and
456/// the API-driven `tests/session_e2e.rs`.
457async fn attach(
458 registry: &SessionRegistry,
459 params: Value,
460 ctx: ConnectionContext,
461) -> Result<Value, RpcError> {
462 let p: SessionIdParams = parse(params, "session.attach")?;
463 let events = registry.attach(&p.session_id, ctx.connection_id, ctx.notify.clone())?;
464 Ok(json!({
465 "session_id": p.session_id,
466 "events": events,
467 "stream_url": format!("/sessions/{}/events", p.session_id),
468 }))
469}
470
471/// `session.detach(session_id) -> {}` (vision spec Axiom 4).
472///
473/// Why: stops this connection's live-event forwarding for the session.
474/// What: idempotent — detaching without a prior attach is a success no-op
475/// (see `SessionRegistry::detach`). `-32007 session_not_found` if
476/// `session_id` itself is unknown.
477/// Test: `protocol::tests::detach_unknown_session_maps_to_session_not_found`.
478async fn detach(
479 registry: &SessionRegistry,
480 params: Value,
481 ctx: ConnectionContext,
482) -> Result<Value, RpcError> {
483 let p: SessionIdParams = parse(params, "session.detach")?;
484 registry.detach(&p.session_id, ctx.connection_id)?;
485 Ok(json!({}))
486}
487
488/// `session.cancel(session_id) -> Session` (vision spec §12, 11.6
489/// Cancellation Semantics).
490///
491/// Why: explicit termination signal. #2056 splits this into two paths: a
492/// session with a background `task.run` execution in flight must be
493/// signalled COOPERATIVELY (the executing `AgentLoop`(s) observe the flag at
494/// their next turn boundary and unwind themselves — see
495/// `agent_loop::AgentLoopError::Cancelled` — before `crate::task::executor`
496/// lands the terminal transition via `SessionRegistry::finish`); a session
497/// with nothing executing keeps the original #2054 immediate-transition
498/// behaviour.
499/// What: idempotent either way. `-32007 session_not_found` if `session_id`
500/// is unknown. When `SessionRegistry::is_executing` is true, calls
501/// `request_cancel` (sets the flag) and then BLOCKS on
502/// `SessionRegistry::await_cancelled` until the spawned run has actually
503/// stopped, returning the post-stop snapshot. Otherwise falls back to
504/// `SessionRegistry::cancel` (the #2054 immediate `status: "cancelled"` path).
505///
506/// (#8207) The wait is the fix for a client being told a task had stopped
507/// while it had not: this used to return the still-`running` snapshot the
508/// instant the flag was set, so the caller reopened its input and the next
509/// `task.run` was rejected with `-32003 invalid_argument` ("already has a task
510/// running"). The reply is now the answer to "did it stop", which makes
511/// "reported cancelled" and "actually stopped" one fact instead of two. The
512/// wait is FAIL-CLOSED: a run that outlives [`CANCEL_CONFIRM_GRACE`] answers
513/// with `await_cancelled`'s `-32010 cancel_unconfirmed` error, never a
514/// cancelled snapshot — see [`RpcError::cancel_unconfirmed`] for what each
515/// client in this repo does with that code.
516///
517/// KNOWN LIMITATION (#8207): the permission gate (`crate::permissions::gate`)
518/// waits up to its own `timeout` for an answer WITHOUT watching the cancel flag,
519/// so Esc at an open permission prompt cannot stop the run until the prompt
520/// resolves — that cancel spends the whole grace and answers `-32010`.
521/// Test: `protocol::tests::cancel_unknown_session_maps_to_session_not_found`,
522/// `protocol::tests::cancel_executing_session_requests_cooperative_cancel`,
523/// `protocol::tests::cancel_waits_for_the_task_to_stop_before_reporting`,
524/// `protocol::tests::a_prompt_right_after_cancel_is_accepted_not_rejected`,
525/// `protocol::tests::cancel_that_cannot_confirm_the_stop_is_an_error`,
526/// `protocol::tests::the_cancel_grace_fits_inside_the_clients_call_budget`.
527async fn cancel(
528 registry: &SessionRegistry,
529 params: Value,
530 _ctx: ConnectionContext,
531) -> Result<Value, RpcError> {
532 let p: SessionIdParams = parse(params, "session.cancel")?;
533 if registry.is_executing(&p.session_id) {
534 registry.request_cancel(&p.session_id)?;
535 registry
536 .await_cancelled(&p.session_id, CANCEL_CONFIRM_GRACE)
537 .await?;
538 Ok(json!(registry.status(&p.session_id)?))
539 } else {
540 Ok(json!(registry.cancel(&p.session_id)?))
541 }
542}
543
544/// `session.get_transcript(session_id) -> TranscriptRecord` (#2058, vision
545/// spec §11.1 Transcript Persistence / §4.3 API Surface).
546///
547/// Why: completes the M1 cut-line's "inspect transcript" verb — read-only
548/// access to the run record `task.run` (#2056) persists via
549/// `SessionRegistry::set_run_outcome`.
550/// What: `-32007 session_not_found` if `session_id` is unknown; otherwise
551/// `SessionRegistry::get_transcript`'s `TranscriptRecord` verbatim — turns,
552/// aggregate usage, and stored cost, never recomputed here. A session that
553/// has never run a task returns a `TranscriptRecord` with an empty `turns`
554/// array rather than an error (see `SessionRegistry::get_transcript`'s docs).
555/// Test: `protocol::tests::get_transcript_unknown_session_maps_to_session_not_found`,
556/// `protocol::tests::get_transcript_on_never_run_session_is_empty`.
557async fn get_transcript(
558 registry: &SessionRegistry,
559 params: Value,
560 _ctx: ConnectionContext,
561) -> Result<Value, RpcError> {
562 let p: SessionIdParams = parse(params, "session.get_transcript")?;
563 Ok(json!(registry.get_transcript(&p.session_id)?))
564}
565
566/// `session.set_goal`/`session.clear_goal`/`session.get_goals` (#2350),
567/// split into their own file purely to keep this production file under the
568/// crate's 500-SLOC cap — a child module of `protocol` (declared via
569/// `#[path = ...] mod protocol_goals;`), so it shares full access to this
570/// module's private `SessionIdParams`/`parse` helpers exactly as if these
571/// handlers were still defined here.
572#[path = "protocol_goals.rs"]
573mod protocol_goals;
574
575/// `session.create`'s workstream-binding step (DOC-48 §4.1/§4.2, issue
576/// #3298), split out for the same 500-SLOC-cap reason as `protocol_goals`
577/// above.
578#[path = "protocol_workstream.rs"]
579mod protocol_workstream;
580
581/// `session.get_readiness` (DOC-39 §5.6 Slice D), split into its own file for
582/// the same 500-SLOC-cap reason as `protocol_goals` above.
583#[path = "protocol_readiness.rs"]
584mod protocol_readiness;
585
586/// `session.get_agents` (DOC-39 §5.4), split into its own file for the same
587/// 500-SLOC-cap reason as `protocol_goals` above.
588#[path = "protocol_agents.rs"]
589mod protocol_agents;
590
591/// `session.get_context_budget` (issue #3015), split into its own file for
592/// the same 500-SLOC-cap reason as `protocol_goals` above.
593#[path = "protocol_budget.rs"]
594mod protocol_budget;
595
596/// `session.get_search_audit` (issue #3072), split into its own file for the
597/// same 500-SLOC-cap reason as `protocol_goals` above.
598#[path = "protocol_search_audit.rs"]
599mod protocol_search_audit;
600
601/// `protocol::tests` (parameter validation, error mapping), split into its
602/// own file for the same reason `sessions_write_tests.rs`/`registry_tests.rs`
603/// are split — a `_tests.rs`-suffixed sibling file falls under the crate's
604/// 1500-SLOC test cap rather than counting against this production file's
605/// 500-SLOC budget.
606#[cfg(test)]
607#[path = "protocol_tests.rs"]
608mod tests;
609
610/// `protocol::binding_tests` (project-binding validation, AC-2.1/AC-16.2),
611/// split out for the same reason as `tests` above.
612#[cfg(test)]
613#[path = "protocol_binding_tests.rs"]
614mod binding_tests;
615
616/// `session.create`'s workstream-binding tests (issue #3298), split into its
617/// own file for the same reason `sessions_write_tests.rs`/`registry_tests.rs`
618/// are split — a `_tests.rs`-suffixed sibling file falls under the crate's
619/// 1500-SLOC test cap rather than counting against this production file's
620/// 500-SLOC budget.
621#[cfg(test)]
622#[path = "protocol_workstream_binding_tests.rs"]
623mod workstream_binding_tests;