rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
//! The sessions the daemon hosts, prompted turn by turn, whose turns run in
//! the daemon and outlive the client that sent them.
//!
//! A loaded session owns its [`SessionRuntime`] and the [`SessionHandle`]
//! that cancels and steers it without waiting for the turn, and its turns
//! are one job in the registry. Requests name the session by its session
//! id. A prompt or an attach for a saved session the daemon has not loaded,
//! such as one an earlier daemon ran or one the TUI saved, reopens it from
//! its file in its own workspace, recording its turns on the session's last
//! job (#1661). The session that started another may answer its questions,
//! never its approvals; see [`answer_question`]. Cancel, steer, unsteer,
//! answer, hold, and configure never
//! load a session: one that is not loaded has no turn to act on, and a
//! client attaches before it changes settings. A steer answers with its id,
//! which a client withdraws it by; see [`steer`]. A prompt answers with its
//! turn's id, which the turn's states and end carry, and may name a key
//! that makes sending it again safe; see [`start`].
//!
//! A session whose host runs its children as its own threads (T3 Code) is
//! woken through that host once background work that outlived its turn
//! finishes; see [`t3_wake`]. Its clients hear whether it is settled, with
//! no turn under way and none the daemon or its host will start for work it
//! waits on; see [`settle`].
//!
//! Clients attach to a loaded session to follow its events (#1657); see
//! [`feed`]. A client that only reads a session observes it instead, which
//! never loads it; see [`observe`]. Observing is also how a client follows
//! a subagent run, by the session the run writes; see [`child_feeds`]. A client may change the session's settings, which apply
//! between turns, a change sent during a turn once it ends, and which the
//! session keeps with its file; see [`configure`] and [`options`]. A
//! session that sits idle, with no turn under way and no client attached,
//! is unloaded until a request reopens it, or discarded when it has saved
//! nothing yet; see [`unload`]. Clients list, rename, and delete saved
//! sessions, loaded or not; see [`catalog`].
//!
//! Once the daemon starts stopping, or restarting in place (#1713), it
//! refuses new sessions and prompts and detaches every client, telling it
//! which; then it stops the turns under way, waits for them to save, and
//! records them interrupted. The daemon a restart re-executes continues
//! those turns as clients attach again; see [`restart_resume`].

use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    sync::{atomic::AtomicBool, Arc, Mutex, MutexGuard, PoisonError, Weak},
    time::Duration,
};

use rho_protocol::{
    DetachReason, ErrorCode, RpcError, SessionAnswerParams, SessionAnswerResponse,
    SessionAttachParams, SessionAttachResponse, SessionCancelParams, SessionCancelResponse,
    SessionHoldParams, SessionHoldResponse, SessionSurfaceActionParams,
    SessionSurfaceActionResponse, Subscription, Surfaces, TurnOutcome,
};
use rho_sdk::{CancellationToken, SessionId};

use super::{
    jobs::{
        Admission, JobEvent, JobId, JobRecord, JobRegistry, Keeping, RegisterError, SessionJob,
        TurnEnd,
    },
    subagents::Subagents,
    wire::state_event,
};
use crate::{
    app::{
        pull_requests::Forge,
        session_events::{LiveEvents, SavedTurn},
        session_runtime::{SavedHistory, SessionHandle, SessionRuntime},
    },
    config::Config,
    session::tree::ProjectedMessage,
};

mod answer_question;
mod awaited;
mod background;
mod budget;
mod cache_warm;
mod catalog;
mod child_feeds;
mod child_questions;
mod configure;
mod cost;
mod feed;
mod fork;
mod grant;
mod held_context;
mod hold;
mod hooks;
mod host_prompt;
mod idle_wake;
mod inputs;
mod inspect;
mod marks;
mod mcp;
mod new;
mod next_turn;
mod observe;
mod open;
mod options;
mod peer_wake;
mod processes;
mod prompt_keys;
mod pull_request_wake;
mod pull_requests;
mod queued;
mod reopen;
mod restart_resume;
mod search;
mod settle;
mod setup;
mod start;
mod steer;
mod store;
mod t3_wake;
#[cfg(test)]
mod test_events;
#[cfg(test)]
mod test_sessions;
mod tool_sources;
mod turn;
mod unload;
mod workflows;
mod worktree;

use super::settings::ConfigStore;
use background::SessionBackground;
use cache_warm::KeepWarm;
pub(super) use child_feeds::{ChildFeeds, ChildStream};
use child_questions::ChildQuestions;
use feed::{attach_response, Feed};
use hold::{Held, Hold};
use idle_wake::IdleWatch;
use inputs::Inputs;
use open::open_failed;
pub(super) use open::{session_environment, Workspace};
use open::{OpenWith, OpenedSession};
pub(super) use prompt_keys::KeyDigest;
use prompt_keys::PromptKeys;
use queued::Queued;
use reopen::ReopenLocks;
use restart_resume::RestartResumes;
use start::Entered;
use t3_wake::{T3Wake, WakeDir};
pub(in crate::app) use turn::DAEMON_COMMANDS;
use turn::{DaemonTurn, PromptStart, TurnLimit, TurnTask};
use unload::Residency;
pub(in crate::app) use unload::UNLOAD_IDLE_AFTER;
pub(super) use worktree::{worktree_stale, Pass, Prune};

