Skip to main content

muse_code_sdk/session/
submit.rs

1//! Turn submission: `send_user_turn`, `unqueue_turn`, and the shared
2//! `turn/start` path that `resolve_reconnect` also resends through.
3
4use std::sync::Arc;
5
6use super::{PendingCommandGuard, Session, SessionInner, SessionOpening};
7use crate::client::{FacadeError, FacadeResult, lock};
8use crate::errors::ProtocolError;
9use crate::msp::{
10    CommandStatus, IfBusy, LastTurn, ReasoningEffort, TurnInputPart, TurnStartDisposition,
11    TurnStartParams, TurnStartResult, TurnUnqueueParams, TurnUnqueueResult,
12};
13use crate::turn::{Turn, TurnHandle};
14
15/// What one `turn/start` sends.
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
17pub struct SendUserTurnOptions {
18    /// The prompt as ordered content parts; the server requires at least one.
19    pub input: Vec<TurnInputPart>,
20    /// What to do when a turn is already running; `None` sends nothing, and
21    /// the server queues the turn.
22    pub if_busy: Option<IfBusy>,
23    /// The prompt's transcript form, never shown to the model.
24    pub display_text: Option<String>,
25    /// This turn's reasoning tier; `None` uses the session's current tier.
26    pub reasoning_effort: Option<ReasoningEffort>,
27    // No `tokenBudget`: the member is experimental-gated (v1
28    // membership unruled) and this SDK serves the stable surface only.
29    /// Replaces the session's workspace roots from this turn on; `None` keeps
30    /// them.
31    pub workspace_roots: Option<Vec<String>>,
32}
33
34impl Session {
35    /// Sends one `turn/start` under a fresh command id and returns the turn
36    /// it started or queued, or the running turn it steered into. A call
37    /// refused at entry (session discarded, client closed, transport
38    /// already ended) records nothing, so [`Session::pending`] does not
39    /// list it. Once recorded, on a durable client only a server refusal
40    /// ([`MuseError::Msp`](crate::errors::MuseError::Msp)) drops the
41    /// submission; any other failure, a `TransportEnded` included, keeps it
42    /// listed, since the server may have taken the turn. A call the caller
43    /// cancels keeps nothing.
44    ///
45    /// A same-command retry (a command id minted again after a reconnect)
46    /// that the server answers with the turn the resume restates as
47    /// `lastTurn` returns once every notification received before that
48    /// answer has been handed to the session. Its `Turn` settles on that
49    /// turn's terminal if this session applied it before the claim, as it
50    /// does one received before the answer unless a pending view-gap fill
51    /// holds that one back; otherwise it replays the turn's held history and
52    /// settles as [`TurnOutcome::Ended`](crate::turn::TurnOutcome::Ended).
53    pub async fn send_user_turn(&self, options: SendUserTurnOptions) -> FacadeResult<Turn> {
54        self.inner.ensure_available()?;
55        let command_id = self.inner.client.mint_command_id()?;
56        let mut pending_command =
57            PendingCommandGuard::begin(&self.inner, command_id.clone(), options.clone());
58        let result = self
59            .inner
60            .submit_turn(&command_id, options, &mut pending_command)
61            .await?;
62        let ended = self.inner.restated_last_turn(&result.turn_id);
63        if ended.is_some() {
64            // The answer names a turn that ended before the resume. Its own
65            // terminal, if one arrived before this answer, settles the retry,
66            // so every notification received first is handed over before the
67            // claim looks for it. A cancel while waiting keeps nothing, like
68            // any other cancel of this call.
69            pending_command.forget_submission_on_cancel();
70            self.inner.client.notifications_received_applied().await;
71            pending_command.keep_submission();
72        }
73        Ok(self
74            .inner
75            .follow_submitted_turn(&command_id, &result, ended))
76    }
77
78    /// Reclaims a queued turn before it launches (`turn/unqueue`).
79    ///
80    /// The result is admission only: the queued [`Turn`] settles as
81    /// [`TurnOutcome::Unqueued`](crate::turn::TurnOutcome::Unqueued) when the
82    /// server's `turn/unqueued` arrives. A turn that already launched is
83    /// refused with [`MuseError::Msp`](crate::errors::MuseError::Msp) and keeps
84    /// running to its terminal. Pass `turn_id` exactly as the server minted it
85    /// ([`Turn::turn_id`] or snapshot `queuedTurns`): the echoed id is compared
86    /// byte for byte.
87    pub async fn unqueue_turn(&self, turn_id: &str) -> FacadeResult<TurnUnqueueResult> {
88        self.inner.ensure_available()?;
89        let command_id = self.inner.client.mint_command_id()?;
90        let params = TurnUnqueueParams {
91            session_id: self.inner.session_id.clone(),
92            command_id: command_id.clone(),
93            turn_id: turn_id.to_owned(),
94        };
95        let result = self
96            .inner
97            .client
98            .command::<_, TurnUnqueueResult>("turn/unqueue", &params)
99            .await?;
100        if result.command_id != command_id {
101            return Err(ProtocolError::new(
102                format!(
103                    "turn/unqueue echoed command id {}, expected {command_id}",
104                    result.command_id
105                ),
106                None,
107            )
108            .into());
109        }
110        if result.turn_id != turn_id {
111            return Err(ProtocolError::new(
112                format!(
113                    "turn/unqueue echoed turn id {}, expected {turn_id}",
114                    result.turn_id
115                ),
116                None,
117            )
118            .into());
119        }
120        require_accepted("turn/unqueue", &result.status)?;
121        Ok(result)
122    }
123}
124
125impl SessionInner {
126    pub(super) fn ensure_available(&self) -> FacadeResult<()> {
127        if lock(&self.state).discarded {
128            Err(FacadeError::SessionDiscarded(self.session_id.clone()))
129        } else {
130            Ok(())
131        }
132    }
133
134    /// Sends one `turn/start` under `command_id` and checks the answer's echo.
135    pub(super) async fn submit_turn(
136        self: &Arc<Self>,
137        command_id: &str,
138        options: SendUserTurnOptions,
139        pending_command: &mut PendingCommandGuard,
140    ) -> FacadeResult<TurnStartResult> {
141        let params = TurnStartParams {
142            session_id: self.session_id.clone(),
143            command_id: command_id.to_owned(),
144            input: options.input,
145            if_busy: options.if_busy,
146            display_text: options.display_text,
147            reasoning_effort: options.reasoning_effort,
148            // Experimental-gated: never sent by this SDK.
149            token_budget: None,
150            // No shell submit in SendUserTurnOptions: this SDK never
151            // sends a `turn/start.userShell` member.
152            user_shell: None,
153            workspace_roots: options.workspace_roots,
154        };
155        let result = self
156            .client
157            .command::<_, TurnStartResult>("turn/start", &params)
158            .await;
159        let result = match result {
160            Ok(result) => result,
161            Err(error) => {
162                match error {
163                    FacadeError::TransportEnded | FacadeError::Transport(_) => {
164                        pending_command.retain_for_retry();
165                    }
166                    // Only a server refusal answers the submission; any other
167                    // failure may follow a written intake.
168                    FacadeError::Msp(_) => {}
169                    _ => pending_command.keep_submission(),
170                }
171                return Err(error);
172            }
173        };
174        pending_command.keep_submission();
175        if result.command_id != command_id {
176            return Err(ProtocolError::new(
177                format!(
178                    "turn/start echoed command id {}, expected {command_id}",
179                    result.command_id
180                ),
181                None,
182            )
183            .into());
184        }
185        require_accepted("turn/start", &result.status)?;
186        Ok(result)
187    }
188
189    /// Follows an answered `turn/start`. `ended` is the resume's `lastTurn`
190    /// when the answer names it and the caller has waited for the
191    /// notifications received before the answer; `resolve_reconnect`, which
192    /// answers that case itself, passes `None`.
193    pub(super) fn follow_submitted_turn(
194        self: &Arc<Self>,
195        command_id: &str,
196        result: &TurnStartResult,
197        ended: Option<LastTurn>,
198    ) -> Turn {
199        if let Some(last_turn) = ended {
200            return self.follow_ended_turn(command_id, result, last_turn);
201        }
202        let turn = match &result.disposition {
203            TurnStartDisposition::Started | TurnStartDisposition::Queued => {
204                self.submitted_turn(&result.turn_id, command_id.to_owned())
205            }
206            TurnStartDisposition::Steered => self.claim_turn(&result.turn_id),
207            // A disposition this build does not know: follow the turn the
208            // server named, as the submission's own only when it says it
209            // started a new one; otherwise join it the way `Steered` does.
210            TurnStartDisposition::Unknown(_) if result.started_new_turn => {
211                self.submitted_turn(&result.turn_id, command_id.to_owned())
212            }
213            TurnStartDisposition::Unknown(_) => self.claim_turn(&result.turn_id),
214        };
215        lock(&self.state).acknowledge_submission(command_id, &result.turn_id);
216        turn
217    }
218
219    /// Follows an answer that names the turn the resume restates as `lastTurn`,
220    /// under one session-state guard, so no notification can land between
221    /// reading the kept route, the claim and the settle.
222    fn follow_ended_turn(
223        self: &Arc<Self>,
224        command_id: &str,
225        result: &TurnStartResult,
226        last_turn: LastTurn,
227    ) -> Turn {
228        let mut state = lock(&self.state);
229        if let Some(handle) = state.last_turn_settled.clone() {
230            // This session already retired the turn's route and keeps it past
231            // the alias hold. Its own terminal settles the retry, even after
232            // a failed event source. A local fault that retired it applies no
233            // terminal, so the retry settles from the resume's restatement,
234            // unless the event source has failed: then it keeps a failure,
235            // through the claim below, as for any turn.
236            let turn = if handle.has_server_outcome() {
237                Some(handle.turn_with_keepalive(Arc::clone(self)))
238            } else if state.event_source_failure.is_none() {
239                Some(self.ended_turn(&handle, last_turn.clone()))
240            } else {
241                None
242            };
243            if let Some(turn) = turn {
244                // Settled from server evidence, however long ago its route
245                // retired.
246                state.forget_submission(command_id);
247                return turn;
248            }
249        }
250        let turn = self.claim_turn_locked(&mut state, &result.turn_id);
251        let turn = match &result.disposition {
252            TurnStartDisposition::Started | TurnStartDisposition::Queued => {
253                turn.with_discard(command_id.to_owned())
254            }
255            TurnStartDisposition::Steered | TurnStartDisposition::Unknown(_) => turn,
256        };
257        // No terminal for it was applied before this claim, and the resume says
258        // it already ended: settle the route the claim opened from the resume's
259        // own restatement. A claim the session refused opens no route, so its
260        // failure stands.
261        state.settle_and_retire_turn(&result.turn_id, |handle| handle.settle_ended(last_turn));
262        state.acknowledge_submission(command_id, &result.turn_id);
263        turn
264    }
265
266    /// A turn settled `Ended` from `last_turn`, carrying what `retired` held:
267    /// its items, in order, and whether it saw `turn/started`.
268    fn ended_turn(self: &Arc<Self>, retired: &TurnHandle, last_turn: LastTurn) -> Turn {
269        let ended = TurnHandle::new(&last_turn.turn_id);
270        if retired.observed_start() {
271            ended.mark_started();
272        }
273        for item in retired.held_items() {
274            ended.push_item(item);
275        }
276        ended.settle_ended(last_turn);
277        ended.turn_with_keepalive(Arc::clone(self))
278    }
279
280    /// The resume's `lastTurn`, when it names `turn_id`.
281    pub(super) fn restated_last_turn(&self, turn_id: &str) -> Option<LastTurn> {
282        match &self.opening {
283            SessionOpening::Resume(result) => result
284                .last_turn
285                .as_ref()
286                .filter(|last_turn| last_turn.turn_id == turn_id)
287                .cloned(),
288            SessionOpening::Start(_) => None,
289        }
290    }
291
292    pub(super) fn finish_command(&self, command_id: &str) {
293        lock(&self.state).finish_pending_command(command_id);
294    }
295}
296
297/// An ack whose status is not `accepted` does not say the host took the
298/// command, so the call fails as a protocol error. Only a newer host's word
299/// reaches the `Unknown` arm, so its message says to update the SDK, because
300/// an app may show it as the turn's failure; the match is exhaustive, so a
301/// status this SDK learns later cannot fall into that message.
302pub(in crate::session) fn require_accepted(
303    method: &str,
304    status: &CommandStatus,
305) -> Result<(), ProtocolError> {
306    match status {
307        CommandStatus::Accepted => Ok(()),
308        CommandStatus::Unknown(word) => Err(ProtocolError::new(
309            format!(
310                "{method} answered status {word:?}, which this SDK does not know: the host is \
311                 newer than this SDK, so update the SDK"
312            ),
313            None,
314        )),
315    }
316}