rho-coding-agent 3.12.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
//! Tells a session of the turns it starts in other sessions through session
//! control (the `sessions` tool's `new` and `prompt`): such a turn that
//! ends, or asks a question, leaves a notice in the starter's `PeerInbox`
//! (see `app::peer_sessions`, which says what the inbox keeps and forgets).
//! The starter's turn under way takes it at its next boundary; an idle
//! starter is woken by a turn the daemon starts for it (see `idle_wake`), as
//! for its finished background work, with no client attached.
//!
//! Only a session the daemon takes turns for has an inbox, one opened with
//! `idle_wake: turn` or started as an agent that reports to its starter
//! (see `open`): no other would be woken to take a notice. Its `sessions`
//! tool registers each prompt before it sends it, under the idempotency key
//! the prompt carries, and a turn owes a notice only when its prompt's key
//! claims a registration as the turn starts (see [`Sessions::owe_for_turn`]).
//! So a turn tells the
//! session whose call started it, and nobody else: a turn a person, another
//! caller, or the daemon starts tells nobody, and neither does one a caller
//! without an inbox starts. Every turn start forgets what the last turn
//! owed. A prompt whose turn ends before it began reports that end itself,
//! and tells nobody. A turn that owes a notice keeps its starter loaded and
//! active (see `unload` and `settle`), so the notice finds it.
//!
//! A session started as an agent that reports to its starter (see
//! `app::starter_report`) is the exception: every turn of it owes its
//! starter, whoever started the turn, and tells nobody else, a prompt's
//! claim being used up. A turn that answered tells its report, if it made
//! one, and nothing otherwise: the notice then stays owed between turns,
//! keeping the starter active, and is told as the session stopping without
//! a report should it settle with nothing left to wake it (see
//! `LoadedSession::stop_unreported`). A turn that ended any other way
//! tells as it ended, since the session could not report. What such a
//! session owes between turns is on its job (`jobs::OwedWord`), so a
//! restart keeps it.
//!
//! The notice lives in the daemon's memory, so the turn's job also records
//! whom it owes one, until a turn of the starter took it (see
//! `peer_sessions::Receipt`). A turn the daemon's end interrupts, as a
//! restart's does, ends with its notice untold, since the daemon delivers
//! nothing while it stops; so does a turn that continues it and ends
//! before its starter loads, and a notice the starter unloaded before
//! taking. Each tells the starter as a client that takes the daemon's
//! turns loads it, as rho-ui and the TUI do as they show it (see
//! [`Sessions::tell_untold_ends`]), until a turn of it takes the notice:
//! exactly one notice delivered of each such turn. No restart
//! continues the turn of a session `sessions new` opened, which no client
//! attaches to continue, even one the daemon takes turns for (see
//! `restart_resume`): its starter decides whether to prompt it again.
//!
//! Of what a turn waits for, only questions the starter may answer are
//! told, as each opens and never again: only a person can answer an
//! approval, or a question for the user alone, as an MCP server's
//! elicitation is, and the person's client shows it. Nor is a starter that
//! may not answer told of any question: one that did not start the asking
//! session, or may not act on sessions (`JobRegistry::may_answer`). It
//! hears only of the turn's end. A question told is held by the starter
//! (`held_by`) as it opens, so clients show it as asking the starter rather
//! than needing the user, until a turn of the starter ends or the starter
//! is gone: then each such question still open moves on (see
//! `held_questions`). A question's notice stays until a turn takes it,
//! though the question may close first; the notice says it may have been
//! answered.
//!
//! The starter is told even while its turn waits on the same session with
//! `sessions wait`: that wait runs on a connection of its own, which the
//! daemon cannot tell from another caller's.

use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};

use rho_protocol::{self as wire, IdempotencyKey};
use rho_sdk::SessionId;

use super::{
    super::jobs::{Delivered, JobId, JobRegistry, OwedWord, Owing, TurnEnd, UntoldEnd, WordChange},
    held_questions::Kept,
    LoadedSession, Sessions,
};
use crate::app::{
    peer_sessions::{Expectation, PeerInbox, PeerTurnEnd, Receipt},
    session_runtime::SessionRuntime,
    starter_report::{ReportKind, StarterReport},
};