/// How long the daemon's stop waits for its turns to save once it was
/// asked to stop, before it records them interrupted and exits anyway.
//
// Tripwire, not measured: a cancelled turn saves in milliseconds, so this
// fires only on a turn stuck in a tool that ignores the cancel. It runs from
// the stop request and stays under `DAEMON_STOP_TIMEOUT` (5 s) with room for
// the rest of the exit (44 ms max measured), so `rho daemon stop` still sees
// the daemon go. `rho daemon restart` drains the same way; an upgrade waits
// for the daemon to be idle first, so it has nothing to drain.
const DRAIN_TIMEOUT: Duration = Duration::from_secs(4);

/// Every session the daemon has loaded, and the job registry that records
/// their turns.
pub(super) struct Sessions {
    jobs: Arc<JobRegistry>,
    /// Lock order: a session's turn lock, then this; never the reverse.
    loaded: Mutex<HashMap<SessionId, Arc<LoadedSession>>>,
    /// The saved sessions being reopened, one at a time each, and those the
    /// idle unload or a delete is tearing down, which a reopen waits for. A
    /// delete holds a session's until its files are gone, so a reopen then
    /// finds nothing saved.
    reopening: ReopenLocks,
    /// The daemon-wide budget the sessions' subagents share, and their jobs.
    subagents: Subagents,
    /// The daemon's settings, which sessions open and turn with.
    settings: Arc<ConfigStore>,
    /// Cancelled once the daemon starts stopping ([`Self::begin_stop`]).
    stopping: CancellationToken,
    /// Read-held from each idle unload decision through its teardown, and
    /// through each delete; the stop write-locks it to wait for them.
    unloading: tokio::sync::RwLock<()>,
    /// The daemon's Rho home, whose saved sessions [`marks`] marks.
    rho_home: PathBuf,
    /// Where the sessions' T3 wake watchers keep their files (see
    /// [`t3_wake`]).
    wakes: WakeDir,
    /// Where the daemon adds the worktrees sessions ask to work in, under
    /// its rho home (see `crate::worktree`).
    worktrees: PathBuf,
    /// This, for the tasks that start a turn on their own (see
    /// [`idle_wake`]).
    myself: Weak<Sessions>,
    /// The sessions whose turn the restart that ran this daemon interrupted,
    /// which continue once a client attaches (see [`restart_resume`]).
    restart_resumes: RestartResumes,
    /// Signals each time the models clients may pick may have changed
    /// (see [`Self::models_changed`]).
    model_lists: tokio::sync::watch::Sender<()>,
    /// The daemon's pull request service (see [`pull_request_wake`]).
    pull_requests: pull_request_wake::PullRequestWake,
    /// The background build of the sessions search index (see [`search`]).
    index_build: search::IndexBuild,
}

