rho-coding-agent 3.13.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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
//! 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,
    SessionCancelParams, SessionCancelResponse, SessionHoldParams, SessionHoldResponse,
    SessionSurfaceActionParams, SessionSurfaceActionResponse, TurnOutcome,
};
use rho_sdk::{CancellationToken, SessionId};

use super::{
    jobs::{
        Admission, Delivered, JobEvent, JobId, JobRecord, JobRegistry, Keeping, SessionJob,
        StarterNotice, TurnEnd,
    },
    subagents::Subagents,
    wire::state_event,
};
use crate::app::{
    pull_requests::Forge, session_events::LiveEvents, session_runtime::SessionHandle,
};
use engine::Engine;
use errors::{being_deleted, ended_early, stopping, writing};
use opening::EngineParts;
use owner::Owner;

/// How many bytes the list a one-message answer carries may take: a
/// message less what wraps the list, the JSON-RPC envelope and id, a
/// history page's `earlier` entry id and the brackets, about 150 bytes
/// together, with room to spare.
const ANSWER_LIMIT: usize = rho_protocol::MAX_LINE_BYTES - 4 * 1024;

mod acp_asks;
mod acp_background;
mod acp_instructions;
mod acp_steer;
mod acp_tools;
mod acp_turns;
mod agent_activity;
mod answer_question;
mod attach;
mod awaited;
mod background;
mod browser;
#[cfg(feature = "browser")]
mod browser_drive;
#[cfg(feature = "browser")]
mod browser_watch;
mod budget;
mod cache_warm;
mod capabilities;
mod catalog;
mod child_feeds;
mod child_questions;
mod configure;
mod cost;
mod engine;
mod engine_replay;
mod errors;
mod feed;
mod fork;
mod grant;
mod held_context;
mod held_questions;
mod history;
mod hold;
mod hooks;
mod host_prompt;
mod idle_wake;
mod inputs;
mod inspect;
mod job_record;
mod line;
mod locate;
mod marks;
mod mcp;
mod mcp_reload;
mod new;
mod next_turn;
mod observe;
mod open;
mod opening;
mod options;
mod owner;
mod peer_wake;
mod processes;
mod prompt_keys;
mod pull_request_wake;
mod pull_requests;
mod queued;
mod reopen;
mod restart_notice;
mod restart_resume;
mod search;
mod secret_answer;
mod self_questions;
mod sent_by;
mod settle;
mod setup;
mod start;
mod started_agent;
mod steer;
mod store;
mod t3_wake;
#[cfg(test)]
mod test_events;
#[cfg(test)]
mod test_sessions;
mod tool_output;
mod tool_sources;
mod tree;
mod turn;
mod unload;
mod unloaded;
mod workflows;
mod worktree;

use super::settings::ConfigStore;
use background::SessionBackground;
use browser::watch_browser;
use cache_warm::KeepWarm;
pub(super) use child_feeds::{ChildFeeds, ChildStream};
use child_questions::ChildQuestions;
use feed::{attach_response, Feed, ResumeFrom};
use hold::{Held, Hold};
use idle_wake::IdleWatch;
use inputs::Inputs;
use job_record::{JobOpening, SessionJobRecord};
use open::open_failed;
pub(super) use open::{session_environment, Workspace};
use open::{OpenWith, OpenedSession};
use peer_wake::TurnTells;
pub(super) use prompt_keys::KeyDigest;
use prompt_keys::PromptKeys;
use queued::Queued;
use reopen::FirstTurn;
use reopen::ReopenLocks;
use restart_notice::RestartNotices;
use restart_resume::RestartResumes;
use self_questions::OwnQuestions;
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.
// docs/protocol.md states it, beside `DAEMON_RESTART_TIMEOUT`.
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,
    /// The sessions that reported and wait on unmerged pull requests, as
    /// the daemon started, whose starters are yet to hear of them (see
    /// `restart_notice`).
    restart_notices: RestartNotices,
    /// 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 browser the daemon's sessions share; `None` in a build without
    /// it.
    browsers: Option<Arc<crate::browser::Browsers>>,
    /// The background build of the sessions search index (see [`search`]).
    index_build: search::IndexBuild,
    /// The calls each session has yet to take in turn, in the order the
    /// daemon read them (see [`line`]).
    lines: line::Lines,
    /// Write-held by a test to hold each change before it joins its
    /// session's queue, as a change slow to get there would be.
    #[cfg(test)]
    hold_changes: tokio::sync::RwLock<()>,
}