/// A loaded session's part in telling sessions of the turns they started.
pub(super) struct PeerWake {
    /// The session this is part of, as the questions it holds name it.
    owner: wire::SessionId,
    /// Where notices of the turns this session starts arrive, when its
    /// client asked for daemon turns.
    inbox: Option<PeerInbox>,
    /// What the turn under way owes the session whose call started it, or,
    /// for a session that reports to its starter, what it owes its starter
    /// between turns, once a turn ended without a report.
    owed: Mutex<Option<Owed>>,
    /// The questions this session was given since its last turn ended, by
    /// sessions it started or passed up to it (see `held_questions`).
    held: Mutex<Vec<Holding>>,
    /// Where the session's turns mark their reports, when it reports to the
    /// session that started it. What it owes that session between turns is
    /// on its job ([`super::super::jobs::OwedWord`]).
    report: Option<StarterReport>,
}

/// Questions of the session `asking` that a session holds (see
/// [`PeerWake::hold_questions`]).
struct Holding {
    asking: Weak<LoadedSession>,
    requests: Vec<wire::InputRequestId>,
}

/// A notice the session owes, and the session it goes to (see
/// [`PeerWake::owed`]).
pub(super) struct Owed {
    notice: Expectation,
    starter: SessionId,
    session: Weak<LoadedSession>,
}

/// Whether a turn's end tells its starter anything (see
/// [`PeerWake::ended`]).
enum Speaks {
    Yes,
    No,
}

/// What a turn that ended tells the session that started it.
pub(super) enum TurnTells {
    /// This notice, now.
    Tell(Owed, PeerTurnEnd),
    /// Nothing now: no starter loaded is owed the notice, which the turn's
    /// job keeps for the starter's next load, if any is owed, with what the
    /// turn reported.
    Untold { report: Option<ReportKind> },
    /// Nothing, ever, of this turn: a turn of a session that reports to its
    /// starter ended without reporting. Should the session still owe its
    /// starter a report, it owes it between turns now, which keeps the
    /// starter's notice owed (see `Word::Unreported`).
    Silent,
}

impl Owed {
    /// The session whose call started the turn.
    pub(super) fn starter(&self) -> &SessionId {
        &self.starter
    }

    /// Tells the starter that the turn ended as `end`; `receipt` runs once
    /// it is delivered.
    pub(super) fn tell_ended(self, name: Option<String>, end: PeerTurnEnd, receipt: Receipt) {
        self.notice.tell_ended(name, end, receipt);
    }

    /// Tells the starter of the questions `asked`, each a request and what
    /// it asks, naming the asking session `name`.
    pub(super) fn tell_questions(
        &self,
        name: Option<String>,
        asked: Vec<(wire::InputRequestId, String)>,
    ) {
        for (request, ask) in asked {
            self.notice.tell_waiting(name.clone(), request, ask);
        }
    }

    /// Notes that `asking` told the starter of its questions `requests`,
    /// which move on once a turn of the starter ends (see
    /// `held_questions`).
    pub(super) fn note_told(
        &self,
        asking: &Arc<LoadedSession>,
        requests: impl IntoIterator<Item = wire::InputRequestId>,
    ) {
        if let Some(starter) = self.session.upgrade() {
            starter.peer_wake.hold_questions(asking, requests);
        }
    }
}

impl PeerWake {
    /// The part of session `owner`, whose runtime is `runtime`.
    pub(super) fn of(owner: &SessionId, runtime: &SessionRuntime) -> Self {
        Self::new(
            owner,
            runtime.peer_sessions().cloned(),
            runtime.starter_report().cloned(),
        )
    }

    /// For session `owner`, which hears of the turns it starts in `inbox`,
    /// when the daemon wakes it for them, and whose turns mark their
    /// reports in `report`, when it reports to its starter; its turns tell
    /// the session that started them either way.
    pub(super) fn new(
        owner: &SessionId,
        inbox: Option<PeerInbox>,
        report: Option<StarterReport>,
    ) -> Self {
        Self {
            owner: wire::SessionId::new(owner.as_str()),
            inbox,
            owed: Mutex::new(None),
            held: Mutex::new(Vec::new()),
            report,
        }
    }

    /// The session this is part of, as the questions it holds name it.
    pub(super) fn owner(&self) -> &wire::SessionId {
        &self.owner
    }