/// A session this daemon loaded.
struct LoadedSession {
    /// The session's id, which its usage is recorded under in the usage
    /// ledger.
    id: SessionId,
    /// The job that records the session's turns, in `jobs`.
    job: JobId,
    jobs: Arc<JobRegistry>,
    /// Held by the turn under way and by the change applying; taken when
    /// the daemon stops. Fair, so turns and changes take it in the order
    /// they joined its queue, which each does under the turn lock (see
    /// [`Queued`]).
    runtime: Arc<tokio::sync::Mutex<Option<SessionRuntime>>>,
    handle: SessionHandle,
    /// The config the session's turns read: the one it opened with, which
    /// each turn brings up to date (see [`next_turn`]).
    config: Mutex<next_turn::SessionConfig>,
    /// The daemon's settings, which each turn reads the global config from.
    settings: Arc<ConfigStore>,
    /// The environment the session's children see, which each prompt
    /// replaces with its client's (#1659).
    environment: crate::session_environment::SessionEnvironment,
    /// The directory the session works in.
    workspace: PathBuf,
    /// The setup it opened with, kept to reopen it (see [`pull_request_wake`]).
    setup: rho_protocol::SessionSetup,
    /// The session it forks, for a fork (see [`fork`]), whose delete
    /// unloads it first, so the store can delete its file too.
    fork_of: Option<SessionId>,
    /// The turn's cancel and the session's residency. A prompt's start, an
    /// attach, a turn's end, a cancel, and the idle unload are ordered by
    /// this lock.
    turn: Mutex<TurnSlot>,
    /// The session's events, as attached clients follow them.
    feed: Feed,
    /// Shared inventory handles; reads never wait for the active turn.
    mcp: Mutex<crate::app::session_mcp::SessionMcp>,
    /// The session's background processes, workflow runs and subagents;
    /// reads never wait for the active turn (see [`background`]).
    background: SessionBackground,
    /// Turns the runtime's events into the feed's; only the turn under way
    /// and its steers use it, each briefly and never across an await.
    live: Mutex<LiveEvents>,
    /// The input requests the turn under way and the session's subagents
    /// have open (#1660).
    inputs: Mutex<Inputs>,
    /// The watchers that wake the idle session through its host, present
    /// exactly when its host wakes it (see [`t3_wake`]). Only turns, which
    /// take the runtime one at a time, lock it.
    wake: Option<tokio::sync::Mutex<T3Wake>>,
    /// The session's side of the watcher that starts a turn when its
    /// background work finishes idle, when its client asked for that (see
    /// [`idle_wake`]).
    idle_wake: Option<IdleWatch>,
    /// Set once the daemon or the session's host will not wake the session
    /// for the work it waits on, though that work holds a result, so the
    /// session settles; cleared as a turn starts. Only [`settle`]'s methods
    /// (`give_up_waking`, `mark_wake_given_up`, `rearm_wake`) touch it.
    wake_gave_up: AtomicBool,
    /// Set once a client asked that the session's results wait for its next
    /// turn ([`rho_protocol::SESSION_BACKGROUND_HOLD`]): the daemon starts
    /// no turn to deliver them (see [`idle_wake`]), and its background work
    /// keeps it loaded no longer (see [`unload`]); cleared as a turn starts.
    /// Only [`settle`]'s methods touch it.
    wake_held: AtomicBool,
    /// The session's side of the watcher that takes its subagents'
    /// questions, when a person can be asked (see [`child_questions`]).
    child_questions: Option<ChildQuestions>,
    /// The session's side of the watcher that keeps its provider prompt
    /// cache warm, when its `process` tool offers that (see
    /// [`cache_warm`]).
    cache_warm: Option<KeepWarm>,
    /// Prompt context no model turn has sent yet (see [`held_context`]).
    held_context: Mutex<crate::app::prompt_content::PromptContext>,
    /// The notices of the turns this session starts in other sessions, and
    /// what its turn under way owes the session that started it (see
    /// [`peer_wake`]).
    peer_wake: peer_wake::PeerWake,
}

/// The state a session's turn lock guards.
struct TurnSlot {
    /// The cancel of the session's current or last turn. A prompt replaces
    /// it as its turn starts, and a cancel trips it and the session's
    /// handle, so a cancel never reaches a turn it did not see start. A
    /// turn that arms a T3 wake watcher replaces it once more as its run
    /// ends, so a later cancel still reaches its host calls.
    cancel: CancellationToken,
    /// What the session's current or last turn runs, which decides what a
    /// prompt sent while it runs does. A prompt sets it as its turn starts.
    kind: TurnKind,
    /// The turns prompts naming a key started, which a prompt sent again
    /// with the key answers as (see [`prompt_keys`]).
    keys: PromptKeys,
    /// Whether the session is in use, idle, or unloaded, as the idle unload
    /// tracks it.
    residency: Residency,
    /// What holds the session, if anything: neither a delete nor the idle
    /// unload takes a held session. Set and freed by [`Held`].
    hold: Option<Hold>,
    /// How many approved plans have switched the session's permission mode.
    /// The approval names the implementation turn's mode, so a mode change
    /// still waiting for the runtime when one lands is dropped (see
    /// `configure`).
    plan_switches: u64,
    /// How many turns prompts have started.
    prompts: u64,
    /// The prompted turn, as `prompts` counted it, whose `/compact` last
    /// reduced the conversation, which a
    /// [`rho_protocol::SessionChange::ModelAfterCompaction`] waits for.
    compacted_prompt: Option<u64>,
}

/// What a session's turn runs, as far as a prompt sent meanwhile goes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TurnKind {
    /// A prompt: one sent meanwhile is refused as busy.
    Prompt,
    /// A T3 wake watcher's wait (see [`t3_wake`]), which the watch sets: one
    /// sent meanwhile, as T3 Code sends once restarted after its `rho acp`
    /// was killed, cancels the wait and runs once it ended, resuming it.
    WakeWait,
}

/// Times out input request `id` of `session` after `after`, unless the
/// request closed or was held by then, or the daemon dropped the session.
async fn time_out(session: Weak<LoadedSession>, id: rho_protocol::InputRequestId, after: Duration) {
    tokio::time::sleep(after).await;
    if let Some(session) = session.upgrade() {
        session.change_inputs(|inputs| inputs.time_out(id));
    }
}