/// 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>,
    /// What runs the session's turns. 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`]).
    engine: Arc<tokio::sync::Mutex<Option<Engine>>>,
    /// What runs the session, which never changes while it is loaded: read
    /// without the engine's lock, which a turn holds.
    runtime: crate::agent::AgentRuntime,
    /// Where a steer reaches the running turn of an agent of another
    /// runtime.
    acp_steers: acp_steer::AcpSteers,
    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 whose delete takes it, which unloads it first, so the
    /// store can delete its file too.
    owner: Option<Owner>,
    /// 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,
    /// The session's way to the daemon's browser, when the daemon has one,
    /// whose changes [`browser`] reports to the feed.
    browser: Option<crate::browser::SessionBrowser>,
    /// The agent budget's say over its turns' model requests (see
    /// `budget.rs`).
    model_slot: Arc<budget::ModelSlot>,
    /// 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,
    /// Set while the prompt that reopened the session has yet to start its
    /// turn, which takes the session's results (see
    /// [`LoadedSession::hold_wake_for_prompt`]).
    wake_held_for_prompt: 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 takes the questions it asks
    /// without waiting, when it reports to its starter (see
    /// [`self_questions`]).
    own_questions: Option<OwnQuestions>,
    /// 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));
    }
}

/// Whether a session being added is new to the daemon or one it reopened,
/// which decides what tearing down a refused add leaves saved.
enum Freshness {
    New,
    Reopened,
}

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 {
            engine,
            config,
            global,
            environment,
            setup,
            owner,
            held_context,
            browser,
            model_slot,
        } = opened;
        let parts = match engine {
            Engine::Rho(runtime) => EngineParts::rho(runtime, job, &config, auths, wakes),
            Engine::Acp(turns) => EngineParts::acp(turns, job, settings.agent_path()),
        };
        let job = job.id.clone();
        let EngineParts {
            wake,
            idle_wake,
            cache_warm,
            peer_wake,
            child_questions,
            own_questions,
            handle,
            live,
            mcp,
            background,
            feed,
            keys,
            engine,
        } = parts;
        let runtime = engine.runtime();
        feed.seed_engine(capabilities::SessionEngine {
            runtime,
            adapter: super::runtimes::adapter(runtime, &environment.current()),
        });
        Self {
            id: engine.session_id().clone(),
            runtime,
            acp_steers: acp_steer::AcpSteers::default(),
            wake,
            idle_wake,
            wake_gave_up: AtomicBool::new(false),
            wake_held: AtomicBool::new(false),
            wake_held_for_prompt: AtomicBool::new(false),
            cache_warm,
            held_context: Mutex::new(held_context),
            peer_wake,
            child_questions,
            own_questions,
            handle,
            workspace: engine.workspace_root().to_path_buf(),
            live: Mutex::new(live),
            mcp: Mutex::new(mcp),
            background,
            feed,
            browser,
            model_slot,
            job,
            jobs,
            engine: Arc::new(tokio::sync::Mutex::new(Some(engine))),
            inputs: Mutex::new(Inputs::new(config.questionnaire.expiry.duration())),
            config: next_turn::SessionConfig::new(config, global),
            settings: Arc::clone(settings),
            environment,
            setup,
            owner,
            turn: Mutex::new(TurnSlot {
                cancel: CancellationToken::new(),
                kind: TurnKind::Prompt,
                keys,
                residency: Residency::InUse,
                hold: None,
                plan_switches: 0,
                prompts: 0,
                compacted_prompt: None,
            }),
        }
    }

    /// `Ok` when what runs the session can do `capability`, else the typed
    /// refusal, decided without waiting for the turn under way.
    fn require(&self, capability: rho_protocol::SessionCapability) -> Result<(), RpcError> {
        capabilities::require(self.engine(), capability)
    }

    /// What runs the session, with what its adapter said as far as this
    /// daemon knows now, which the session's clients are told of.
    fn engine(&self) -> capabilities::SessionEngine {
        let ambient = self.environment.current();
        let adapter = super::runtimes::adapter(self.runtime, &ambient);
        let engine = capabilities::SessionEngine {
            runtime: self.runtime,
            adapter,
        };
        self.feed.update_engine(engine);
        engine
    }

    /// 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) {
        self.feed.publish_change(|| {
            let moved = self
                .jobs
                .record(&self.job, event)
                .inspect_err(|error| {
                    tracing::warn!(job = %self.job, %error, "could not record a turn's progress");
                })
                .ok();
            ((), moved.map(|moved| state_event(&moved)))
        });
    }

    /// 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();
        // Where the questions this session holds go up, should it report
        // to its starter (see `held_questions`).
        let up = self.peer_wake.report_target();
        let note = match &outcome {
            Some(TurnOutcome::Answered { text, .. }) => Some(text.clone()),
            _ => None,
        };
        let word = self.jobs.word_of(&self.job);
        // A daemon that stops ends every turn so: the holder did not leave
        // its questions, and their saved holders must outlive the stop.
        let passes_on = !matches!(end, TurnEnd::Interrupted);
        let (told, word) = self.peer_wake.ended(&end, outcome.as_ref(), word.as_ref());
        // Kept until the notice is delivered, so a daemon that ends first,
        // as one whose end interrupts this turn, tells it again as the
        // starter loads (see `peer_wake`). A turn that tells nothing of
        // itself is done telling. Recorded with the end, in one write.
        let starter = match &told {
            TurnTells::Tell(_, end) => StarterNotice::Owed {
                report: end.report(),
            },
            TurnTells::Silent => StarterNotice::Nothing,
            TurnTells::Untold { report } => StarterNotice::Owed { report: *report },
        };
        let ended = outcome
            .clone()
            .map(|outcome| rho_protocol::SessionEvent::TurnEnded {
                turn: turn.clone(),
                outcome,
            });
        self.feed.publish_change(|| {
            let moved = self
                .jobs
                .end_turn(&self.job, end, outcome, starter, word)
                .inspect_err(|error| {
                    tracing::warn!(job = %self.job, %error, "could not record a turn's end");
                })
                .ok();
            (
                (),
                ended
                    .into_iter()
                    .chain(moved.map(|moved| state_event(&moved))),
            )
        });
        // Once the job records the end, so a starter that looks once told
        // finds the turn ended.
        if let TurnTells::Tell(owed, end) = told {
            let receipt = self.receipt(Delivered::End {
                turn: turn.clone(),
                starter: owed.starter().clone(),
            });
            owed.tell_ended(self.feed.name(), end, receipt);
        }
        // Whatever this turn left unanswered of the questions it held moves
        // on.
        if passes_on {
            self.pass_on_held(note, up);
        }
        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::queue_in_agent_budget();
        let settings = Arc::new(ConfigStore::new(rho_home, subagents.concurrency()));
        let browsers = crate::browser::Browsers::for_daemon(rho_home, {
            let settings = Arc::clone(&settings);
            Box::new(move || {
                let settings = Arc::clone(&settings);
                Box::pin(async move {
                    // A config that never loaded leaves the defaults; one
                    // that stopped loading keeps its last good values.
                    settings
                        .agent_config()
                        .await
                        .map(|config| config.browser.clone())
                        .unwrap_or_default()
                })
            })
        });
        Arc::new_cyclic(|myself| Self {
            myself: Weak::clone(myself),
            settings,
            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(),
            restart_notices: RestartNotices::default(),
            model_lists: tokio::sync::watch::Sender::new(()),
            pull_requests: pull_request_wake::PullRequestWake::open(rho_home, forge),
            browsers,
            index_build: search::IndexBuild::default(),
            lines: line::Lines::default(),
            #[cfg(test)]
            hold_changes: tokio::sync::RwLock::new(()),
        })
    }

    /// What a session the daemon runs serves its tools from.
    fn run_services(&self) -> open::RunServices<'_> {
        open::RunServices {
            pull_requests: &self.pull_requests,
            browsers: self.browsers.as_ref(),
        }
    }

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

    /// Whether the daemon has any session loaded.
    pub(super) fn any_loaded(&self) -> bool {
        !self.loaded().is_empty()
    }

    /// 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,
        first: FirstTurn,
    ) -> Result<Arc<LoadedSession>, RpcError> {
        let session = opened.engine.session_id().clone();
        let agent = opened.engine.job_agent();
        // A session new to the daemon leaves nothing saved if it is refused;
        // a reopened one keeps its file.
        let fresh = match &job {
            SessionJobRecord::Register(_) => Freshness::New,
            SessionJobRecord::Reuse(_) => Freshness::Reopened,
        };
        let (auths, tool_sources) = match opened.engine.as_rho() {
            Some(runtime) => (
                options::available_auths(runtime.credentials()).await,
                runtime.tool_sources_loaded(),
            ),
            None => (Vec::new(), None),
        };
        let entry = LoadedSession::new(
            job.job(),
            Arc::clone(&self.jobs),
            opened,
            &auths,
            &self.wakes,
            &self.settings,
        );
        match first {
            FirstTurn::Daemon => {}
            // Before its idle watcher starts.
            FirstTurn::Prompt => entry.hold_wake_for_prompt(),
        }
        let opening = JobOpening {
            agent,
            title: entry.feed.title(),
            reports_to: entry.peer_wake.reports_to().cloned(),
        };
        let refused = 'added: {
            let mut loaded = self.loaded();
            match self
                .refuse_when_stopping()
                .and_then(|()| job.claim(&self.jobs, &session, opening))
            {
                Ok(()) => {
                    let entry = Arc::new(entry);
                    loaded.insert(session, Arc::clone(&entry));
                    // Before its first activity: questions it waits on keep
                    // it from reading as settled.
                    let reopening = self.reopen_self_questions(&entry);
                    // Before any attach, so every replay ends with it.
                    entry.report_activity();
                    self.watch_idle_results(&entry);
                    self.watch_background(&entry);
                    watch_browser(&entry);
                    self.watch_cache_warm(&entry);
                    self.watch_child_questions(&entry);
                    if let Some(loaded) = tool_sources {
                        tool_sources::attach_when_loaded(&entry, loaded);
                    }
                    drop(loaded);
                    // Once `loaded` is free: it reads the loaded sessions.
                    self.watch_self_questions(&entry, reopening);
                    // Once `loaded` is free: it takes other sessions' turn
                    // locks.
                    self.tell_untold_ends(&entry);
                    return Ok(entry);
                }
                Err(error) => break 'added error,
            }
        };
        // Never added, so nothing else holds the runtime or queues on it.
        if let Some(engine) = Arc::into_inner(entry.engine).and_then(tokio::sync::Mutex::into_inner)
        {
            match fresh {
                Freshness::New => engine.discard_new().await,
                Freshness::Reopened => engine.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));
        };
        match params.answer {
            rho_protocol::InputAnswer::Secret { value } => {
                secret_answer::answer(&session, params.request, value).await?;
            }
            answer => session.change_inputs(|inputs| inputs.answer(params.request, 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 {})
    }

    /// 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 engine = session.engine.lock().await.take();
            if let Some(engine) = engine {
                engine.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"
            );
        }
        // After the sessions, which close their contexts as they tear down.
        if let Some(browsers) = &self.browsers {
            browsers.close().await;
        }
        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)
    }
}

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