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