/// The rows `runtime` has saved that `live` has not replayed yet, as a turn
/// of the feed's transcript, or `None` when it has saved none since or they
/// could not be read.
fn saved_replay(live: &mut LiveEvents, runtime: &SessionRuntime, job: &JobId) -> Option<SavedTurn> {
    let saved = runtime.saved_history()?;
    let rows = saved_rows(&saved, job)?;
    live.replay(&rows, saved.cwd(), saved.tools())
}

/// The rows of `saved` along the session's branch, or `None` when they
/// could not be read.
fn saved_rows(saved: &SavedHistory<'_>, job: &JobId) -> Option<Vec<ProjectedMessage>> {
    saved
        .display_rows()
        .inspect_err(|error| {
            tracing::warn!(
                %job,
                error = format!("{error:#}"),
                "could not read the session's saved rows; a reset replays only the turns since, live, until a later turn saves"
            );
        })
        .ok()
}

/// The feed of a session opened as `runtime` with `config`, whose turns are
/// recorded on `job`, the mapper that replayed it, and the keyed prompts its
/// saved rows and job name: the feed begins with the conversation the
/// session has saved and how the job's last turn ended, which a new session
/// has neither of, so a client attaching to a reopened session learns that
/// end (#1661).
fn opening_feed(
    job: &JobRecord,
    runtime: &SessionRuntime,
    config: &Config,
    auths: &[String],
) -> (Feed, LiveEvents, PromptKeys) {
    let mut live = LiveEvents::new(
        runtime.workspace_root(),
        runtime.tools(),
        runtime.configured_context_window(),
    );
    // Titles are not saved with the transcript, so the feed starts with the
    // one the session's file has.
    let last = job.moved();
    let feed = Feed::new(
        (&last.state).into(),
        last.turn.clone(),
        runtime.stored_title(),
        options::daemon_options(runtime, config, auths),
        runtime.agent_id().to_string(),
    );
    feed.seed_started_session_defaults(options::started_session_defaults(
        runtime.started_session_defaults(),
    ));
    let saved = runtime.saved_history();
    let rows = saved.as_ref().and_then(|saved| saved_rows(saved, &job.id));
    let saved_keys = saved.as_ref().map_or_else(Vec::new, |saved| {
        saved.message_keys().unwrap_or_else(|error| {
            tracing::warn!(
                job = %job.id,
                error = format!("{error:#}"),
                "could not read the session's saved message keys; a prompt sent again with the key of a saved message starts a turn"
            );
            Vec::new()
        })
    });
    let keys = PromptKeys::loaded(job, &saved_keys);
    if let Some(turn) = saved
        .zip(rows)
        .and_then(|(saved, rows)| live.replay(&rows, saved.cwd(), saved.tools()))
    {
        feed.end_turn(turn);
        feed.seed_usage(&live.context_usage(runtime.context_estimate()));
    }
    // An outcome is recorded with the turn it is of.
    if let (Some(outcome), Some(turn)) = (job.outcome.clone(), last.turn.clone()) {
        feed.publish([
            rho_protocol::SessionEvent::TurnEnded { turn, outcome },
            state_event(&last),
        ]);
    }
    (feed, live, keys)
}

impl LoadedSession {
    /// A session opened as `opened`, whose turns are recorded on `job` in
    /// `jobs`: a new job for a new session, the last one for a reopened one.
    /// Its feed is its [`opening_feed`]. Its T3 wake watchers, when its host wakes it, keep their files in
    /// `wakes`.
    fn new(
        job: &JobRecord,
        jobs: Arc<JobRegistry>,
        opened: OpenedSession,
        auths: &[String],
        wakes: &WakeDir,
        settings: &Arc<ConfigStore>,
    ) -> Self {
        let OpenedSession {
            mut runtime,
            config,
            global,
            environment,
            setup,
            fork_of,
            held_context,
        } = opened;
        let (feed, live, keys) = opening_feed(job, &runtime, &config, auths);
        let job = job.id.clone();
        Self {
            id: runtime.session_id().clone(),
            wake: T3Wake::of(&runtime, wakes).map(tokio::sync::Mutex::new),
            idle_wake: IdleWatch::of(&runtime),
            wake_gave_up: AtomicBool::new(false),
            wake_held: AtomicBool::new(false),
            cache_warm: KeepWarm::of(&runtime),
            held_context: Mutex::new(held_context),
            peer_wake: peer_wake::PeerWake::of(&runtime),
            child_questions: ChildQuestions::of(&mut runtime),
            handle: runtime.handle(),
            workspace: runtime.workspace_root().to_path_buf(),
            live: Mutex::new(live),
            mcp: Mutex::new(crate::app::session_mcp::SessionMcp::of(&runtime)),
            background: SessionBackground::of(&runtime),
            feed,
            job,
            jobs,
            runtime: Arc::new(tokio::sync::Mutex::new(Some(runtime))),
            inputs: Mutex::new(Inputs::new(config.questionnaire.expiry.duration())),
            config: next_turn::SessionConfig::new(config, global),
            settings: Arc::clone(settings),
            environment,
            setup,
            fork_of,
            turn: Mutex::new(TurnSlot {
                cancel: CancellationToken::new(),
                kind: TurnKind::Prompt,
                keys,
                residency: Residency::InUse,
                hold: None,
                plan_switches: 0,
                prompts: 0,
                compacted_prompt: None,
            }),
        }
    }