    fn held(&self) -> MutexGuard<'_, Vec<Holding>> {
        // Only ever pushed to, extended, or taken whole.
        self.held.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Notes that this session holds the questions `requests` of `asking`.
    pub(super) fn hold_questions(
        &self,
        asking: &Arc<LoadedSession>,
        requests: impl IntoIterator<Item = wire::InputRequestId>,
    ) {
        let mut held = self.held();
        let asking = Arc::downgrade(asking);
        match held.iter_mut().find(|held| held.asking.ptr_eq(&asking)) {
            Some(holding) => holding.requests.extend(requests),
            None => held.push(Holding {
                asking,
                requests: requests.into_iter().collect(),
            }),
        }
    }

    /// The questions this session holds, of sessions still loaded, which
    /// it holds no more of: a turn of this session ended (see
    /// `held_questions`).
    pub(super) fn take_held_questions(
        &self,
    ) -> Vec<(Arc<LoadedSession>, Vec<wire::InputRequestId>)> {
        std::mem::take(&mut *self.held())
            .into_iter()
            .filter_map(|held| Some((held.asking.upgrade()?, held.requests)))
            .collect()
    }

    /// The session that started this one, while it is loaded and this
    /// session reports to it and owes it word: where the questions it
    /// leaves unanswered go up (see `held_questions`). Read it before the
    /// turn's end takes what the turn owes.
    pub(super) fn report_target(&self) -> Option<Arc<LoadedSession>> {
        self.report.as_ref()?;
        self.owed().as_ref()?.session.upgrade()
    }

    pub(super) fn inbox(&self) -> Option<&PeerInbox> {
        self.inbox.as_ref()
    }

    /// What the session owes its starter, if anything (see [`Owed`]). Hold
    /// it while telling the starter, so the turn cannot stop owing it in
    /// between.
    pub(super) fn owed(&self) -> MutexGuard<'_, Option<Owed>> {
        // Only ever replaced or taken whole.
        self.owed.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// The turn under way owes nothing: it ended before it began, and its
    /// prompt's answer reports that end. Call under the turn lock.
    pub(super) fn forget(&self) {
        *self.owed() = None;
    }

    /// What the turn that ended as `end` with `outcome` tells the session
    /// that started it, and what the end does to the word the session owes
    /// it, `word` until now; tell it once the job recorded the end. A turn
    /// of a session that reports to its starter tells it the report the
    /// turn marked, if it answered with one, and nothing if it answered
    /// without one: a session that owes a report owes it between turns
    /// then, its notice still owed, and one that owes none tells nothing.
    /// Call under the turn lock.
    pub(super) fn ended(
        &self,
        end: &TurnEnd,
        outcome: Option<&wire::TurnOutcome>,
        word: Option<&OwedWord>,
    ) -> (TurnTells, WordChange) {
        let report = self.report.as_ref().and_then(StarterReport::take);
        let peer_end = turn_end(end, outcome, report);
        let (speaks, change) = match (&peer_end, word, &self.report) {
            (_, _, None) => (Speaks::Yes, WordChange::Keep),
            // Only an answer delivers the report the turn marked.
            (
                PeerTurnEnd::Answered {
                    report: Some(_), ..
                },
                _,
                Some(_),
            ) => (Speaks::Yes, WordChange::Reported),
            (
                PeerTurnEnd::Answered {
                    answer,
                    report: None,
                    ..
                },
                Some(_),
                Some(_),
            ) => (
                Speaks::No,
                WordChange::Answered {
                    answer: answer.clone(),
                },
            ),
            // Having reported, the session owes its starter nothing more
            // until it prompts again.
            (PeerTurnEnd::Answered { report: None, .. }, None, Some(_)) => {
                *self.owed() = None;
                (Speaks::No, WordChange::Keep)
            }
            // Told as it ended, since the session could not report.
            (_, Some(_), Some(_)) => (Speaks::Yes, WordChange::Told),
            (_, None, Some(_)) => (Speaks::Yes, WordChange::Keep),
        };
        let told = match speaks {
            Speaks::No => TurnTells::Silent,
            Speaks::Yes => match self.owed().take() {
                Some(owed) => TurnTells::Tell(owed, peer_end),
                None => TurnTells::Untold {
                    report: peer_end.report(),
                },
            },
        };
        (told, change)
    }

    /// Whether the session, between turns, still owes its starter word of
    /// its work, which keeps it loaded until it tells it (see
    /// [`Self::tell_stopped`]).
    pub(super) fn owes_word(&self) -> bool {
        self.owed().is_some()
    }

    /// Whether the session reports to the session that started it.
    pub(super) fn reports(&self) -> bool {
        self.report.is_some()
    }

