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
//! 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 opened with `idle_wake: turn` has an inbox: 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::claim_starter`]). 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.
//!
//! 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 marked
//! `told_starter` 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 is the person's
//! again (`return_told`). 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::TurnEnd, LoadedSession, Sessions};
use crate::app::{
peer_sessions::{Expectation, PeerInbox, PeerTurnEnd},
session_runtime::SessionRuntime,
};
/// A loaded session's part in telling sessions of the turns they started.
pub(super) struct PeerWake {
/// 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.
owed: Mutex<Option<Owed>>,
/// The sessions this one started that told it of a question since its
/// last turn ended.
told: Mutex<Vec<Weak<LoadedSession>>>,
}
/// A notice the turn under way owes, and the session it goes to.
pub(super) struct Owed {
notice: Expectation,
starter: SessionId,
session: Weak<LoadedSession>,
}
impl Owed {
/// The session whose call started the turn.
pub(super) fn starter(&self) -> &SessionId {
&self.starter
}
/// 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 a question, which returns
/// to the person once a turn of the starter ends.
pub(super) fn note_told(&self, asking: &Arc<LoadedSession>) {
if let Some(starter) = self.session.upgrade() {
let mut told = starter.peer_wake.told();
if !told.iter().any(|told| told.ptr_eq(&Arc::downgrade(asking))) {
told.push(Arc::downgrade(asking));
}
}
}
}
impl PeerWake {
pub(super) fn of(runtime: &SessionRuntime) -> Self {
Self::new(runtime.peer_sessions().cloned())
}
/// For a session that hears of the turns it starts in `inbox`, when the
/// daemon wakes it for them; its turns tell the session that started
/// them either way.
pub(super) fn new(inbox: Option<PeerInbox>) -> Self {
Self {
inbox,
owed: Mutex::new(None),
told: Mutex::new(Vec::new()),
}
}
fn told(&self) -> MutexGuard<'_, Vec<Weak<LoadedSession>>> {
// Only ever pushed to or taken whole.
self.told.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Gives the person back the questions the sessions this one started
/// told it of and are still open: a turn of this session ended without
/// answering them, or this session is gone.
pub(super) fn return_told(&self) {
let told = std::mem::take(&mut *self.told());
for asking in told.iter().filter_map(Weak::upgrade) {
asking.feed.return_told_questions();
}
}
pub(super) fn inbox(&self) -> Option<&PeerInbox> {
self.inbox.as_ref()
}
/// What the turn under way owes its starter, if anything. 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 just started, and its prompt
/// claims what it owes after, or it ended before it began. 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, if it owes it a notice; tell it once the job
/// recorded the end. Call under the turn lock.
pub(super) fn ended(
&self,
end: &TurnEnd,
outcome: Option<&wire::TurnOutcome>,
) -> Option<(Expectation, PeerTurnEnd)> {
let owed = self.owed().take()?;
Some((owed.notice, turn_end(end, outcome)))
}
}
impl Drop for PeerWake {
/// A starter that is gone answers nothing.
fn drop(&mut self) {
self.return_told();
}
}
impl Sessions {
/// Makes `session`'s turn, which a prompt naming `key` just started,
/// owe a notice to the session that registered that prompt, if one
/// did. Call under `session`'s turn lock, right after the turn started.
pub(super) fn claim_starter(&self, session: &LoadedSession, key: Option<&IdempotencyKey>) {
let Some(key) = key.filter(|key| PeerInbox::may_claim(key)) else {
return;
};
// The turn lock comes before `loaded`, never after.
let owed = self.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),
})
});
if owed.is_some() {
*session.peer_wake.owed() = owed;
}
}
}
/// 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 told to its starter.
pub(super) fn mark_told(
events: &mut [wire::SessionEvent],
told: &[(wire::InputRequestId, String)],
) {
for event in events {
if let wire::SessionEvent::InputRequested { request } = event {
if told.iter().any(|(id, _)| *id == request.id) {
request.told_starter = true;
}
}
}
}
/// What `question` asks: its title, else its first question's prompt.
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()
}
/// How a turn that ended as `end` with `outcome` reads to its starter.
fn turn_end(end: &TurnEnd, outcome: Option<&wire::TurnOutcome>) -> PeerTurnEnd {
match end {
TurnEnd::Completed => match outcome {
Some(wire::TurnOutcome::Answered { text, stop }) => PeerTurnEnd::Answered {
answer: text.clone(),
stop: *stop,
},
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;