    /// Records that the turn, queued for capacity, has its slot: `running`
    /// from then on. Under the turn lock, as the turn's start and end are
    /// told (see `Sessions::start_turn`).
    fn admitted(&self) {
        let _turn = self.turn();
        self.record(JobEvent::Admitted);
    }

    /// Applies `event` to the session's job and tells attached clients the
    /// state it left the job in.
    fn record(&self, event: JobEvent) {
        match self.jobs.record(&self.job, event) {
            Ok(moved) => self.feed.publish([state_event(&moved)]),
            Err(error) => {
                tracing::warn!(job = %self.job, %error, "could not record a turn's progress");
            }
        }
    }

    /// Records that turn `turn` ended as `end`, keeping `outcome` on the job
    /// for a later daemon to replay, and tells attached clients `outcome`,
    /// if any, then the state it left the job in, in one publish, so no
    /// client's replay holds one without the other (#1669). Any change to
    /// its background work goes first, so a client hears what the turn left
    /// running before it hears the turn end, and whether the session settled
    /// follows. A turn that owes the session that started this one a notice
    /// tells it then (see [`peer_wake`]).
    fn end_turn(&self, turn: rho_protocol::TurnId, outcome: Option<TurnOutcome>, end: TurnEnd) {
        self.report_background();
        let told = self.peer_wake.ended(&end, outcome.as_ref());
        let ended = outcome
            .clone()
            .map(|outcome| rho_protocol::SessionEvent::TurnEnded { turn, outcome });
        match self.jobs.end_turn(&self.job, end, outcome) {
            Ok(moved) => self
                .feed
                .publish(ended.into_iter().chain([state_event(&moved)])),
            Err(error) => {
                tracing::warn!(job = %self.job, %error, "could not record a turn's end");
                self.feed.publish(ended);
            }
        }
        // Once the job records the end, so a starter that looks once told
        // finds the turn ended.
        if let Some((owed, end)) = told {
            owed.tell_ended(self.feed.title(), end);
        }
        self.report_activity();
    }

    fn live(&self) -> MutexGuard<'_, LiveEvents> {
        // A panic while mapping one event leaves the mapper as it was
        // between events, at worst missing that event's bookkeeping.
        self.live.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn turn(&self) -> MutexGuard<'_, TurnSlot> {
        // Its fields are only ever replaced or cancelled whole, so a panic
        // cannot leave it half-changed.
        self.turn.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// The turn lock of a request that uses the session, marked in use, or
    /// `None` once the idle unload took the session: the request looks it
    /// up again instead, which reopens it if it was saved.
    fn enter(&self) -> Option<MutexGuard<'_, TurnSlot>> {
        let mut turn = self.turn();
        turn.residency.mark_in_use().then_some(turn)
    }

    /// Cancels the turn under way, if any, even one that has not begun its
    /// prompt yet.
    fn cancel_turn(&self) {
        self.cancel_turn_under(&self.turn());
    }

    /// [`Self::cancel_turn`], with `turn`, the session's turn lock, held.
    fn cancel_turn_under(&self, turn: &TurnSlot) {
        // Both under the turn lock, which a prompt takes to start its turn,
        // so the handle's cancel cannot reach a turn started after this
        // cancel. Lock order: the turn lock, then the prompt gate's
        // slot inside `handle.cancel()`; nothing takes them the other way.
        turn.cancel.cancel();
        self.handle.cancel();
    }
}

impl Sessions {
    /// No sessions yet; their turns are recorded in `jobs`, they keep
    /// their T3 wake watchers' files under `rho_home`, the daemon's Rho
    /// home, and their pull requests are read through `forge`.
    pub(super) fn new(jobs: Arc<JobRegistry>, rho_home: &Path, forge: Arc<dyn Forge>) -> Arc<Self> {
        let stopping = CancellationToken::new();
        let subagents = Subagents::new(Arc::clone(&jobs), stopping.clone());
        crate::tools::share_agent_budget(subagents.concurrency());
        Arc::new_cyclic(|myself| Self {
            myself: Weak::clone(myself),
            settings: Arc::new(ConfigStore::new(rho_home, subagents.concurrency())),
            subagents,
            jobs,
            loaded: Mutex::default(),
            reopening: ReopenLocks::default(),
            stopping,
            unloading: tokio::sync::RwLock::new(()),
            rho_home: rho_home.to_path_buf(),
            wakes: WakeDir::in_home(rho_home),
            worktrees: crate::worktree::root(rho_home),
            restart_resumes: RestartResumes::default(),
            model_lists: tokio::sync::watch::Sender::new(()),
            pull_requests: pull_request_wake::PullRequestWake::open(rho_home, forge),
            index_build: search::IndexBuild::default(),
        })
    }