    /// Tells the session's starter, while it is loaded to hear, that the
    /// session, `name`d, stopped without a report, should `stop` record
    /// that on its job, returning the starter and the answer its last turn
    /// ended with; the notice's receipt is `receipt`'s for that starter. A
    /// starter not loaded hears as it loads (see
    /// [`Sessions::tell_untold_ends`]). `stop` runs under the session's
    /// owed notice, which a turn that starts replaces only after its job
    /// records it started: so a stop recorded first tells the notice it
    /// stopped, and a turn that starts first leaves `stop` nothing to
    /// stop. Takes its own lock, then the job registry's in `stop`, then
    /// the starter inbox's, a leaf.
    pub(super) fn tell_stopped(
        &self,
        name: Option<String>,
        stop: impl FnOnce() -> Option<(SessionId, String)>,
        receipt: impl FnOnce(SessionId) -> Receipt,
    ) {
        let mut owed = self.owed();
        let Some((starter, answer)) = stop() else {
            return;
        };
        if let Some(Owed { notice, .. }) = owed.take() {
            notice.tell_unreported(name, answer, receipt(starter));
        }
    }
}

impl Drop for PeerWake {
    /// A holder that is gone answers nothing: each question it holds is the
    /// person's.
    fn drop(&mut self) {
        for (asking, requests) in self.take_held_questions() {
            asking.give_held(
                &requests,
                Some(&self.owner),
                /*to*/ None,
                Kept::InMemory,
            );
        }
    }
}

impl Sessions {
    /// Makes `session`'s turn `turn`, which a prompt naming `key` (if any)
    /// just started, owe what it tells to the session it tells, and records
    /// so on the turn's job, so a starter not loaded to hear is told of the
    /// turn's end as it loads. A turn owes the session that registered the
    /// prompt, if one did; but every turn of a session that reports to its
    /// starter owes its starter, whoever started it, so the starter hears
    /// what the session reports from a turn the daemon started too, and the
    /// prompt's claim is used up. Call under `session`'s turn lock, as the
    /// turn starts.
    pub(super) fn owe_for_turn(
        &self,
        session: &LoadedSession,
        turn: &wire::TurnId,
        key: Option<&IdempotencyKey>,
    ) {
        let key = key.filter(|key| PeerInbox::may_claim(key));
        // The turn lock comes before `loaded`, never after.
        let loaded = self.loaded();
        let mut claimed = key.and_then(|key| {
            loaded.values().find_map(|loaded| {
                let notice = loaded.peer_wake.inbox()?.claim(session.id.as_str(), key)?;
                Some(Owed {
                    notice,
                    starter: loaded.id.clone(),
                    session: Arc::downgrade(loaded),
                })
            })
        });
        let starter = match &session.peer_wake.report {
            Some(report) => {
                let starter = report.starter();
                // Its starter asks more of it: it owes a report.
                if claimed
                    .as_ref()
                    .is_some_and(|owed| owed.starter == *starter)
                {
                    self.jobs.owe_word(&session.job, starter);
                }
                claimed = loaded.get(starter).and_then(|loaded| {
                    Some(Owed {
                        notice: loaded.peer_wake.inbox()?.expect(session.id.as_str()),
                        starter: loaded.id.clone(),
                        session: Arc::downgrade(loaded),
                    })
                });
                Some(starter.clone())
            }
            None => claimed.as_ref().map(|owed| owed.starter.clone()),
        };
        drop(loaded);
        if let Some(starter) = &starter {
            self.jobs.owe_starter(&session.job, turn, starter);
        }
        // Replaced whole, so a reporting session's starter is owed
        // throughout; any other turn owes nothing but what it claimed.
        *session.peer_wake.owed() = claimed;
    }