    /// The daemon's settings.
    pub(super) fn settings(&self) -> &ConfigStore {
        &self.settings
    }

    /// What `rho/job/list` reports of loaded session `session`'s job from
    /// its stream; `None` for a session the daemon has not loaded.
    pub(super) fn session_live(&self, session: &SessionId) -> Option<rho_protocol::JobLive> {
        let loaded = self.loaded().get(session).cloned()?;
        Some(loaded.feed.live())
    }

    /// The sessions' subagents: the daemon-wide budget and its queue.
    pub(super) fn subagents(&self) -> &Subagents {
        &self.subagents
    }

    /// Starts the daemon's stop, or its restart: from now on no session
    /// opens, no turn starts, no client attaches, and every client attached
    /// to a session, even by an attach that raced the stop, is detached as
    /// `told`, `daemon_stopping` or `restarting`. Call before the transport
    /// closes the connections, so each client learns why. Calling again
    /// keeps what the first call told.
    pub(super) fn begin_stop(&self, told: DetachReason) {
        // Under the lock `add` checks `stopping` under, so no session is
        // added after this with its feed open.
        let loaded = self.loaded();
        self.stopping.cancel();
        for session in loaded.values() {
            session.feed.close(told);
        }
    }

    /// Adds `opened`, whose turns are recorded as `job` says. Checked,
    /// recorded, and added under the lock the stop drains the sessions
    /// under, so a session opened while the daemon stops is shut down here,
    /// neither left running nor recorded. Its saved conversation is replayed
    /// before that lock, which every request takes.
    async fn add(
        &self,
        job: SessionJobRecord,
        opened: OpenedSession,
    ) -> Result<Arc<LoadedSession>, RpcError> {
        let session = opened.runtime.session_id().clone();
        let auths = options::available_auths(opened.runtime.credentials()).await;
        let tool_sources = opened.runtime.tool_sources_loaded();
        let entry = LoadedSession::new(
            job.job(),
            Arc::clone(&self.jobs),
            opened,
            &auths,
            &self.wakes,
            &self.settings,
        );
        let refused = {
            let mut loaded = self.loaded();
            match self
                .refuse_when_stopping()
                .and_then(|()| job.claim(&self.jobs, &session))
            {
                Ok(()) => {
                    let entry = Arc::new(entry);
                    loaded.insert(session, Arc::clone(&entry));
                    // Before any attach, so every replay ends with it.
                    entry.report_activity();
                    self.watch_idle_results(&entry);
                    self.watch_background(&entry);
                    self.watch_cache_warm(&entry);
                    self.watch_child_questions(&entry);
                    if let Some(loaded) = tool_sources {
                        tool_sources::attach_when_loaded(&entry, loaded);
                    }
                    return Ok(entry);
                }
                Err(error) => error,
            }
        };
        // Never added, so nothing else holds the runtime or queues on it.
        if let Some(runtime) =
            Arc::into_inner(entry.runtime).and_then(tokio::sync::Mutex::into_inner)
        {
            runtime.shutdown().await;
        }
        Err(refused)
    }

    /// Cancels a session's turn, if one is under way, even one that has not
    /// begun its prompt yet.
    pub(super) async fn cancel(
        &self,
        params: SessionCancelParams,
    ) -> Result<SessionCancelResponse, RpcError> {
        if let Some(session) = self.loaded_session(&params.session).await? {
            session.cancel_turn();
        }
        Ok(SessionCancelResponse {})
    }

    /// Hands a client's answer to one of a session's open input requests
    /// (#1660). The first answer wins: a later one finds the request gone.
    pub(super) async fn answer(
        &self,
        params: SessionAnswerParams,
    ) -> Result<SessionAnswerResponse, RpcError> {
        let Some(session) = self.loaded_session(&params.session).await? else {
            return Err(inputs::not_open(params.request));
        };
        session.change_inputs(|inputs| inputs.answer(params.request, params.answer))?;
        Ok(SessionAnswerResponse {})
    }

    /// Hands a session what the user did on an A2UI surface its `ui` tool
    /// showed. The `ui` call waiting on the surface returns it; with none,
    /// the session's next turn delivers it, which the idle watcher starts
    /// where the session's client asked for that (see [`idle_wake`]).
    pub(super) async fn surface_action(
        &self,
        params: SessionSurfaceActionParams,
    ) -> Result<SessionSurfaceActionResponse, RpcError> {
        let invalid = |message: String| RpcError::new(ErrorCode::InvalidParams, message);
        let surfaces = self
            .loaded_session(&params.session)
            .await?
            .and_then(|session| session.background.surfaces())
            .ok_or_else(|| invalid(format!("the session has no surface `{}`", params.surface)))?;
        surfaces
            .act(&params.surface, &params.action, params.data_model)
            .map_err(invalid)?;
        Ok(SessionSurfaceActionResponse {})
    }

    /// Stops one of a session's open input requests from timing out, for a
    /// client whose user started on it (#1660).
    pub(super) async fn hold(
        &self,
        params: SessionHoldParams,
    ) -> Result<SessionHoldResponse, RpcError> {
        let Some(session) = self.loaded_session(&params.session).await? else {
            return Err(inputs::not_open(params.request));
        };
        session.change_inputs(|inputs| inputs.hold(params.request))?;
        Ok(SessionHoldResponse {})
    }

    /// Subscribes a client to a session's events, resuming after its cursor
    /// when the session's feed still can, and continues the session's turn
    /// if the restart that ran this daemon interrupted it.
    pub(super) async fn attach(
        &self,
        params: SessionAttachParams,
    ) -> Result<(SessionAttachResponse, Subscription), RpcError> {
        self.refuse_when_stopping()?;
        // Taken under the turn lock a prompt starts its turn under, so an
        // attach never sees the last turn's end once the job list says the
        // next turn runs, and the idle unload never takes a session a client
        // just attached to.
        // Applied only if this attach reopens the session: one the daemon
        // has loaded keeps the environment and setup it opened with.
        // Its grant is its environment's: an attach names none.
        let draws = params.setup.surfaces;
        // Applied to a loaded session too, from its next turn.
        let prompt = params
            .setup
            .system_prompt
            .as_ref()
            .map(setup::host_prompt)
            .transpose()?;
        let with = OpenWith::under(
            grant::asked(/*named*/ None, &params.environment)?,
            &params.environment,
            params.setup,
        )?;
        // A turn the restart interrupted continues first, so the client
        // attaches to the turn that continues it.
        let (session, (resumed, attached)) = self
            .enter_session(&params.session, &with, |session, turn| {
                let resumed = self.resume_interrupted(session, turn);
                // Read from every attach, not only one that opens the
                // session: a `ui` call waits for the user only while a
                // client that draws surfaces follows the session.
                let viewer = match draws {
                    Surfaces::Unsupported => None,
                    Surfaces::Drawn => session
                        .background
                        .surfaces()
                        .map(|surfaces| surfaces.viewer()),
                };
                Ok((
                    resumed,
                    session.feed.attach_viewer(params.after.as_ref(), viewer),
                ))
            })
            .await?;
        if let Some(prompt) = prompt {
            host_prompt::apply_when_free(&session, prompt, self.stopping.clone());
        }
        if let Some(turn) = resumed {
            // Spawned before anything awaits, as a prompt's turn is.
            TurnTask {
                session: Arc::clone(&session),
                turn,
                stopping: self.stopping.clone(),
            }
            .spawn_daemon(restart_resume::resume_turn());
        }
        Ok(attach_response(&session.workspace, attached))
    }

    /// Stops every session for the daemon's exit, beginning the stop if
    /// [`Self::begin_stop`] has not. Stops each turn, waits until
    /// [`DRAIN_TIMEOUT`] after `stop_requested` for the turns to save and
    /// the runtimes to tear down, the idle unload's included, and records
    /// every job still under way as interrupted. Returns whether every turn
    /// saved and every runtime was torn down in time.
    pub(super) async fn stop(&self, stop_requested: tokio::time::Instant) -> bool {
        self.begin_stop(DetachReason::DaemonStopping);
        let sessions: Vec<_> = self.loaded().drain().map(|(_, session)| session).collect();
        for session in &sessions {
            // The turn stops as one its client lost, so the session keeps
            // what a later daemon resumes (#1661).
            session.handle.close();
        }
        let teardowns = sessions.iter().map(|session| async {
            // Free once the session's turn saved and recorded its end.
            let runtime = session.runtime.lock().await.take();
            if let Some(runtime) = runtime {
                runtime.shutdown().await;
            }
        });
        let drained = tokio::time::timeout_at(
            stop_requested + DRAIN_TIMEOUT,
            futures_util::future::join(
                futures_util::future::join_all(teardowns),
                // The unload decides under the lock `begin_stop` took, so a
                // session it took from `loaded` is torn down under this.
                self.unloading.write(),
            ),
        )
        .await;
        if drained.is_err() {
            tracing::warn!(
                timeout = ?DRAIN_TIMEOUT,
                "turns did not save within DRAIN_TIMEOUT of the stop request; exiting anyway"
            );
        }
        self.jobs.close();
        drained.is_ok()
    }