    /// Tells `starter`, a session just loaded, of each turn it started that
    /// ended and whose end it has yet to take: an earlier daemon's end
    /// interrupted it, which that daemon could not tell, as the notice
    /// lived in its memory; it continued that interrupted turn and ended
    /// while `starter` was not loaded; or its notice was never delivered
    /// before `starter` unloaded or the daemon ended. And of each session
    /// that reports to `starter` and stopped without the report it owes:
    /// one not loaded, which a daemon's end stopped, or that settled while
    /// `starter` was not loaded to hear. So a lead that loads after a
    /// restart hears once of each workstream the restart stopped.
    ///
    /// A turn that continues one, or runs, or a session that reports to
    /// `starter` and still works on what it owes, owes `starter` from here
    /// on, as if `starter` had been loaded as it started. Only a session
    /// whose client takes the daemon's turns hears, as of any started
    /// turn's end; one that loads otherwise is told when it next loads with
    /// such a client. Call holding no lock: it takes each loaded session's
    /// turn lock in turn, the lock a turn ends under, so each turn either
    /// ended before and is told here, or tells as it ends.
    pub(super) fn tell_untold_ends(&self, starter: &Arc<LoadedSession>) {
        let Some(inbox) = starter.peer_wake.inbox() else {
            return;
        };
        let others: Vec<Arc<LoadedSession>> = self
            .loaded()
            .values()
            .filter(|loaded| loaded.id != starter.id)
            .cloned()
            .collect();
        let owe_starter = |session: &LoadedSession| {
            let mut owed = session.peer_wake.owed();
            if owed.is_none() {
                *owed = Some(Owed {
                    notice: inbox.expect(session.id.as_str()),
                    starter: starter.id.clone(),
                    session: Arc::downgrade(starter),
                });
            }
        };
        let (mut ends, mut stops) = (Vec::new(), Vec::new());
        for session in &others {
            let _turn = session.turn();
            // It tells of its own end once it continues.
            if self.restart_resumes.waits(&session.id) {
                continue;
            }
            let ended = match self.jobs.owing(&session.job, &starter.id) {
                Owing::Nothing => false,
                Owing::Running => {
                    owe_starter(session);
                    continue;
                }
                Owing::Ended(end) => {
                    ends.push(end);
                    true
                }
            };
            let owes = self
                .jobs
                .word_of(&session.job)
                .is_some_and(|owed| owed.starter == starter.id);
            if !owes {
                continue;
            }
            // Still at work on it, or news may wake it to, unless the end
            // told here, of a turn a daemon's end interrupted, is its word:
            // it tells as it reports or stops.
            if !ended && session.peer_wake.reports() && !session.nothing_may_wake() {
                owe_starter(session);
            } else if let Some(stopped) = self.jobs.stop_word(&session.job, &starter.id) {
                stops.push(stopped);
            }
        }
        // The rest are not loaded, so none ends a turn meanwhile. A turn
        // that will continue tells of its own end instead, and a session
        // pull request news reopens may still report.
        let skip = |session: &SessionId| {
            others.iter().any(|other| other.id == *session) || self.restart_resumes.waits(session)
        };
        ends.extend(self.jobs.untold_ends(&starter.id, skip));
        stops.extend(self.jobs.stop_words(&starter.id, |session| {
            skip(session) || self.pull_requests.keeps_opening(session)
        }));
        // Stops first: an end of the same session replaces its stop, as the
        // fuller word, and both receipts run once it is delivered.
        for stopped in stops {
            let receipt = receipt_on(
                &self.jobs,
                stopped.job,
                Delivered::Stopped {
                    starter: starter.id.clone(),
                },
            );
            inbox.tell_stopped(
                stopped.session.as_str(),
                stopped.title,
                stopped.stop,
                receipt,
            );
        }
        for end in ends {
            self.tell_untold(inbox, &starter.id, end);
        }
    }

    /// Tells `inbox`, `starter`'s, of `end`, a turn's end it has yet to
    /// take, which the turn's job keeps until the notice is delivered.
    pub(super) fn tell_untold(&self, inbox: &PeerInbox, starter: &SessionId, end: UntoldEnd) {
        let peer_end = end.peer_end();
        let delivered = Delivered::End {
            turn: end.turn,
            starter: starter.clone(),
        };
        let receipt = receipt_on(&self.jobs, end.job, delivered);
        inbox.tell_ended(end.session.as_str(), end.title, peer_end, receipt);
    }

    /// Makes `session`'s turn `turn`, which continues one a restart
    /// interrupted, owe its end to `starter`, whose call started the
    /// interrupted turn: on the turn's job, and in memory when `starter` is
    /// loaded and hears of its starts. A starter not loaded then hears of
    /// the end as it loads (see [`Self::tell_untold_ends`]). Call under
    /// `session`'s turn lock, right after the turn started.
    pub(super) fn carry_starter(
        &self,
        session: &LoadedSession,
        turn: &wire::TurnId,
        starter: SessionId,
    ) {
        let owed = self.loaded().get(&starter).and_then(|loaded| {
            Some(Owed {
                notice: loaded.peer_wake.inbox()?.expect(session.id.as_str()),
                starter: loaded.id.clone(),
                session: Arc::downgrade(loaded),
            })
        });
        self.jobs.owe_starter(&session.job, turn, &starter);
        if owed.is_some() {
            *session.peer_wake.owed() = owed;
        }
    }
}