    fn refuse_when_stopping(&self) -> Result<(), RpcError> {
        if self.stopping.is_cancelled() {
            Err(stopping())
        } else {
            Ok(())
        }
    }

    /// Takes each session, loaded as its id, out of `loaded` and marks it
    /// unloaded, all or none: none when the daemon is stopping or an id now
    /// names another session; whether it did. Each comes with its turn
    /// lock, held, so a request either used the session before this or
    /// finds it gone and looks it up again. Under the lock `begin_stop`
    /// takes, so a stop either drains the sessions first or finds them gone.
    /// Lock order: the turn locks, then `loaded`.
    fn evict(&self, sessions: &mut [(&SessionId, &Arc<LoadedSession>, &mut TurnSlot)]) -> bool {
        let mut loaded = self.loaded();
        let current = sessions.iter().all(|(id, session, _)| {
            loaded
                .get(*id)
                .is_some_and(|loaded| Arc::ptr_eq(loaded, session))
        });
        if self.stopping.is_cancelled() || !current {
            return false;
        }
        for (id, _, turn) in sessions {
            loaded.remove(*id);
            turn.residency = Residency::Unloaded;
        }
        true
    }

    fn loaded(&self) -> MutexGuard<'_, HashMap<SessionId, Arc<LoadedSession>>> {
        // The map is only inserted into, removed from, and drained, so a
        // panic cannot leave it half-changed.
        self.loaded.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// How a session's turns are recorded once it is added.
enum SessionJobRecord {
    /// On a new job, registered as the session is added.
    Register(JobRecord),
    /// On the session's last job, which an earlier daemon or an earlier load
    /// recorded.
    Reuse(JobRecord),
}

impl SessionJobRecord {
    fn job(&self) -> &JobRecord {
        match self {
            Self::Register(record) | Self::Reuse(record) => record,
        }
    }

    /// Records the job in `jobs` as the one of `session`'s turns, refusing
    /// it when the registry no longer agrees, as when another job began
    /// writing the session while it reopened (#1661).
    fn claim(self, jobs: &JobRegistry, session: &SessionId) -> Result<(), RpcError> {
        match (self, jobs.session_job(session)) {
            (Self::Register(record), SessionJob::New) => {
                jobs.register(record).map_err(|error| match error {
                    // Stopping, or restarting for an upgrade.
                    RegisterError::Closed => stopping(),
                    RegisterError::Io(error) => RpcError::new(
                        ErrorCode::InternalError,
                        format!("could not record the session's job: {error}"),
                    ),
                })
            }
            (Self::Reuse(record), SessionJob::Last(last)) if last.id == record.id => {
                // The session reopens with the grant its environment
                // carries, held to the job's limit, so its record says the
                // same.
                jobs.set_grant(&record.id, record.grant);
                Ok(())
            }
            (_, SessionJob::Busy(job)) => Err(writing(&job, session)),
            (Self::Register(_) | Self::Reuse(_), SessionJob::New | SessionJob::Last(_)) => {
                Err(RpcError::new(
                    ErrorCode::SessionBusy,
                    format!("session {session}'s job changed while the daemon opened it"),
                ))
            }
        }
    }
}

/// The error for a session job `job` writes, so the daemon must not open it
/// a second time.
fn writing(job: &JobId, session: &SessionId) -> RpcError {
    RpcError::new(
        ErrorCode::SessionBusy,
        format!("job {job} is writing session {session}"),
    )
}

/// The error a request that needs the session answers while a delete
/// unloads it.
fn being_deleted() -> RpcError {
    RpcError::new(ErrorCode::SessionBusy, "the session is being deleted")
}

fn stopping() -> RpcError {
    RpcError::new(ErrorCode::DaemonStopping, "the daemon is stopping")
}

/// The error a prompt answers when its turn ended, as `outcome` says,
/// before it began: `TurnEnded`, with the outcome as its data.
fn ended_early(outcome: &TurnOutcome) -> RpcError {
    let message = match outcome {
        TurnOutcome::Failed { error } => error.message.clone(),
        TurnOutcome::Cancelled => "the turn was cancelled before it started".to_owned(),
        TurnOutcome::TimedOut { timeout_ms } => {
            format!("the turn reached its {timeout_ms}ms time limit before it started")
        }
        // Only those three end a turn before it begins.
        _ => "the turn ended before it started".to_owned(),
    };
    let data = serde_json::to_value(outcome).expect("a turn outcome serializes");
    RpcError::new(ErrorCode::TurnEnded, message).with_data(data)
}

#[cfg(test)]
#[path = "restored_reopen_tests.rs"]
mod restored_reopen_tests;