impl LoadedSession {
    /// What runs once the notice `delivered` of the session's job reaches
    /// its starter: the job no longer keeps it to tell again (see
    /// `jobs::Delivered`).
    pub(super) fn receipt(&self, delivered: Delivered) -> Receipt {
        receipt_on(&self.jobs, self.job.clone(), delivered)
    }
}

/// What runs once the notice `delivered` of job `job` reaches its starter.
fn receipt_on(jobs: &Arc<JobRegistry>, job: JobId, delivered: Delivered) -> Receipt {
    let jobs = Arc::downgrade(jobs);
    Receipt::new(move || {
        if let Some(jobs) = jobs.upgrade() {
            jobs.delivered(&job, &delivered);
        }
    })
}

/// The questions `events`, those of one change of the session's input
/// requests, asked: each request and what it asks. Each request opens once.
/// The caller leaves out those for the user alone, which the wire does not
/// mark.
pub(super) fn asked_questions(
    events: &[wire::SessionEvent],
) -> Vec<(wire::InputRequestId, String)> {
    events
        .iter()
        .filter_map(|event| match event {
            wire::SessionEvent::InputRequested { request } => match &request.ask {
                wire::Ask::Question(question) => Some((request.id, ask_of(question))),
                // Only a person answers these, and their client shows them.
                wire::Ask::Approval(_) | wire::Ask::PlanApproval(_) | wire::Ask::Secret(_) => None,
                // `Unknown`, or an ask a newer protocol adds (`Ask` is
                // non-exhaustive).
                _ => None,
            },
            _ => None,
        })
        .collect()
}

/// Marks each request of `events` that `told` names as held by `starter`,
/// which was told of it.
pub(super) fn mark_told(
    events: &mut [wire::SessionEvent],
    told: &[(wire::InputRequestId, String)],
    starter: &SessionId,
) {
    for event in events {
        if let wire::SessionEvent::InputRequested { request } = event {
            if told.iter().any(|(id, _)| *id == request.id) {
                request.set_held_by(Some(wire::SessionId::new(starter.as_str())));
            }
        }
    }
}

/// What `question` asks: its title, else its first question's prompt.
pub(super) fn ask_of(question: &wire::QuestionAsk) -> String {
    std::iter::once(&question.title)
        .chain(question.questions.iter().map(|asked| &asked.prompt))
        .find(|text| !text.trim().is_empty())
        .cloned()
        .unwrap_or_default()
}

impl UntoldEnd {
    /// How the turn's end reads to its starter, with the report it made,
    /// if it made one. A turn of a session that reports to its starter that
    /// answered without one never goes untold (see [`TurnTells::Silent`]).
    pub(super) fn peer_end(&self) -> PeerTurnEnd {
        turn_end(&self.end, self.outcome.as_ref(), self.report)
    }
}

/// How a turn that ended as `end` with `outcome`, having marked `report`,
/// reads to its starter. Only an answer carries the report: a turn that
/// ended any other way could not finish reporting, so it tells as it ended.
fn turn_end(
    end: &TurnEnd,
    outcome: Option<&wire::TurnOutcome>,
    report: Option<ReportKind>,
) -> PeerTurnEnd {
    match end {
        TurnEnd::Completed => match outcome {
            Some(wire::TurnOutcome::Answered { text, stop }) => PeerTurnEnd::Answered {
                answer: text.clone(),
                stop: *stop,
                report,
            },
            Some(wire::TurnOutcome::MaxSteps { text }) => PeerTurnEnd::StepLimit {
                reply: text.clone(),
            },
            // A completed turn records one of those two, unless the daemon
            // stops, when it records none (see `DaemonView::end`).
            Some(_) | None => PeerTurnEnd::Interrupted,
        },
        TurnEnd::Failed(error) => PeerTurnEnd::Failed {
            error: error.clone(),
        },
        TurnEnd::Cancelled => PeerTurnEnd::Cancelled,
        TurnEnd::TimedOut { timeout_ms } => PeerTurnEnd::TimedOut {
            timeout_ms: *timeout_ms,
        },
        TurnEnd::Interrupted => PeerTurnEnd::Interrupted,
    }
}

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